OXYGENHUB

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

460 of 501 lines run, 87 of 97 functions · run #347 on proposal/125 · 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.
25517×
    pub fn checkout(
26517×
        &self,
27517×
        heads: &[ChangeHash],
28517×
        discard: bool,
29517×
        command: &str,
30517×
    ) -> Result<CheckoutReport> {
31517×
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
32517×
    }
33
34
    /// [`Repo::checkout`], leaving the nested repositories at
35
    /// `keep_subrepos` as they are (their pins are carried work).
36522×
    pub(crate) fn checkout_keeping(
37522×
        &self,
38522×
        heads: &[ChangeHash],
39522×
        discard: bool,
40522×
        command: &str,
41522×
        keep_subrepos: &BTreeSet<String>,
42522×
    ) -> Result<CheckoutReport> {
43522×
        let _wc = self.lock_working_copy()?;
44522×
        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).
50522×
        let changed_paths: Vec<String> = if self.clean_by_manifest()? {
51219×
            Vec::new()
52
        } else {
53303×
            let snap = self.snapshot_status(command)?;
54303×
            self.refuse_dirty(&snap, discard)?;
55301×
            snap.statuses.iter().map(|s| s.path.clone()).collect()
56
        };
57520×
        let (_, wc_now) = self.working_copy()?;
58520×
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
59520×
        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.
63520×
        let mut target = self.load_state_indexed(heads)?;
64520×
        let heads = target.maximal(heads);
65520×
        let tv = crate::timing::phase("checkout: target view");
66520×
        let tview = self.tree_view(&mut target)?;
67520×
        drop(tv);
68520×
        let mut report = CheckoutReport::default();
69
        // Paths this file system cannot hold side by side (spec §7.7).
70520×
        report.notes.extend(
71520×
            self.platform
72520×
                .problems(tview.entries.keys().map(String::as_str)),
73
        );
74520×
        report.conflicted = tview.is_conflicted();
75520×
        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).
79520×
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
80520×
        let gone: BTreeSet<&str> = old_manifest
81520×
            .entries
82520×
            .keys()
83520×
            .map(String::as_str)
84520×
            .chain(changed.iter().copied())
857772×
            .filter(|p| !tview.entries.contains_key(*p))
86520×
            .collect();
873079×
        for path in gone {
883079×
            let dir = self.root.join(path);
893079×
            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;
943077×
            }
953077×
            let full = self.safe_path(path)?;
963077×
            if fs::symlink_metadata(&full).is_err() {
971×
                continue;
983076×
            }
993076×
            fs::remove_file(&full)?;
1003076×
            report.removed += 1;
1013076×
            if report.removed_paths.len() < 5 {
102126×
                report.removed_paths.push(path.to_string());
1032950×
            }
1043076×
            if let Some(parent) = full.parent() {
1053076×
                dirs_to_prune.insert(parent.to_path_buf());
1063076×
            }
107
        }
108
109
        // The manifest after the checkout, built from what is known.
110520×
        let plan = crate::timing::phase("checkout: plan");
111520×
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1125890×
        let hex = |b: &[u8]| *blake3::hash(b).as_bytes();
113
        // Text files to render, attribute files first (the others need them).
114520×
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
11510585×
        for (path, e) in tview.entries.iter() {
11610585×
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
117218×
                continue;
11810367×
            }
119
            // The manifest entry of a file the working copy has not changed,
120
            // with the right executable bit.
12110367×
            let exec_ok =
1224643×
                |m: &prompt::ManifestEntry| !self.platform.exec_bits || m.exec == e.mode.exec;
12310367×
            let entry = old_manifest
12410367×
                .entries
12510367×
                .get(path)
12610367×
                .filter(|m| !changed.contains(path.as_str()) && exec_ok(m));
12710367×
            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.
13110327×
                let key = target.graph_key(&e.node);
13210327×
                let proven = |m: &&prompt::ManifestEntry| {
1334616×
                    !is_attributes(path) && key.is_some() && m.graph == key
1344616×
                };
