OXYGENHUB

Coverage / crates/oxy-core/src/repo/checkout.rs 91.9%

464 of 505 lines run, 87 of 97 functions · run #391 on push-notes · run missed

1
//! Moving the working copy to another state (spec §12.3, §7.7).
2
3
use super::*;
4
5
#[derive(Debug, Default, Clone, PartialEq, Eq)]
6
pub struct CheckoutReport {
7
    pub written: usize,
8
    pub removed: usize,
9
    /// The first files removed, to name them (oxygen#102).
10
    pub removed_paths: Vec<String>,
11
    pub conflicted: bool,
12
    /// Nested repositories that could not be moved, and other remarks.
13
    pub notes: Vec<String>,
14
    /// How many changes of the state left behind the new one lacks.
15
    pub lacks: usize,
16
    /// Union files whose adjacent insertions were settled by keeping both
17
    /// sides (oxygen#145).
18
    pub kept_both: Vec<KeptBoth>,
19
}
20
21
/// Text files rendered at a time by a checkout: bounds its memory.
22
const CHECKOUT_BATCH: usize = 2048;
23
24
impl Repo {
25
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
26
    /// the working directory is rewritten to that state and a fresh
27
    /// working-copy change is started on it. The bookmark does not move.
28571×
    pub fn checkout(
29571×
        &self,
30571×
        heads: &[ChangeHash],
31571×
        discard: bool,
32571×
        command: &str,
33571×
    ) -> Result<CheckoutReport> {
34571×
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
35571×
    }
36
37
    /// [`Repo::checkout`], leaving the nested repositories at
38
    /// `keep_subrepos` as they are (their pins are carried work).
39576×
    pub(crate) fn checkout_keeping(
40576×
        &self,
41576×
        heads: &[ChangeHash],
42576×
        discard: bool,
43576×
        command: &str,
44576×
        keep_subrepos: &BTreeSet<String>,
45576×
    ) -> Result<CheckoutReport> {
46576×
        let _wc = self.lock_working_copy()?;
47576×
        let _all = crate::timing::phase("checkout");
48
        // A working copy clean by the manifest needs no snapshot; otherwise a
49
        // status snapshot records what changed, and rewrites the manifest
50
        // with the graph key of every file it proves unchanged. Either way
51
        // the manifest then says, for each file on disk, which graph it
52
        // renders, so the base state itself is not needed (oxygen#35).
53576×
        let changed_paths: Vec<String> = if self.clean_by_manifest()? {
54240×
            Vec::new()
55
        } else {
56336×
            let snap = self.snapshot_status(command)?;
57336×
            self.refuse_dirty(&snap, discard)?;
58334×
            snap.statuses.iter().map(|s| s.path.clone()).collect()
59
        };
60574×
        let (_, wc_now) = self.working_copy()?;
61574×
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
62574×
        let changed: HashSet<&str> = changed_paths.iter().map(String::as_str).collect();
63
        // The target's history; its file graphs are built a batch at a time
64
        // for the files that must be written, and dropped after. It becomes
65
        // the working copy's base, which the state index holds.
66574×
        let mut target = self.load_state_indexed(heads)?;
67574×
        let heads = target.maximal(heads);
68574×
        let tv = crate::timing::phase("checkout: target view");
69574×
        let tview = self.tree_view(&mut target)?;
70574×
        drop(tv);
71574×
        let mut report = CheckoutReport::default();
72
        // Paths this file system cannot hold side by side (spec §7.7).
73574×
        report.notes.extend(
74574×
            self.platform
75574×
                .problems(tview.entries.keys().map(String::as_str)),
76
        );
77574×
        report.conflicted = tview.is_conflicted();
78574×
        report.lacks = self.count_lacking(&wc_now.deps, &target)?;
79
80
        // Remove what the base or the working copy has and the target does
81
        // not. A nested repository is never deleted (spec §7.8).
82574×
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
83574×
        let gone: BTreeSet<&str> = old_manifest
84574×
            .entries
85574×
            .keys()
86574×
            .map(String::as_str)
87574×
            .chain(changed.iter().copied())
887813×
            .filter(|p| !tview.entries.contains_key(*p))
89574×
            .collect();
903074×
        for path in gone {
913074×
            let dir = self.root.join(path);
923074×
            if dir.join(OXY_DIR).exists() || dir.join(".git").exists() {
932×
                report
942×
                    .notes
952×
                    .push(format!("{path}: nested repository left in place"));
962×
                continue;
973072×
            }
983072×
            let full = self.safe_path(path)?;
993072×
            if fs::symlink_metadata(&full).is_err() {
1001×
                continue;
1013071×
            }
1023071×
            fs::remove_file(&full)?;
1033071×
            report.removed += 1;
1043071×
            if report.removed_paths.len() < 5 {
105121×
                report.removed_paths.push(path.to_string());
1062950×
            }
1073071×
            if let Some(parent) = full.parent() {
1083071×
                dirs_to_prune.insert(parent.to_path_buf());
1093071×
            }
110
        }
111
112
        // The manifest after the checkout, built from what is known.
113574×
        let plan = crate::timing::phase("checkout: plan");
114574×
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1155972×
        let hex = |b: &[u8]| *blake3::hash(b).as_bytes();
116
        // Text files to render, attribute files first (the others need them).
117574×
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
11810687×
        for (path, e) in tview.entries.iter() {
11910687×
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
120220×
                continue;
12110467×
            }
122
            // The manifest entry of a file the working copy has not changed,
123
            // with the right executable bit.
12410467×
            let exec_ok =
1254699×
                |m: &prompt::ManifestEntry| !self.platform.exec_bits || m.exec == e.mode.exec;
12610467×
            let entry = old_manifest
12710467×
                .entries
12810467×
                .get(path)
12910467×
                .filter(|m| !changed.contains(path.as_str()) && exec_ok(m));
13010467×
            if e.kind == NodeKind::File && !e.mode.opaque {
131
                // The manifest proves the file on disk equal to the rendering
132
                // of a graph whose key is the target's: nothing to read,
133
                // render or write.
13410411×
                let key = target.graph_key(&e.node);
13510411×
                let proven = |m: &&prompt::ManifestEntry| {
1364665×
                    !is_attributes(path) && key.is_some() && m.graph == key
1374665×
                };
13810411×
                match entry.filter(proven) {
1394463×
                    Some(m) => {
1404463×
                        entries.insert(
1414463×
                            path.clone(),
1424463×
                            FsEntry {
1434463×
                                content_hash: Some(m.hash),
1444463×
                                graph_key: m.graph,
1454463×
                                unchanged: true,
1464463×
                                stat: Some((m.size, m.mtime_ns)),
1474463×
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
1484463×
                            },
1494463×
                        );
1504463×
                    }
1515948×
                    None => texts.push((path.clone(), e.node, e.mode)),
152
                }
15310411×
                continue;
15456×
            }
155
            // Opaque files, symlinks and subrepos: their blobs.
15656×
            let blobs = target.live_blobs(&e.node);
15756×
            if blobs.len() > 1 {
1583×
                report.conflicted = true;
15953×
            }
16056×
            let Some(blob) = blobs.first().copied() else {
1610×
                continue;
162
            };
16356×
            if e.kind == NodeKind::Subrepo {
16413×
                if keep_subrepos.contains(path) {
1651×
                    continue;
16612×
                }
16712×
                let pin = crate::subrepo::Pin::decode(&self.read_blob(&blob)?)?;
16812×
                let sync = self.sync_subrepo(path, &pin, false)?;
1698×
                if matches!(
17012×
                    sync,
171
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
1724×
                ) {
1734×
                    report.written += 1;
1748×
                }
17512×
                report.notes.extend(sync.note(path));
17612×
                continue;
17743×
            }
17843×
            if let Some(m) = entry
17943×
                .filter(|m| e.kind == NodeKind::File && blobs.len() == 1 && m.blob == Some(blob))
180
            {
18117×
                entries.insert(
18217×
                    path.clone(),
18317×
                    FsEntry {
18417×
                        content_hash: Some(m.hash),
18517×
                        blob: (e.kind == NodeKind::File).then_some(blob),
18617×
                        stat: Some((m.size, m.mtime_ns)),
18717×
                        ..FsEntry::new(e.kind, e.mode.exec, Vec::new())
18817×
                    },
189
                );
19017×
                continue;
19126×
            }
19226×
            let bytes = self.read_blob(&blob)?;
19326×
            let full = self.root.join(path);
19426×
            if e.kind == NodeKind::Symlink {
1950×
                let same = fs::read_link(&full)
1960×
                    .is_ok_and(|t| t.to_string_lossy().as_bytes() == bytes.as_slice());
1970×
                if !same {
1980×
                    self.write_symlink(path, &bytes)?;
1990×
                    report.written += 1;
2000×
                }
2010×
                entries.insert(
2020×
                    path.clone(),
2030×
                    FsEntry {
2040×
                        content_hash: Some(hex(&bytes)),
2050×
                        ..FsEntry::new(NodeKind::Symlink, false, Vec::new())
2060×
                    },
207
                );
208
            } else {
20926×
                if !self.same_on_disk(&full, &bytes, e.mode.exec) {
21024×
                    self.write_file(path, &bytes, e.mode.exec)?;
21124×
                    report.written += 1;
2122×
                }
21326×
                entries.insert(
21426×
                    path.clone(),
21526×
                    FsEntry {
21626×
                        content_hash: Some(hex(&bytes)),
21726×
                        blob: (blobs.len() == 1).then_some(blob),
21826×
                        ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
21926×
                    },
220
                );
221
            }
22226×
            for (i, b) in blobs.iter().enumerate().skip(1) {
2232×
                self.write_file(
2242×
                    &format!("{path}.oxy-conflict-{}", i + 1),
2252×
                    &self.read_blob(b)?,
2262×
                    e.mode.exec,
2270×
                )?;
228
            }
229
        }
230
231574×
        drop(plan);
232574×
        let _render = crate::timing::phase("checkout: render and write");
233
        // Render and write text files a batch at a time; attribute files
234
        // come first, since the others' line endings and locks follow them.
23511056×
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
236574×
        let keys: HashMap<NodeId, [u8; 32]> = texts
237574×
            .iter()
2385948×
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
239574×
            .collect();
240574×
        let mut attrs = crate::attributes::Attributes::default();
2415948×
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
242574×
        let mut done = 0usize;
243574×
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
244574×
        if attr_count > 0 {
2456×
            batches.push(&texts[..attr_count]);
246568×
        }
247574×
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
248574×
        for batch in batches {
249
            use rayon::prelude::*;
250427×
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
251
            // A file added once and never edited is its text: no graph.
252427×
            let single: Vec<Option<crate::objects::TextRef>> =
2535948×
                nodes.iter().map(|n| target.single_text(n)).collect();
254427×
            let graphs: Vec<NodeId> = nodes
255427×
                .iter()
256427×
                .zip(&single)
2575948×
                .filter(|(_, s)| s.is_none())
258427×
                .map(|(n, _)| *n)
259427×
                .collect();
260427×
            let mut texts = {
261427×
                let _t = crate::timing::phase("checkout: read single texts");
262427×
                let wanted: Vec<crate::objects::TextRef> =
263427×
                    single.iter().flatten().copied().collect();
264427×
                self.single_texts(&wanted)?.into_iter()
265
            };
266
            {
267427×
                let _t = crate::timing::phase("checkout: build graphs");
268427×
                self.load_graphs_of(&mut target, &graphs)?;
269
            }
270427×
            let rendered: Vec<(Vec<u8>, bool)> = {
271427×
                let _t = crate::timing::phase("checkout: render");
272427×
                let mut out: Vec<Option<(Vec<u8>, bool)>> = single
273427×
                    .iter()
2745948×
                    .map(|s| s.as_ref().and_then(|_| texts.next().map(|t| (t, false))))
275427×
                    .collect();
276427×
                let from_graphs: Vec<(Vec<u8>, bool)> = graphs
277427×
                    .par_iter()
278427×
                    .map(|n| {
279377×
                        let (bytes, m) = target.render_file(n);
280377×
                        (bytes, m.is_conflicted())
281377×
                    })
282427×
                    .collect();
283427×
                let mut from_graphs = from_graphs.into_iter();
2845948×
                for o in out.iter_mut().filter(|o| o.is_none()) {
285377×
                    *o = from_graphs.next();
286377×
                }
287427×
                out.into_iter()
2885948×
                    .map(|o| o.expect("every file rendered"))
289427×
                    .collect()
290
            };
291
            #[cfg(test)]
292
            {
293223×
                let singles: Vec<NodeId> = nodes
294223×
                    .iter()
295223×
                    .zip(&single)
2965368×
                    .filter(|(_, s)| s.is_some())
297223×
                    .map(|(n, _)| *n)
298223×
                    .collect();
299223×
                self.load_graphs_of(&mut target, &singles)?;
3005368×
                for (n, (bytes, _)) in nodes.iter().zip(&rendered) {
3015368×
                    assert_eq!(
302
                        *bytes,
3035368×
                        target.render_file(n).0,
304
                        "a single text is its file's rendering"
305
                    );
306
                }
307
            }
308427×
            target.drop_graphs(&nodes);
309427×
            let _t = crate::timing::phase("checkout: write");
310427×
            if done == 0 && attr_count > 0 {
3116×
                attrs = crate::attributes::Attributes::from_files(
3126×
                    batch
3136×
                        .iter()
3146×
                        .zip(&rendered)
3156×
                        .map(|((p, _, _), (b, _))| (p.as_str(), b.as_slice())),
316
                );
317421×
            }
318427×
            done += batch.len();
319427×
            let on_disk: Vec<Vec<u8>> = batch
320427×
                .iter()
321427×
                .zip(rendered.iter())
3225948×
                .map(|((path, _, _), (bytes, _))| {
3235948×
                    if attrs.lookup(path).eol == Some(crate::attributes::Eol::Crlf) {
3242×
                        crate::attributes::to_crlf(bytes)
325
                    } else {
3265946×
                        bytes.clone()
327
                    }
3285948×
                })
329427×
                .collect();
330
            // Each directory checked (no symlink on the way) and made once,
331
            // then the files compared and written on every core.
332427×
            let mut dirs: BTreeSet<&str> = BTreeSet::new();
3335948×
            for (path, _, _) in batch {
3345948×
                if let Some((dir, _)) = path.rsplit_once('/') {
3355265×
                    dirs.insert(dir);
3365265×
                }
337
            }
338427×
            for dir in dirs {
339174×
                let full = self.safe_path(dir)?;
340173×
                if !full.is_dir() {
341132×
                    if fs::symlink_metadata(&full).is_ok() {
3420×
                        remove_any(&full)?;
343132×
                    }
344132×
                    fs::create_dir_all(&full)?;
34541×
                }
346
            }
3475946×
            for (path, _, _) in batch {
3485946×
                check_path_name(path)?;
349
            }
350426×
            let (root, exec_bits) = (&self.root, self.platform.exec_bits);
351
            // Compared on every core; new files written on every core too,
352
            // but files that exist rewritten one at a time: on ext4,
353
            // rewriting in parallel was six times slower (each truncation
354
            // starts writing back the old blocks).
355426×
            let plans: Vec<Disk> = batch
356426×
                .par_iter()
357426×
                .zip(on_disk.par_iter())
3585946×
                .map(|((path, _, mode), bytes)| {
3595946×
                    compare_on_disk(&root.join(path), bytes, mode.exec, exec_bits)
3605946×
                })
361426×
                .collect();
362426×
            let fresh: Vec<usize> = (0..batch.len())
3635946×
                .filter(|&i| plans[i] == Disk::Absent)
364426×
                .collect();
365426×
            fresh
366426×
                .par_iter()
3675734×
                .map(|&i| write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec))
368426×
                .collect::<std::io::Result<()>>()?;
3695946×
            for (i, plan) in plans.iter().enumerate() {
3705946×
                if *plan == Disk::Differs {
371179×
                    write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec)?;
3725767×
                }
373
            }
