OXYGENHUB

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

461 of 502 lines run, 87 of 97 functions · run #379 on main · 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
}
17
18
/// Text files rendered at a time by a checkout: bounds its memory.
19
const CHECKOUT_BATCH: usize = 2048;
20
21
impl Repo {
22
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
23
    /// the working directory is rewritten to that state and a fresh
24
    /// working-copy change is started on it. The bookmark does not move.
25561×
    pub fn checkout(
26561×
        &self,
27561×
        heads: &[ChangeHash],
28561×
        discard: bool,
29561×
        command: &str,
30561×
    ) -> Result<CheckoutReport> {
31561×
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
32561×
    }
33
34
    /// [`Repo::checkout`], leaving the nested repositories at
35
    /// `keep_subrepos` as they are (their pins are carried work).
36566×
    pub(crate) fn checkout_keeping(
37566×
        &self,
38566×
        heads: &[ChangeHash],
39566×
        discard: bool,
40566×
        command: &str,
41566×
        keep_subrepos: &BTreeSet<String>,
42566×
    ) -> Result<CheckoutReport> {
43566×
        let _wc = self.lock_working_copy()?;
44566×
        let _all = crate::timing::phase("checkout");
45
        // A working copy clean by the manifest needs no snapshot; otherwise a
46
        // status snapshot records what changed, and rewrites the manifest
47
        // with the graph key of every file it proves unchanged. Either way
48
        // the manifest then says, for each file on disk, which graph it
49
        // renders, so the base state itself is not needed (oxygen#35).
50566×
        let changed_paths: Vec<String> = if self.clean_by_manifest()? {
51230×
            Vec::new()
52
        } else {
53336×
            let snap = self.snapshot_status(command)?;
54336×
            self.refuse_dirty(&snap, discard)?;
55334×
            snap.statuses.iter().map(|s| s.path.clone()).collect()
56
        };
57564×
        let (_, wc_now) = self.working_copy()?;
58564×
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
59564×
        let changed: HashSet<&str> = changed_paths.iter().map(String::as_str).collect();
60
        // The target's history; its file graphs are built a batch at a time
61
        // for the files that must be written, and dropped after. It becomes
62
        // the working copy's base, which the state index holds.
63564×
        let mut target = self.load_state_indexed(heads)?;
64564×
        let heads = target.maximal(heads);
65564×
        let tv = crate::timing::phase("checkout: target view");
66564×
        let tview = self.tree_view(&mut target)?;
67564×
        drop(tv);
68564×
        let mut report = CheckoutReport::default();
69
        // Paths this file system cannot hold side by side (spec §7.7).
70564×
        report.notes.extend(
71564×
            self.platform
72564×
                .problems(tview.entries.keys().map(String::as_str)),
73
        );
74564×
        report.conflicted = tview.is_conflicted();
75564×
        report.lacks = self.count_lacking(&wc_now.deps, &target)?;
76
77
        // Remove what the base or the working copy has and the target does
78
        // not. A nested repository is never deleted (spec §7.8).
79564×
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
80564×
        let gone: BTreeSet<&str> = old_manifest
81564×
            .entries
82564×
            .keys()
83564×
            .map(String::as_str)
84564×
            .chain(changed.iter().copied())
857804×
            .filter(|p| !tview.entries.contains_key(*p))
86564×
            .collect();
873071×
        for path in gone {
883071×
            let dir = self.root.join(path);
893071×
            if dir.join(OXY_DIR).exists() || dir.join(".git").exists() {
902×
                report
912×
                    .notes
922×
                    .push(format!("{path}: nested repository left in place"));
932×
                continue;
943069×
            }
953069×
            let full = self.safe_path(path)?;
963069×
            if fs::symlink_metadata(&full).is_err() {
971×
                continue;
983068×
            }
993068×
            fs::remove_file(&full)?;
1003068×
            report.removed += 1;
1013068×
            if report.removed_paths.len() < 5 {
102118×
                report.removed_paths.push(path.to_string());
1032950×
            }
1043068×
            if let Some(parent) = full.parent() {
1053068×
                dirs_to_prune.insert(parent.to_path_buf());
1063068×
            }
107
        }
108
109
        // The manifest after the checkout, built from what is known.
110564×
        let plan = crate::timing::phase("checkout: plan");
111564×
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1125963×
        let hex = |b: &[u8]| *blake3::hash(b).as_bytes();
113
        // Text files to render, attribute files first (the others need them).
114564×
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
11510685×
        for (path, e) in tview.entries.iter() {
11610685×
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
117232×
                continue;
11810453×
            }
119
            // The manifest entry of a file the working copy has not changed,
120
            // with the right executable bit.
12110453×
            let exec_ok =
1224693×
                |m: &prompt::ManifestEntry| !self.platform.exec_bits || m.exec == e.mode.exec;
12310453×
            let entry = old_manifest
12410453×
                .entries
12510453×
                .get(path)
12610453×
                .filter(|m| !changed.contains(path.as_str()) && exec_ok(m));
12710453×
            if e.kind == NodeKind::File && !e.mode.opaque {
128
                // The manifest proves the file on disk equal to the rendering
129
                // of a graph whose key is the target's: nothing to read,
130
                // render or write.
13110397×
                let key = target.graph_key(&e.node);
13210397×
                let proven = |m: &&prompt::ManifestEntry| {
1334659×
                    !is_attributes(path) && key.is_some() && m.graph == key
1344659×
                };
13510397×
                match entry.filter(proven) {
1364458×
                    Some(m) => {
1374458×
                        entries.insert(
1384458×
                            path.clone(),
1394458×
                            FsEntry {
1404458×
                                content_hash: Some(m.hash),
1414458×
                                graph_key: m.graph,
1424458×
                                unchanged: true,
1434458×
                                stat: Some((m.size, m.mtime_ns)),
1444458×
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
1454458×
                            },
1464458×
                        );
1474458×
                    }
1485939×
                    None => texts.push((path.clone(), e.node, e.mode)),
149
                }
15010397×
                continue;
15156×
            }
152
            // Opaque files, symlinks and subrepos: their blobs.
15356×
            let blobs = target.live_blobs(&e.node);
15456×
            if blobs.len() > 1 {
1553×
                report.conflicted = true;
15653×
            }
15756×
            let Some(blob) = blobs.first().copied() else {
1580×
                continue;
159
            };
16056×
            if e.kind == NodeKind::Subrepo {
16113×
                if keep_subrepos.contains(path) {
1621×
                    continue;
16312×
                }
16412×
                let pin = crate::subrepo::Pin::decode(&self.read_blob(&blob)?)?;
16512×
                let sync = self.sync_subrepo(path, &pin, false)?;
1668×
                if matches!(
16712×
                    sync,
168
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
1694×
                ) {
1704×
                    report.written += 1;
1718×
                }
17212×
                report.notes.extend(sync.note(path));
17312×
                continue;
17443×
            }
17543×
            if let Some(m) = entry
17643×
                .filter(|m| e.kind == NodeKind::File && blobs.len() == 1 && m.blob == Some(blob))
177
            {
17817×
                entries.insert(
17917×
                    path.clone(),
18017×
                    FsEntry {
18117×
                        content_hash: Some(m.hash),
18217×
                        blob: (e.kind == NodeKind::File).then_some(blob),
18317×
                        stat: Some((m.size, m.mtime_ns)),
18417×
                        ..FsEntry::new(e.kind, e.mode.exec, Vec::new())
18517×
                    },
186
                );
18717×
                continue;
18826×
            }
18926×
            let bytes = self.read_blob(&blob)?;
19026×
            let full = self.root.join(path);
19126×
            if e.kind == NodeKind::Symlink {
1920×
                let same = fs::read_link(&full)
1930×
                    .is_ok_and(|t| t.to_string_lossy().as_bytes() == bytes.as_slice());
1940×
                if !same {
1950×
                    self.write_symlink(path, &bytes)?;
1960×
                    report.written += 1;
1970×
                }
1980×
                entries.insert(
1990×
                    path.clone(),
2000×
                    FsEntry {
2010×
                        content_hash: Some(hex(&bytes)),
2020×
                        ..FsEntry::new(NodeKind::Symlink, false, Vec::new())
2030×
                    },
204
                );
205
            } else {
20626×
                if !self.same_on_disk(&full, &bytes, e.mode.exec) {
20724×
                    self.write_file(path, &bytes, e.mode.exec)?;
20824×
                    report.written += 1;
2092×
                }
21026×
                entries.insert(
21126×
                    path.clone(),
21226×
                    FsEntry {
21326×
                        content_hash: Some(hex(&bytes)),
21426×
                        blob: (blobs.len() == 1).then_some(blob),
21526×
                        ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
21626×
                    },
217
                );
218
            }
21926×
            for (i, b) in blobs.iter().enumerate().skip(1) {
2202×
                self.write_file(
2212×
                    &format!("{path}.oxy-conflict-{}", i + 1),
2222×
                    &self.read_blob(b)?,
2232×
                    e.mode.exec,
2240×
                )?;
225
            }
226
        }
227
228564×
        drop(plan);
229564×
        let _render = crate::timing::phase("checkout: render and write");
230
        // Render and write text files a batch at a time; attribute files
231
        // come first, since the others' line endings and locks follow them.
23211056×
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
233564×
        let keys: HashMap<NodeId, [u8; 32]> = texts
234564×
            .iter()
2355939×
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
236564×
            .collect();
237564×
        let mut attrs = crate::attributes::Attributes::default();
2385939×
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
239564×
        let mut done = 0usize;
240564×
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
241564×
        if attr_count > 0 {
2422×
            batches.push(&texts[..attr_count]);
243562×
        }
244564×
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
245564×
        for batch in batches {
246
            use rayon::prelude::*;
247414×
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
248
            // A file added once and never edited is its text: no graph.
249414×
            let single: Vec<Option<crate::objects::TextRef>> =
2505939×
                nodes.iter().map(|n| target.single_text(n)).collect();
251414×
            let graphs: Vec<NodeId> = nodes
252414×
                .iter()
253414×
                .zip(&single)
2545939×
                .filter(|(_, s)| s.is_none())
255414×
                .map(|(n, _)| *n)
256414×
                .collect();
257414×
            let mut texts = {
258414×
                let _t = crate::timing::phase("checkout: read single texts");
259414×
                let wanted: Vec<crate::objects::TextRef> =
260414×
                    single.iter().flatten().copied().collect();
261414×
                self.single_texts(&wanted)?.into_iter()
262
            };
263
            {
264414×
                let _t = crate::timing::phase("checkout: build graphs");
265414×
                self.load_graphs_of(&mut target, &graphs)?;
266
            }
267414×
            let rendered: Vec<(Vec<u8>, bool)> = {
268414×
                let _t = crate::timing::phase("checkout: render");
269414×
                let mut out: Vec<Option<(Vec<u8>, bool)>> = single
270414×
                    .iter()
2715939×
                    .map(|s| s.as_ref().and_then(|_| texts.next().map(|t| (t, false))))
272414×
                    .collect();
273414×
                let from_graphs: Vec<(Vec<u8>, bool)> = graphs
274414×
                    .par_iter()
275414×
                    .map(|n| {
276381×
                        let (bytes, m) = target.render_file(n);
277381×
                        (bytes, m.is_conflicted())
278381×
                    })
279414×
                    .collect();
280414×
                let mut from_graphs = from_graphs.into_iter();
2815939×
                for o in out.iter_mut().filter(|o| o.is_none()) {
282381×
                    *o = from_graphs.next();
283381×
                }
284414×
                out.into_iter()
2855939×
                    .map(|o| o.expect("every file rendered"))
286414×
                    .collect()
287
            };
288
            #[cfg(test)]
289
            {
290209×
                let singles: Vec<NodeId> = nodes
291209×
                    .iter()
292209×
                    .zip(&single)
2935351×
                    .filter(|(_, s)| s.is_some())
294209×
                    .map(|(n, _)| *n)
295209×
                    .collect();
296209×
                self.load_graphs_of(&mut target, &singles)?;
2975351×
                for (n, (bytes, _)) in nodes.iter().zip(&rendered) {
2985351×
                    assert_eq!(
299
                        *bytes,
3005351×
                        target.render_file(n).0,
301
                        "a single text is its file's rendering"
302
                    );
303
                }
304
            }
305414×
            target.drop_graphs(&nodes);
306414×
            let _t = crate::timing::phase("checkout: write");
307414×
            if done == 0 && attr_count > 0 {
3082×
                attrs = crate::attributes::Attributes::from_files(
3092×
                    batch
3102×
                        .iter()
3112×
                        .zip(&rendered)
3122×
                        .map(|((p, _, _), (b, _))| (p.as_str(), b.as_slice())),
313
                );
314412×
            }
315414×
            done += batch.len();
316414×
            let on_disk: Vec<Vec<u8>> = batch
317414×
                .iter()
318414×
                .zip(rendered.iter())
3195939×
                .map(|((path, _, _), (bytes, _))| {
3205939×
                    if attrs.lookup(path).eol == Some(crate::attributes::Eol::Crlf) {
3212×
                        crate::attributes::to_crlf(bytes)
322
                    } else {
3235937×
                        bytes.clone()
324
                    }
3255939×
                })
326414×
                .collect();
327
            // Each directory checked (no symlink on the way) and made once,
328
            // then the files compared and written on every core.
329414×
            let mut dirs: BTreeSet<&str> = BTreeSet::new();
3305939×
            for (path, _, _) in batch {
3315939×
                if let Some((dir, _)) = path.rsplit_once('/') {
3325274×
                    dirs.insert(dir);
3335274×
                }
334
            }
335414×
            for dir in dirs {
336183×
                let full = self.safe_path(dir)?;
337182×
                if !full.is_dir() {
338136×
                    if fs::symlink_metadata(&full).is_ok() {
3390×
                        remove_any(&full)?;
340136×
                    }
341136×
                    fs::create_dir_all(&full)?;
34246×
                }
343
            }
3445937×
            for (path, _, _) in batch {
3455937×
                check_path_name(path)?;
346
            }
347413×
            let (root, exec_bits) = (&self.root, self.platform.exec_bits);
348
            // Compared on every core; new files written on every core too,
349
            // but files that exist rewritten one at a time: on ext4,
350
            // rewriting in parallel was six times slower (each truncation
351
            // starts writing back the old blocks).
352413×
            let plans: Vec<Disk> = batch
353413×
                .par_iter()
354413×
                .zip(on_disk.par_iter())
3555937×
                .map(|((path, _, mode), bytes)| {
3565937×
                    compare_on_disk(&root.join(path), bytes, mode.exec, exec_bits)
3575937×
                })
358413×
                .collect();
359413×
            let fresh: Vec<usize> = (0..batch.len())
3605937×
                .filter(|&i| plans[i] == Disk::Absent)
361413×
                .collect();
362413×
            fresh
363413×
                .par_iter()
3645726×
                .map(|&i| write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec))
365413×
                .collect::<std::io::Result<()>>()?;
3665937×
            for (i, plan) in plans.iter().enumerate() {
3675937×
                if *plan == Disk::Differs {
368179×
                    write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec)?;
3695758×
                }
370
            }