13510327×
                match entry.filter(proven) {
1364450×
                    Some(m) => {
1374450×
                        entries.insert(
1384450×
                            path.clone(),
1394450×
                            FsEntry {
1404450×
                                content_hash: Some(m.hash),
1414450×
                                graph_key: m.graph,
1424450×
                                unchanged: true,
1434450×
                                stat: Some((m.size, m.mtime_ns)),
1444450×
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
1454450×
                            },
1464450×
                        );
1474450×
                    }
1485877×
                    None => texts.push((path.clone(), e.node, e.mode)),
149
                }
15010327×
                continue;
15140×
            }
152
            // Opaque files, symlinks and subrepos: their blobs.
15340×
            let blobs = target.live_blobs(&e.node);
15440×
            if blobs.len() > 1 {
1551×
                report.conflicted = true;
15639×
            }
15740×
            let Some(blob) = blobs.first().copied() else {
1580×
                continue;
159
            };
16040×
            if e.kind == NodeKind::Subrepo {
16110×
                if keep_subrepos.contains(path) {
1621×
                    continue;
1639×
                }
1649×
                let pin = crate::subrepo::Pin::decode(&self.read_blob(&blob)?)?;
1659×
                let sync = self.sync_subrepo(path, &pin, false)?;
1668×
                if matches!(
1679×
                    sync,
168
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
1691×
                ) {
1701×
                    report.written += 1;
1718×
                }
1729×
                report.notes.extend(sync.note(path));
1739×
                continue;
17430×
            }
17530×
            if let Some(m) = entry
17630×
                .filter(|m| e.kind == NodeKind::File && blobs.len() == 1 && m.blob == Some(blob))
177
            {
17815×
                entries.insert(
17915×
                    path.clone(),
18015×
                    FsEntry {
18115×
                        content_hash: Some(m.hash),
18215×
                        blob: (e.kind == NodeKind::File).then_some(blob),
18315×
                        stat: Some((m.size, m.mtime_ns)),
18415×
                        ..FsEntry::new(e.kind, e.mode.exec, Vec::new())
18515×
                    },
186
                );
18715×
                continue;
18815×
            }
18915×
            let bytes = self.read_blob(&blob)?;
19015×
            let full = self.root.join(path);
19115×
            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 {
20615×
                if !self.same_on_disk(&full, &bytes, e.mode.exec) {
20714×
                    self.write_file(path, &bytes, e.mode.exec)?;
20814×
                    report.written += 1;
2091×
                }
21015×
                entries.insert(
21115×
                    path.clone(),
21215×
                    FsEntry {
21315×
                        content_hash: Some(hex(&bytes)),
21415×
                        blob: (blobs.len() == 1).then_some(blob),
21515×
                        ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
21615×
                    },
217
                );
218
            }
21915×
            for (i, b) in blobs.iter().enumerate().skip(1) {
2201×
                self.write_file(
2211×
                    &format!("{path}.oxy-conflict-{}", i + 1),
2221×
                    &self.read_blob(b)?,
2231×
                    e.mode.exec,
2240×
                )?;
225
            }
226
        }
227
228520×
        drop(plan);
229520×
        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.
23210990×
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
233520×
        let keys: HashMap<NodeId, [u8; 32]> = texts
234520×
            .iter()
2355877×
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
236520×
            .collect();
237520×
        let mut attrs = crate::attributes::Attributes::default();
2385877×
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
239520×
        let mut done = 0usize;
240520×
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
241520×
        if attr_count > 0 {
2422×
            batches.push(&texts[..attr_count]);
243518×
        }