3745946×
            report.written += plans.iter().filter(|p| **p != Disk::Same).count();
3755946×
            for (((path, node, mode), (_, conflicted)), on_disk) in
376426×
                batch.iter().zip(rendered).zip(on_disk)
377
            {
3785946×
                let a = attrs.lookup(path);
3795946×
                report.conflicted |= conflicted;
3805946×
                entries.insert(
3815946×
                    path.clone(),
382
                    FsEntry {
3835946×
                        content_hash: Some(hex(&on_disk)),
3845946×
                        graph_key: (!conflicted && a.eol.is_none())
3855946×
                            .then(|| keys.get(node).copied())
3865946×
                            .flatten(),
3875946×
                        ..FsEntry::new(NodeKind::File, mode.exec, Vec::new())
388
                    },
389
                );
390
            }
391
        }
392
        // Lockable files are read-only until locked (spec §18), whether
393
        // written now or left as they were.
39410452×
        for (path, e) in &entries {
39510452×
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
3962×
                let _ = set_readonly(&self.root.join(path), true);
39710450×
            }
398
        }
399
        // Prune directories left empty, deepest first.
400573×
        for d in dirs_to_prune.iter().rev() {
40178×
            let mut d = d.clone();
40296×
            while d != self.root
40321×
                && fs::read_dir(&d)
40421×
                    .map(|mut i| i.next().is_none())
40521×
                    .unwrap_or(false)
406
            {
40718×
                fs::remove_dir(&d)?;
40818×
                let Some(p) = d.parent() else { break };
40918×
                d = p.to_path_buf();
410
            }
411
        }