3715937×
            report.written += plans.iter().filter(|p| **p != Disk::Same).count();
3725937×
            for (((path, node, mode), (_, conflicted)), on_disk) in
373413×
                batch.iter().zip(rendered).zip(on_disk)
374
            {
3755937×
                let a = attrs.lookup(path);
3765937×
                report.conflicted |= conflicted;
3775937×
                entries.insert(
3785937×
                    path.clone(),
379
                    FsEntry {
3805937×
                        content_hash: Some(hex(&on_disk)),
3815937×
                        graph_key: (!conflicted && a.eol.is_none())
3825937×
                            .then(|| keys.get(node).copied())
3835937×
                            .flatten(),
3845937×
                        ..FsEntry::new(NodeKind::File, mode.exec, Vec::new())
385
                    },
386
                );
387
            }
388
        }
389
        // Lockable files are read-only until locked (spec §18), whether
390
        // written now or left as they were.
39110438×
        for (path, e) in &entries {
39210438×
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
3932×
                let _ = set_readonly(&self.root.join(path), true);
39410436×
            }
395
        }
396
        // Prune directories left empty, deepest first.
397563×
        for d in dirs_to_prune.iter().rev() {
39873×
            let mut d = d.clone();
39988×
            while d != self.root
40018×
                && fs::read_dir(&d)
40118×
                    .map(|mut i| i.next().is_none())
40218×
                    .unwrap_or(false)
403
            {
40415×
                fs::remove_dir(&d)?;
40515×
                let Some(p) = d.parent() else { break };
40615×
                d = p.to_path_buf();
407
            }
408
        }