244520×
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
245520×
        for batch in batches {
246
            use rayon::prelude::*;
247385×
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
248
            // A file added once and never edited is its text: no graph.
249385×
            let single: Vec<Option<crate::objects::TextRef>> =
2505877×
                nodes.iter().map(|n| target.single_text(n)).collect();
251385×
            let graphs: Vec<NodeId> = nodes
252385×
                .iter()
253385×
                .zip(&single)
2545877×
                .filter(|(_, s)| s.is_none())
255385×
                .map(|(n, _)| *n)
256385×
                .collect();
257385×
            let mut texts = {
258385×
                let _t = crate::timing::phase("checkout: read single texts");
259385×
                let wanted: Vec<crate::objects::TextRef> =
260385×
                    single.iter().flatten().copied().collect();
261385×
                self.single_texts(&wanted)?.into_iter()
262
            };
263
            {
264385×
                let _t = crate::timing::phase("checkout: build graphs");
265385×
                self.load_graphs_of(&mut target, &graphs)?;
266
            }
267385×
            let rendered: Vec<(Vec<u8>, bool)> = {
268385×
                let _t = crate::timing::phase("checkout: render");
269385×
                let mut out: Vec<Option<(Vec<u8>, bool)>> = single
270385×
                    .iter()
2715877×
                    .map(|s| s.as_ref().and_then(|_| texts.next().map(|t| (t, false))))
272385×
                    .collect();
273385×
                let from_graphs: Vec<(Vec<u8>, bool)> = graphs
274385×
                    .par_iter()
275385×
                    .map(|n| {
276333×
                        let (bytes, m) = target.render_file(n);
277333×
                        (bytes, m.is_conflicted())
278333×
                    })
279385×
                    .collect();
280385×
                let mut from_graphs = from_graphs.into_iter();
2815877×
                for o in out.iter_mut().filter(|o| o.is_none()) {
282333×
                    *o = from_graphs.next();
283333×
                }
284385×
                out.into_iter()
2855877×
                    .map(|o| o.expect("every file rendered"))
286385×
                    .collect()
287
            };
288
            #[cfg(test)]
289
            {
290188×
                let singles: Vec<NodeId> = nodes
291188×
                    .iter()
292188×
                    .zip(&single)
2935330×
                    .filter(|(_, s)| s.is_some())
294188×
                    .map(|(n, _)| *n)
295188×
                    .collect();
296188×
                self.load_graphs_of(&mut target, &singles)?;
2975330×
                for (n, (bytes, _)) in nodes.iter().zip(&rendered) {
2985330×
                    assert_eq!(
299
                        *bytes,
3005330×
                        target.render_file(n).0,
301
                        "a single text is its file's rendering"
302
                    );
303
                }
304
            }
305385×
            target.drop_graphs(&nodes);
306385×
            let _t = crate::timing::phase("checkout: write");
307385×
            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
                );
314383×
            }
315385×
            done += batch.len();
316385×
            let on_disk: Vec<Vec<u8>> = batch
317385×
                .iter()
318385×
                .zip(rendered.iter())
3195877×
                .map(|((path, _, _), (bytes, _))| {
3205877×
                    if attrs.lookup(path).eol == Some(crate::attributes::Eol::Crlf) {
3212×
                        crate::attributes::to_crlf(bytes)
322
                    } else {
3235875×
                        bytes.clone()
324
                    }
3255877×
                })
326385×
                .collect();
327
            // Each directory checked (no symlink on the way) and made once,
328
            // then the files compared and written on every core.
329385×
            let mut dirs: BTreeSet<&str> = BTreeSet::new();
3305877×
            for (path, _, _) in batch {
3315877×
                if let Some((dir, _)) = path.rsplit_once('/') {
3325263×
                    dirs.insert(dir);
3335263×
                }
334
            }
335385×
            for dir in dirs {
336172×
                let full = self.safe_path(dir)?;
337171×
                if !full.is_dir() {
338132×
                    if fs::symlink_metadata(&full).is_ok() {
3390×
                        remove_any(&full)?;
340132×
                    }
341132×
                    fs::create_dir_all(&full)?;
34239×
                }
343
            }
3445875×
            for (path, _, _) in batch {
3455875×
                check_path_name(path)?;
346
            }