412
413573×
        drop(_render);
414
        // How the files rendered: which way each graph was ordered, summed
415
        // over every core (`OXY_TIMINGS`).
416573×
        crate::timing::report_totals();
417573×
        let recording = crate::timing::phase("checkout: record");
418573×
        let (op_ref, op) = self.head_op()?;
419573×
        let wc = self.new_working_copy(heads.clone(), "");
420573×
        let wc_hash = self.store.put_change(&wc)?;
421573×
        let mut view = op.view.clone();
422573×
        view.workspaces.insert(self.workspace, wc_hash);
423573×
        self.record_op(&[op_ref], command, view)?;
424573×
        drop(recording);
425573×
        let _t = crate::timing::phase("checkout: manifest");
426
        // The directories the new tree has, with any the old manifest kept
427
        // that still exist (holding only ignored files, say), statted now,
428
        // after the writes: the next check then need not list the tree. A
429
        // directory written just now is within the racy window, so for a
430
        // moment the check lists anyway.
431573×
        if !old_manifest.dirs.is_empty() {
432573×
            let mut dirs: BTreeSet<String> =
433672×
                old_manifest.dirs.iter().map(|(d, _)| d.clone()).collect();
434573×
            dirs.insert(String::new());
43510452×
            for p in entries.keys() {
43610452×
                let mut at = p.as_str();
43710585×
                while let Some((parent, _)) = at.rsplit_once('/') {
4389499×
                    if !dirs.insert(parent.to_string()) {
4399366×
                        break;
440133×
                    }
441133×
                    at = parent;
442
                }
443
            }
444
            use rayon::prelude::*;
445573×
            let root = &self.root;
446573×
            let dirs: Vec<(String, u128)> = dirs
447573×
                .into_par_iter()
448805×
                .filter_map(|d| {
449805×
                    let m = fs::metadata(root.join(&d)).ok().filter(|m| m.is_dir())?;
450787×
                    Some((d, prompt::mtime_ns(&m)))
451805×
                })
452573×
                .collect();
453573×
            let mut dirs = dirs;
454573×
            dirs.sort_unstable();
455573×
            *self.walked_dirs.borrow_mut() = Some((dirs, old_manifest.nested.clone()));
4560×
        }