409
410563×
        drop(_render);
411
        // How the files rendered: which way each graph was ordered, summed
412
        // over every core (`OXY_TIMINGS`).
413563×
        crate::timing::report_totals();
414563×
        let recording = crate::timing::phase("checkout: record");
415563×
        let (op_ref, op) = self.head_op()?;
416563×
        let wc = self.new_working_copy(heads.clone(), "");
417563×
        let wc_hash = self.store.put_change(&wc)?;
418563×
        let mut view = op.view.clone();
419563×
        view.workspaces.insert(self.workspace, wc_hash);
420563×
        self.record_op(&[op_ref], command, view)?;
421563×
        drop(recording);
422563×
        let _t = crate::timing::phase("checkout: manifest");
423
        // The directories the new tree has, with any the old manifest kept
424
        // that still exist (holding only ignored files, say), statted now,
425
        // after the writes: the next check then need not list the tree. A
426
        // directory written just now is within the racy window, so for a
427
        // moment the check lists anyway.
428563×
        if !old_manifest.dirs.is_empty() {
429563×
            let mut dirs: BTreeSet<String> =
430664×
                old_manifest.dirs.iter().map(|(d, _)| d.clone()).collect();
431563×
            dirs.insert(String::new());
43210438×
            for p in entries.keys() {
43310438×
                let mut at = p.as_str();
43410575×
                while let Some((parent, _)) = at.rsplit_once('/') {
4359511×
                    if !dirs.insert(parent.to_string()) {
4369374×
                        break;
437137×
                    }
438137×
                    at = parent;
439
                }
440
            }
441
            use rayon::prelude::*;
442563×
            let root = &self.root;
443563×
            let dirs: Vec<(String, u128)> = dirs
444563×
                .into_par_iter()
445801×
                .filter_map(|d| {
446801×
                    let m = fs::metadata(root.join(&d)).ok().filter(|m| m.is_dir())?;
447786×
                    Some((d, prompt::mtime_ns(&m)))
448801×
                })
449563×
                .collect();
450563×
            let mut dirs = dirs;
451563×
            dirs.sort_unstable();
452563×
            *self.walked_dirs.borrow_mut() = Some((dirs, old_manifest.nested.clone()));
4530×
        }