347384×
            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).
352384×
            let plans: Vec<Disk> = batch
353384×
                .par_iter()
354384×
                .zip(on_disk.par_iter())
3555875×
                .map(|((path, _, mode), bytes)| {
3565875×
                    compare_on_disk(&root.join(path), bytes, mode.exec, exec_bits)
3575875×
                })
358384×
                .collect();
359384×
            let fresh: Vec<usize> = (0..batch.len())
3605875×
                .filter(|&i| plans[i] == Disk::Absent)
361384×
                .collect();
362384×
            fresh
363384×
                .par_iter()
3645699×
                .map(|&i| write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec))
365384×
                .collect::<std::io::Result<()>>()?;
3665875×
            for (i, plan) in plans.iter().enumerate() {
3675875×
                if *plan == Disk::Differs {
368157×
                    write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec)?;
3695718×
                }
370
            }
3715875×
            report.written += plans.iter().filter(|p| **p != Disk::Same).count();
3725875×
            for (((path, node, mode), (_, conflicted)), on_disk) in
373384×
                batch.iter().zip(rendered).zip(on_disk)
374
            {
3755875×
                let a = attrs.lookup(path);
3765875×
                report.conflicted |= conflicted;
3775875×
                entries.insert(
3785875×
                    path.clone(),
379
                    FsEntry {
3805875×
                        content_hash: Some(hex(&on_disk)),
3815875×
                        graph_key: (!conflicted && a.eol.is_none())
3825875×
                            .then(|| keys.get(node).copied())
3835875×
                            .flatten(),
3845875×
                        ..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.
39110355×
        for (path, e) in &entries {
39210355×
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
3932×
                let _ = set_readonly(&self.root.join(path), true);
39410353×
            }
395
        }
396
        // Prune directories left empty, deepest first.
397519×
        for d in dirs_to_prune.iter().rev() {
39880×
            let mut d = d.clone();
39998×
            while d != self.root
40021×
                && fs::read_dir(&d)
40121×
                    .map(|mut i| i.next().is_none())
40221×
                    .unwrap_or(false)
403
            {
40418×
                fs::remove_dir(&d)?;
40518×
                let Some(p) = d.parent() else { break };
40618×
                d = p.to_path_buf();
407
            }
408
        }
409
410519×
        drop(_render);
411519×
        let recording = crate::timing::phase("checkout: record");
412519×
        let (op_ref, op) = self.head_op()?;
413519×
        let wc = self.new_working_copy(heads.clone(), "");
414519×
        let wc_hash = self.store.put_change(&wc)?;
415519×
        let mut view = op.view.clone();
416519×
        view.workspaces.insert(self.workspace, wc_hash);
417519×
        self.record_op(&[op_ref], command, view)?;
418519×
        drop(recording);
419519×
        let _t = crate::timing::phase("checkout: manifest");
420
        // The directories the new tree has, with any the old manifest kept
421
        // that still exist (holding only ignored files, say), statted now,
422
        // after the writes: the next check then need not list the tree. A
423
        // directory written just now is within the racy window, so for a
424
        // moment the check lists anyway.
425519×
        if !old_manifest.dirs.is_empty() {
426519×
            let mut dirs: BTreeSet<String> =
427616×
                old_manifest.dirs.iter().map(|(d, _)| d.clone()).collect();
428519×
            dirs.insert(String::new());
42910355×
            for p in entries.keys() {
43010355×
                let mut at = p.as_str();
43110488×
                while let Some((parent, _)) = at.rsplit_once('/') {
4329500×
                    if !dirs.insert(parent.to_string()) {
4339367×
                        break;
434133×
                    }
435133×
                    at = parent;
436
                }
437
            }
438
            use rayon::prelude::*;
439519×
            let root = &self.root;
440519×
            let dirs: Vec<(String, u128)> = dirs
441519×
                .into_par_iter()
442749×
                .filter_map(|d| {
443749×
                    let m = fs::metadata(root.join(&d)).ok().filter(|m| m.is_dir())?;
444731×
                    Some((d, prompt::mtime_ns(&m)))
445749×
                })
446519×
                .collect();
447519×
            let mut dirs = dirs;
448519×
            dirs.sort_unstable();
449519×
            *self.walked_dirs.borrow_mut() = Some((dirs, old_manifest.nested.clone()));
4500×
        }
451519×
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
452519×
        let _ = self.run_hook(
453519×
            "post-checkout",
454519×
            &format!(
455
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
456863×
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
457
                report.written,
458
                report.removed
459
            ),
460
        );
461519×
        Ok(report)
462522×
    }
463
464
    /// How many changes of the state at `from` the state `to` lacks: a walk
465
    /// down from `from` that stops at what `to` holds.
466520×
    fn count_lacking(&self, from: &[ChangeHash], to: &State) -> Result<usize> {
467520×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
468520×
        let mut stack: Vec<ChangeHash> = from.to_vec();
4691002×
        while let Some(h) = stack.pop() {
470482×
            if to.contains(&h) || !seen.insert(h) {
471389×
                continue;
47293×
            }
47393×
            stack.extend(self.store.get_change_lazy(&h)?.0.deps);
474
        }
475520×
        Ok(seen.len())
476520×
    }
477
478
    /// Refuse to leave uncommitted work behind unless `discard`.
479303×
    pub(crate) fn refuse_dirty(&self, snap: &SnapshotResult, discard: bool) -> Result<()> {
480303×
        if discard || (snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty()) {
481301×
            return Ok(());
4822×
        }
4832×
        let list: Vec<String> = snap
4842×
            .statuses
4852×
            .iter()
4862×
            .take(8)
4873×
            .map(|s| format!("{} {}", status_word(s.status), s.path))
4882×
            .collect();
4892×
        fail(format!(
490
            "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
4912×
            list.join(", "),
4922×
            if snap.statuses.len() > 8 { ", …" } else { "" }
493
        ))
494303×
    }
495
496
    /// Whether the file at `full` already holds `bytes` with this executable
497
    /// bit, so writing it again can be skipped.
49815×
    fn same_on_disk(&self, full: &Path, bytes: &[u8], exec: bool) -> bool {
49915×
        match fs::symlink_metadata(full) {
5005×
            Ok(m) if m.is_file() && m.len() == bytes.len() as u64 => {
5014×
                (!self.platform.exec_bits || is_executable(&m) == exec)
5024×
                    && fs::read(full).is_ok_and(|b| b == bytes)
503
            }
50411×
            _ => false,
505
        }
50615×
    }
507
508
    /// The absolute path for a repository path, refusing anything that would
509
    /// escape the workspace or write through a symlink (spec §7.7).
5103271×
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
5113271×
        let mut full = self.root.clone();
5123271×
        let comps: Vec<&str> = rel.split('/').collect();
5136286×
        for (i, comp) in comps.iter().enumerate() {
5146286×
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
5150×
                return fail(format!("refusing unsafe path {rel:?}"));
5166286×
            }
5176286×
            if i == 0 && *comp == OXY_DIR {
5180×
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
5196286×
            }
5206286×
            if i + 1 < comps.len() {
5213016×
                full.push(comp);
5223016×
                if let Ok(m) = fs::symlink_metadata(&full) {
5233015×
                    if m.file_type().is_symlink() {
5241×
                        return fail(format!(
525
                            "refusing to write through symlink {}",
5261×
                            full.display()
527
                        ));
5283014×
                    }
5291×
                }
5303270×
            } else {
5313270×
                full.push(comp);
5323270×
            }
533
        }