457573×
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
458573×
        if report.conflicted && !self.bare {
45977×
            report.kept_both = self.settle_unions(command)?;
460496×
        }
461573×
        let _ = self.run_hook(
462573×
            "post-checkout",
463573×
            &format!(
464
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
465875×
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
466
                report.written,
467
                report.removed
468
            ),
469
        );
470573×
        Ok(report)
471576×
    }
472
473
    /// How many changes of the state at `from` the state `to` lacks: a walk
474
    /// down from `from` that stops at what `to` holds.
475574×
    fn count_lacking(&self, from: &[ChangeHash], to: &State) -> Result<usize> {
476574×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
477574×
        let mut stack: Vec<ChangeHash> = from.to_vec();
4781081×
        while let Some(h) = stack.pop() {
479507×
            if to.contains(&h) || !seen.insert(h) {
480402×
                continue;
481105×
            }
482105×
            stack.extend(self.store.get_change_lazy(&h)?.0.deps);
483
        }
484574×
        Ok(seen.len())
485574×
    }
486
487
    /// Refuse to leave uncommitted work behind unless `discard`.
488336×
    pub(crate) fn refuse_dirty(&self, snap: &SnapshotResult, discard: bool) -> Result<()> {
489336×
        if discard || (snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty()) {
490334×
            return Ok(());
4912×
        }
4922×
        let list: Vec<String> = snap
4932×
            .statuses
4942×
            .iter()
4952×
            .take(8)
4963×
            .map(|s| format!("{} {}", status_word(s.status), s.path))
4972×
            .collect();
4982×
        fail(format!(
499
            "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
5002×
            list.join(", "),
5012×
            if snap.statuses.len() > 8 { ", …" } else { "" }
502
        ))
503336×
    }