454563×
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
455563×
        let _ = self.run_hook(
456563×
            "post-checkout",
457563×
            &format!(
458
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
459888×
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
460
                report.written,
461
                report.removed
462
            ),
463
        );
464563×
        Ok(report)
465566×
    }
466
467
    /// How many changes of the state at `from` the state `to` lacks: a walk
468
    /// down from `from` that stops at what `to` holds.
469564×
    fn count_lacking(&self, from: &[ChangeHash], to: &State) -> Result<usize> {
470564×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
471564×
        let mut stack: Vec<ChangeHash> = from.to_vec();
4721060×
        while let Some(h) = stack.pop() {
473496×
            if to.contains(&h) || !seen.insert(h) {
474396×
                continue;
475100×
            }
476100×
            stack.extend(self.store.get_change_lazy(&h)?.0.deps);
477
        }
478564×
        Ok(seen.len())
479564×
    }
480
481
    /// Refuse to leave uncommitted work behind unless `discard`.
482336×
    pub(crate) fn refuse_dirty(&self, snap: &SnapshotResult, discard: bool) -> Result<()> {
483336×
        if discard || (snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty()) {
484334×
            return Ok(());
4852×
        }
4862×
        let list: Vec<String> = snap
4872×
            .statuses
4882×
            .iter()
4892×
            .take(8)
4903×
            .map(|s| format!("{} {}", status_word(s.status), s.path))
4912×
            .collect();
4922×
        fail(format!(
493
            "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
4942×
            list.join(", "),
4952×
            if snap.statuses.len() > 8 { ", …" } else { "" }
496
        ))
497336×
    }