5343270×
        Ok(full)
5353271×
    }
536
53722×
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
53822×
        let full = self.safe_path(rel)?;
53922×
        if let Some(parent) = full.parent() {
54022×
            fs::create_dir_all(parent)?;
5410×
        }
54222×
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
5430×
            remove_any(&full)?;
54422×
        }
54522×
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
5461×
            set_readonly(&full, false)?;
54721×
        }
54822×
        fs::write(&full, bytes)?;
54922×
        set_executable(&full, exec)?;
55022×
        Ok(())
55122×
    }
552
5530×
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
5540×
        let full = self.safe_path(rel)?;
5550×
        if let Some(parent) = full.parent() {
5560×
            fs::create_dir_all(parent)?;
5570×
        }
5580×
        if fs::symlink_metadata(&full).is_ok() {
5590×
            remove_any(&full)?;
5600×
        }
561
        #[cfg(unix)]
562
        {
5630×
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
5640×
            Ok(())
565
        }
566
        #[cfg(not(unix))]
567
        {
568
            // Spec §7.7: without symlink support, write the target as a plain file.
569
            fs::write(&full, target)?;
570
            Ok(())
571
        }
5720×
    }
573
}
574
575
/// How a refusal names a path's change: "removed" is a file of the working
576
/// copy's base that is missing on disk.
5773×
fn status_word(s: ChangeStatus) -> &'static str {
5783×
    match s {
5790×
        ChangeStatus::Added => "added",
5802×
        ChangeStatus::Modified => "modified",
5811×
        ChangeStatus::Removed => "removed",
5820×
        ChangeStatus::Renamed => "renamed",
5830×
        ChangeStatus::ModeChanged => "mode changed",
5840×
        ChangeStatus::ConflictEdited => "conflict edited",
5850×
        ChangeStatus::Resolved => "resolved",
586
    }