504
505
    /// Whether the file at `full` already holds `bytes` with this executable
506
    /// bit, so writing it again can be skipped.
50726×
    fn same_on_disk(&self, full: &Path, bytes: &[u8], exec: bool) -> bool {
50826×
        match fs::symlink_metadata(full) {
5098×
            Ok(m) if m.is_file() && m.len() == bytes.len() as u64 => {
5107×
                (!self.platform.exec_bits || is_executable(&m) == exec)
5117×
                    && fs::read(full).is_ok_and(|b| b == bytes)
512
            }
51319×
            _ => false,
514
        }
51526×
    }
516
517
    /// The absolute path for a repository path, refusing anything that would
518
    /// escape the workspace or write through a symlink (spec §7.7).
5193279×
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
5203279×
        let mut full = self.root.clone();
5213279×
        let comps: Vec<&str> = rel.split('/').collect();
5226294×
        for (i, comp) in comps.iter().enumerate() {
5236294×
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
5240×
                return fail(format!("refusing unsafe path {rel:?}"));
5256294×
            }
5266294×
            if i == 0 && *comp == OXY_DIR {
5270×
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
5286294×
            }
5296294×
            if i + 1 < comps.len() {
5303016×
                full.push(comp);
5313016×
                if let Ok(m) = fs::symlink_metadata(&full) {
5323015×
                    if m.file_type().is_symlink() {
5331×
                        return fail(format!(
534
                            "refusing to write through symlink {}",
5351×
                            full.display()
536
                        ));
5373014×
                    }
5381×
                }
5393278×
            } else {
5403278×
                full.push(comp);
5413278×
            }