498
499
    /// Whether the file at `full` already holds `bytes` with this executable
500
    /// bit, so writing it again can be skipped.
50126×
    fn same_on_disk(&self, full: &Path, bytes: &[u8], exec: bool) -> bool {
50226×
        match fs::symlink_metadata(full) {
5038×
            Ok(m) if m.is_file() && m.len() == bytes.len() as u64 => {
5047×
                (!self.platform.exec_bits || is_executable(&m) == exec)
5057×
                    && fs::read(full).is_ok_and(|b| b == bytes)
506
            }
50719×
            _ => false,
508
        }
50926×
    }
510
511
    /// The absolute path for a repository path, refusing anything that would
512
    /// escape the workspace or write through a symlink (spec §7.7).
5133285×
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
5143285×
        let mut full = self.root.clone();
5153285×
        let comps: Vec<&str> = rel.split('/').collect();
5166297×
        for (i, comp) in comps.iter().enumerate() {
5176297×
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
5180×
                return fail(format!("refusing unsafe path {rel:?}"));
5196297×
            }
5206297×
            if i == 0 && *comp == OXY_DIR {
5210×
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
5226297×
            }
5236297×
            if i + 1 < comps.len() {
5243013×
                full.push(comp);
5253013×
                if let Ok(m) = fs::symlink_metadata(&full) {
5263012×
                    if m.file_type().is_symlink() {
5271×
                        return fail(format!(
528
                            "refusing to write through symlink {}",
5291×
                            full.display()
530
                        ));
5313011×
                    }
5321×
                }
5333284×
            } else {
5343284×
                full.push(comp);
5353284×
            }