5873×
}
588
589
/// Refuse a path that could escape the workspace (spec §7.7): an empty,
590
/// `.` or `..` component, a backslash, or a first component `.oxy`.
5915875×
fn check_path_name(rel: &str) -> Result<()> {
59211138×
    for (i, comp) in rel.split('/').enumerate() {
59311138×
        if comp.is_empty() || comp == "." || comp == ".." || comp.contains('\\') {
5940×
            return fail(format!("refusing unsafe path {rel:?}"));
59511138×
        }
59611138×
        if i == 0 && comp == OXY_DIR {
5970×
            return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
59811138×
        }
599
    }
6005875×
    Ok(())
6015875×
}
602
603
/// A file on disk against what a checkout would write there.
604
#[derive(Clone, Copy, PartialEq, Eq)]
605
enum Disk {
606
    Same,
607
    Differs,
608
    Absent,
609
}
610
611
/// Whether the file at `full` already holds `bytes` with the right
612
/// executable bit. Touches no repository state, so it runs in parallel.
6135875×
fn compare_on_disk(full: &Path, bytes: &[u8], exec: bool, exec_bits: bool) -> Disk {
6145875×
    match fs::symlink_metadata(full) {
61519×
        Ok(m)
616176×
            if m.is_file()
617176×
                && m.len() == bytes.len() as u64
61841×
                && (!exec_bits || is_executable(&m) == exec)
61940×
                && fs::read(full).is_ok_and(|b| b == bytes) =>
620
        {
62119×
            Disk::Same
622
        }
623157×
        Ok(_) => Disk::Differs,
6245699×
        Err(_) => Disk::Absent,
625
    }
6265875×
}
627
628
/// Write a file whose directory exists, replacing whatever is there.
6295856×
fn write_file_at(full: &Path, bytes: &[u8], exec: bool) -> std::io::Result<()> {
6305856×
    match fs::symlink_metadata(full) {
631157×
        Ok(m) if m.is_file() => {
632157×
            if m.permissions().readonly() {
6330×
                set_readonly(full, false)?;
634157×
            }
635
        }
6360×
        Ok(_) => remove_any(full)?,
6375699×
        Err(_) => {}
638
    }
6395856×
    fs::write(full, bytes)?;
6405856×
    set_executable(full, exec)
6415856×
}