542
        }
5433278×
        Ok(full)
5443279×
    }
545
54633×
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
54733×
        let full = self.safe_path(rel)?;
54833×
        if let Some(parent) = full.parent() {
54933×
            fs::create_dir_all(parent)?;
5500×
        }
55133×
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
5520×
            remove_any(&full)?;
55333×
        }
55433×
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
5551×
            set_readonly(&full, false)?;
55632×
        }
55733×
        fs::write(&full, bytes)?;
55833×
        set_executable(&full, exec)?;
55933×
        Ok(())
56033×
    }
561
5620×
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
5630×
        let full = self.safe_path(rel)?;
5640×
        if let Some(parent) = full.parent() {
5650×
            fs::create_dir_all(parent)?;
5660×
        }
5670×
        if fs::symlink_metadata(&full).is_ok() {
5680×
            remove_any(&full)?;
5690×
        }
570
        #[cfg(unix)]
571
        {
5720×
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
5730×
            Ok(())
574
        }
575
        #[cfg(not(unix))]
576
        {
577
            // Spec §7.7: without symlink support, write the target as a plain file.
578
            fs::write(&full, target)?;
579
            Ok(())
580
        }
5810×
    }
582
}
583
584
/// How a refusal names a path's change: "removed" is a file of the working
585
/// copy's base that is missing on disk.
5863×
fn status_word(s: ChangeStatus) -> &'static str {
5873×
    match s {
5880×
        ChangeStatus::Added => "added",
5892×
        ChangeStatus::Modified => "modified",
5901×
        ChangeStatus::Removed => "removed",
5910×
        ChangeStatus::Renamed => "renamed",
5920×
        ChangeStatus::ModeChanged => "mode changed",
5930×
        ChangeStatus::ConflictEdited => "conflict edited",
5940×
        ChangeStatus::Resolved => "resolved",
595
    }