536
        }
5373284×
        Ok(full)
5383285×
    }
539
54033×
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
54133×
        let full = self.safe_path(rel)?;
54233×
        if let Some(parent) = full.parent() {
54333×
            fs::create_dir_all(parent)?;
5440×
        }
54533×
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
5460×
            remove_any(&full)?;
54733×
        }
54833×
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
5491×
            set_readonly(&full, false)?;
55032×
        }
55133×
        fs::write(&full, bytes)?;
55233×
        set_executable(&full, exec)?;
55333×
        Ok(())
55433×
    }
555
5560×
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
5570×
        let full = self.safe_path(rel)?;
5580×
        if let Some(parent) = full.parent() {
5590×
            fs::create_dir_all(parent)?;
5600×
        }
5610×
        if fs::symlink_metadata(&full).is_ok() {
5620×
            remove_any(&full)?;
5630×
        }
564
        #[cfg(unix)]
565
        {
5660×
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
5670×
            Ok(())
568
        }
569
        #[cfg(not(unix))]
570
        {
571
            // Spec §7.7: without symlink support, write the target as a plain file.
572
            fs::write(&full, target)?;
573
            Ok(())
574
        }
5750×
    }
576
}
577
578
/// How a refusal names a path's change: "removed" is a file of the working
579
/// copy's base that is missing on disk.
5803×
fn status_word(s: ChangeStatus) -> &'static str {
5813×
    match s {
5820×
        ChangeStatus::Added => "added",
5832×
        ChangeStatus::Modified => "modified",
5841×
        ChangeStatus::Removed => "removed",
5850×
        ChangeStatus::Renamed => "renamed",
5860×
        ChangeStatus::ModeChanged => "mode changed",
5870×
        ChangeStatus::ConflictEdited => "conflict edited",
5880×
        ChangeStatus::Resolved => "resolved",
589
    }
5903×
}
591
592
/// Refuse a path that could escape the workspace (spec §7.7): an empty,
593
/// `.` or `..` component, a backslash, or a first component `.oxy`.
5945937×
fn check_path_name(rel: &str) -> Result<()> {
59511211×
    for (i, comp) in rel.split('/').enumerate() {
59611211×
        if comp.is_empty() || comp == "." || comp == ".." || comp.contains('\\') {
5970×
            return fail(format!("refusing unsafe path {rel:?}"));
59811211×
        }
59911211×
        if i == 0 && comp == OXY_DIR {
6000×
            return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
60111211×
        }
602
    }
6035937×
    Ok(())
6045937×
}
605
606
/// A file on disk against what a checkout would write there.
607
#[derive(Clone, Copy, PartialEq, Eq)]
608
enum Disk {
609
    Same,
610
    Differs,
611
    Absent,
612
}
613
614
/// Whether the file at `full` already holds `bytes` with the right
615
/// executable bit. Touches no repository state, so it runs in parallel.
6165937×
fn compare_on_disk(full: &Path, bytes: &[u8], exec: bool, exec_bits: bool) -> Disk {
6175937×
    match fs::symlink_metadata(full) {
61832×
        Ok(m)
619211×
            if m.is_file()
620211×
                && m.len() == bytes.len() as u64
62156×
                && (!exec_bits || is_executable(&m) == exec)
62255×
                && fs::read(full).is_ok_and(|b| b == bytes) =>
623
        {
62432×
            Disk::Same
625
        }
626179×
        Ok(_) => Disk::Differs,
6275726×
        Err(_) => Disk::Absent,
628
    }
6295937×
}
630
631
/// Write a file whose directory exists, replacing whatever is there.
6325905×
fn write_file_at(full: &Path, bytes: &[u8], exec: bool) -> std::io::Result<()> {
6335905×
    match fs::symlink_metadata(full) {
634179×
        Ok(m) if m.is_file() => {
635179×
            if m.permissions().readonly() {
6360×
                set_readonly(full, false)?;
637179×
            }
638
        }
6390×
        Ok(_) => remove_any(full)?,
6405726×
        Err(_) => {}
641
    }
6425905×
    fs::write(full, bytes)?;
6435905×
    set_executable(full, exec)
6445905×
}