5963×
}
597
598
/// Refuse a path that could escape the workspace (spec §7.7): an empty,
599
/// `.` or `..` component, a backslash, or a first component `.oxy`.
6005946×
fn check_path_name(rel: &str) -> Result<()> {
60111211×
    for (i, comp) in rel.split('/').enumerate() {
60211211×
        if comp.is_empty() || comp == "." || comp == ".." || comp.contains('\\') {
6030×
            return fail(format!("refusing unsafe path {rel:?}"));
60411211×
        }
60511211×
        if i == 0 && comp == OXY_DIR {
6060×
            return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
60711211×
        }
608
    }
6095946×
    Ok(())
6105946×
}
611
612
/// A file on disk against what a checkout would write there.
613
#[derive(Clone, Copy, PartialEq, Eq)]
614
enum Disk {
615
    Same,
616
    Differs,
617
    Absent,
618
}
619
620
/// Whether the file at `full` already holds `bytes` with the right
621
/// executable bit. Touches no repository state, so it runs in parallel.
6225946×
fn compare_on_disk(full: &Path, bytes: &[u8], exec: bool, exec_bits: bool) -> Disk {
6235946×
    match fs::symlink_metadata(full) {
62433×
        Ok(m)
625212×
            if m.is_file()
626212×
                && m.len() == bytes.len() as u64
62760×
                && (!exec_bits || is_executable(&m) == exec)
62859×
                && fs::read(full).is_ok_and(|b| b == bytes) =>
629
        {
63033×
            Disk::Same
631
        }
632179×
        Ok(_) => Disk::Differs,
6335734×
        Err(_) => Disk::Absent,
634
    }
6355946×
}
636
637
/// Write a file whose directory exists, replacing whatever is there.
6385913×
fn write_file_at(full: &Path, bytes: &[u8], exec: bool) -> std::io::Result<()> {
6395913×
    match fs::symlink_metadata(full) {
640179×
        Ok(m) if m.is_file() => {
641179×
            if m.permissions().readonly() {
6420×
                set_readonly(full, false)?;
643179×
            }
644
        }
6450×
        Ok(_) => remove_any(full)?,
6465734×
        Err(_) => {}
647
    }
6485913×
    fs::write(full, bytes)?;
6495913×
    set_executable(full, exec)
6505913×
}