OXYGENHUB

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

456 of 498 lines run, 87 of 97 functions · run #266 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
    pub conflicted: bool,
10
    /// Nested repositories that could not be moved, and other remarks.
11
    pub notes: Vec<String>,
12
    /// How many changes of the state left behind the new one lacks.
13
    pub lacks: usize,
14
}
15
16
/// Text files rendered at a time by a checkout: bounds its memory.
17
const CHECKOUT_BATCH: usize = 2048;
18
19
impl Repo {
20
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
21
    /// the working directory is rewritten to that state and a fresh
22
    /// working-copy change is started on it. The bookmark does not move.
23456×
    pub fn checkout(
24456×
        &self,
25456×
        heads: &[ChangeHash],
26456×
        discard: bool,
27456×
        command: &str,
28456×
    ) -> Result<CheckoutReport> {
29456×
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
30456×
    }
31
32
    /// [`Repo::checkout`], leaving the nested repositories at
33
    /// `keep_subrepos` as they are (their pins are carried work).
34460×
    pub(crate) fn checkout_keeping(
35460×
        &self,
36460×
        heads: &[ChangeHash],
37460×
        discard: bool,
38460×
        command: &str,
39460×
        keep_subrepos: &BTreeSet<String>,
40460×
    ) -> Result<CheckoutReport> {
41460×
        let _wc = self.lock_working_copy()?;
42460×
        let _all = crate::timing::phase("checkout");
43
        // A working copy clean by the manifest needs no snapshot; otherwise a
44
        // status snapshot records what changed, and rewrites the manifest
45
        // with the graph key of every file it proves unchanged. Either way
46
        // the manifest then says, for each file on disk, which graph it
47
        // renders, so the base state itself is not needed (oxygen#35).
48460×
        let changed_paths: Vec<String> = if self.clean_by_manifest()? {
49188×
            Vec::new()
50
        } else {
51272×
            let snap = self.snapshot_status(command)?;
52272×
            self.refuse_dirty(&snap, discard)?;
53270×
            snap.statuses.iter().map(|s| s.path.clone()).collect()
54
        };
55458×
        let (_, wc_now) = self.working_copy()?;
56458×
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
57458×
        let changed: HashSet<&str> = changed_paths.iter().map(String::as_str).collect();
58
        // The target's history; its file graphs are built a batch at a time
59
        // for the files that must be written, and dropped after. It becomes
60
        // the working copy's base, which the state index holds.
61458×
        let mut target = self.load_state_indexed(heads)?;
62458×
        let heads = target.maximal(heads);
63458×
        let tv = crate::timing::phase("checkout: target view");
64458×
        let tview = target.tree().view();
65458×
        drop(tv);
66458×
        let mut report = CheckoutReport::default();
67
        // Paths this file system cannot hold side by side (spec §7.7).
68458×
        report.notes.extend(
69458×
            self.platform
70458×
                .problems(tview.entries.keys().map(String::as_str)),
71
        );
72458×
        report.conflicted = tview.is_conflicted();
73458×
        report.lacks = self.count_lacking(&wc_now.deps, &target)?;
74
75
        // Remove what the base or the working copy has and the target does
76
        // not. A nested repository is never deleted (spec §7.8).
77458×
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
78458×
        let gone: BTreeSet<&str> = old_manifest
79458×
            .entries
80458×
            .keys()
81458×
            .map(String::as_str)
82458×
            .chain(changed.iter().copied())
837692×
            .filter(|p| !tview.entries.contains_key(*p))
84458×
            .collect();
853063×
        for path in gone {
863063×
            let dir = self.root.join(path);
873063×
            if dir.join(OXY_DIR).exists() || dir.join(".git").exists() {
881×
                report
891×
                    .notes
901×
                    .push(format!("{path}: nested repository left in place"));
911×
                continue;
923062×
            }
933062×
            let full = self.safe_path(path)?;
943062×
            if fs::symlink_metadata(&full).is_err() {
950×
                continue;
963062×
            }
973062×
            fs::remove_file(&full)?;
983062×
            report.removed += 1;
993062×
            if let Some(parent) = full.parent() {
1003062×
                dirs_to_prune.insert(parent.to_path_buf());
1013062×
            }
102
        }
103
104
        // The manifest after the checkout, built from what is known.
105458×
        let plan = crate::timing::phase("checkout: plan");
106458×
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1075861×
        let hex = |b: &[u8]| *blake3::hash(b).as_bytes();
108
        // Text files to render, attribute files first (the others need them).
109458×
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
11010532×
        for (path, e) in tview.entries.iter() {
11110532×
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
112226×
                continue;
11310306×
            }
114
            // The manifest entry of a file the working copy has not changed,
115
            // with the right executable bit.
11610306×
            let exec_ok =
1174592×
                |m: &prompt::ManifestEntry| !self.platform.exec_bits || m.exec == e.mode.exec;
11810306×
            let entry = old_manifest
11910306×
                .entries
12010306×
                .get(path)
12110306×
                .filter(|m| !changed.contains(path.as_str()) && exec_ok(m));
12210306×
            if e.kind == NodeKind::File && !e.mode.opaque {
123
                // The manifest proves the file on disk equal to the rendering
124
                // of a graph whose key is the target's: nothing to read,
125
                // render or write.
12610268×
                let key = target.graph_key(&e.node);
12710268×
                let proven = |m: &&prompt::ManifestEntry| {
1284568×
                    !is_attributes(path) && key.is_some() && m.graph == key
1294568×
                };
13010268×
                match entry.filter(proven) {
1314420×
                    Some(m) => {
1324420×
                        entries.insert(
1334420×
                            path.clone(),
1344420×
                            FsEntry {
1354420×
                                content_hash: Some(m.hash),
1364420×
                                graph_key: m.graph,
1374420×
                                unchanged: true,
1384420×
                                stat: Some((m.size, m.mtime_ns)),
1394420×
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
1404420×
                            },
1414420×
                        );
1424420×
                    }
1435848×
                    None => texts.push((path.clone(), e.node, e.mode)),
144
                }
14510268×
                continue;
14638×
            }
147
            // Opaque files, symlinks and subrepos: their blobs.
14838×
            let blobs = target.live_blobs(&e.node);
14938×
            if blobs.len() > 1 {
1501×
                report.conflicted = true;
15137×
            }
15238×
            let Some(blob) = blobs.first().copied() else {
1530×
                continue;
154
            };
15538×
            if e.kind == NodeKind::Subrepo {
1568×
                if keep_subrepos.contains(path) {
1571×
                    continue;
1587×
                }
1597×
                let pin = crate::subrepo::Pin::decode(&self.read_blob(&blob)?)?;
1607×
                let sync = self.sync_subrepo(path, &pin, false)?;
1616×
                if matches!(
1627×
                    sync,
163
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
1641×
                ) {
1651×
                    report.written += 1;
1666×
                }
1677×
                report.notes.extend(sync.note(path));
1687×
                continue;
16930×
            }
17030×
            if let Some(m) = entry
17130×
                .filter(|m| e.kind == NodeKind::File && blobs.len() == 1 && m.blob == Some(blob))
172
            {
17315×
                entries.insert(
17415×
                    path.clone(),
17515×
                    FsEntry {
17615×
                        content_hash: Some(m.hash),
17715×
                        blob: (e.kind == NodeKind::File).then_some(blob),
17815×
                        stat: Some((m.size, m.mtime_ns)),
17915×
                        ..FsEntry::new(e.kind, e.mode.exec, Vec::new())
18015×
                    },
181
                );
18215×
                continue;
18315×
            }
18415×
            let bytes = self.read_blob(&blob)?;
18515×
            let full = self.root.join(path);
18615×
            if e.kind == NodeKind::Symlink {
1870×
                let same = fs::read_link(&full)
1880×
                    .is_ok_and(|t| t.to_string_lossy().as_bytes() == bytes.as_slice());
1890×
                if !same {
1900×
                    self.write_symlink(path, &bytes)?;
1910×
                    report.written += 1;
1920×
                }
1930×
                entries.insert(
1940×
                    path.clone(),
1950×
                    FsEntry {
1960×
                        content_hash: Some(hex(&bytes)),
1970×
                        ..FsEntry::new(NodeKind::Symlink, false, Vec::new())
1980×
                    },
199
                );
200
            } else {
20115×
                if !self.same_on_disk(&full, &bytes, e.mode.exec) {
20214×
                    self.write_file(path, &bytes, e.mode.exec)?;
20314×
                    report.written += 1;
2041×
                }
20515×
                entries.insert(
20615×
                    path.clone(),
20715×
                    FsEntry {
20815×
                        content_hash: Some(hex(&bytes)),
20915×
                        blob: (blobs.len() == 1).then_some(blob),
21015×
                        ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
21115×
                    },
212
                );
213
            }
21415×
            for (i, b) in blobs.iter().enumerate().skip(1) {
2151×
                self.write_file(
2161×
                    &format!("{path}.oxy-conflict-{}", i + 1),
2171×
                    &self.read_blob(b)?,
2181×
                    e.mode.exec,
2190×
                )?;
220
            }
221
        }
222
223458×
        drop(plan);
224458×
        let _render = crate::timing::phase("checkout: render and write");
225
        // Render and write text files a batch at a time; attribute files
226
        // come first, since the others' line endings and locks follow them.
22711010×
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
228458×
        let keys: HashMap<NodeId, [u8; 32]> = texts
229458×
            .iter()
2305848×
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
231458×
            .collect();
232458×
        let mut attrs = crate::attributes::Attributes::default();
2335848×
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
234458×
        let mut done = 0usize;
235458×
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
236458×
        if attr_count > 0 {
2372×
            batches.push(&texts[..attr_count]);
238456×
        }
239458×
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
240458×
        for batch in batches {
241
            use rayon::prelude::*;
242346×
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
243
            // A file added once and never edited is its text: no graph.
244346×
            let single: Vec<Option<crate::objects::TextRef>> =
2455848×
                nodes.iter().map(|n| target.single_text(n)).collect();
246346×
            let graphs: Vec<NodeId> = nodes
247346×
                .iter()
248346×
                .zip(&single)
2495848×
                .filter(|(_, s)| s.is_none())
250346×
                .map(|(n, _)| *n)
251346×
                .collect();
252346×
            let mut texts = {
253346×
                let _t = crate::timing::phase("checkout: read single texts");
254346×
                let wanted: Vec<crate::objects::TextRef> =
255346×
                    single.iter().flatten().copied().collect();
256346×
                self.single_texts(&wanted)?.into_iter()
257
            };
258
            {
259346×
                let _t = crate::timing::phase("checkout: build graphs");
260346×
                self.load_graphs_of(&mut target, &graphs)?;
261
            }
262346×
            let rendered: Vec<(Vec<u8>, bool)> = {
263346×
                let _t = crate::timing::phase("checkout: render");
264346×
                let mut out: Vec<Option<(Vec<u8>, bool)>> = single
265346×
                    .iter()
2665848×
                    .map(|s| s.as_ref().and_then(|_| texts.next().map(|t| (t, false))))
267346×
                    .collect();
268346×
                let from_graphs: Vec<(Vec<u8>, bool)> = graphs
269346×
                    .par_iter()
270346×
                    .map(|n| {
271315×
                        let (bytes, m) = target.render_file(n);
272315×
                        (bytes, m.is_conflicted())
273315×
                    })
274346×
                    .collect();
275346×
                let mut from_graphs = from_graphs.into_iter();
2765848×
                for o in out.iter_mut().filter(|o| o.is_none()) {
277315×
                    *o = from_graphs.next();
278315×
                }
279346×
                out.into_iter()
2805848×
                    .map(|o| o.expect("every file rendered"))
281346×
                    .collect()
282
            };
283
            #[cfg(test)]
284
            {
285147×
                let singles: Vec<NodeId> = nodes
286147×
                    .iter()
287147×
                    .zip(&single)
2885279×
                    .filter(|(_, s)| s.is_some())
289147×
                    .map(|(n, _)| *n)
290147×
                    .collect();
291147×
                self.load_graphs_of(&mut target, &singles)?;
2925279×
                for (n, (bytes, _)) in nodes.iter().zip(&rendered) {
2935279×
                    assert_eq!(
294
                        *bytes,
2955279×
                        target.render_file(n).0,
296
                        "a single text is its file's rendering"
297
                    );
298
                }
299
            }
300346×
            target.drop_graphs(&nodes);
301346×
            let _t = crate::timing::phase("checkout: write");
302346×
            if done == 0 && attr_count > 0 {
3032×
                attrs = crate::attributes::Attributes::from_files(
3042×
                    batch
3052×
                        .iter()
3062×
                        .zip(&rendered)
3072×
                        .map(|((p, _, _), (b, _))| (p.as_str(), b.as_slice())),
308
                );
309344×
            }
310346×
            done += batch.len();
311346×
            let on_disk: Vec<Vec<u8>> = batch
312346×
                .iter()
313346×
                .zip(rendered.iter())
3145848×
                .map(|((path, _, _), (bytes, _))| {
3155848×
                    if attrs.lookup(path).eol == Some(crate::attributes::Eol::Crlf) {
3162×
                        crate::attributes::to_crlf(bytes)
317
                    } else {
3185846×
                        bytes.clone()
319
                    }
3205848×
                })
321346×
                .collect();
322
            // Each directory checked (no symlink on the way) and made once,
323
            // then the files compared and written on every core.
324346×
            let mut dirs: BTreeSet<&str> = BTreeSet::new();
3255848×
            for (path, _, _) in batch {
3265848×
                if let Some((dir, _)) = path.rsplit_once('/') {
3275268×
                    dirs.insert(dir);
3285268×
                }
329
            }
330346×
            for dir in dirs {
331177×
                let full = self.safe_path(dir)?;
332176×
                if !full.is_dir() {
333135×
                    if fs::symlink_metadata(&full).is_ok() {
3340×
                        remove_any(&full)?;
335135×
                    }
336135×
                    fs::create_dir_all(&full)?;
33741×
                }
338
            }
3395846×
            for (path, _, _) in batch {
3405846×
                check_path_name(path)?;
341
            }
342345×
            let (root, exec_bits) = (&self.root, self.platform.exec_bits);
343
            // Compared on every core; new files written on every core too,
344
            // but files that exist rewritten one at a time: on ext4,
345
            // rewriting in parallel was six times slower (each truncation
346
            // starts writing back the old blocks).
347345×
            let plans: Vec<Disk> = batch
348345×
                .par_iter()
349345×
                .zip(on_disk.par_iter())
3505846×
                .map(|((path, _, mode), bytes)| {
3515846×
                    compare_on_disk(&root.join(path), bytes, mode.exec, exec_bits)
3525846×
                })
353345×
                .collect();
354345×
            let fresh: Vec<usize> = (0..batch.len())
3555846×
                .filter(|&i| plans[i] == Disk::Absent)
356345×
                .collect();
357345×
            fresh
358345×
                .par_iter()
3595692×
                .map(|&i| write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec))
360345×
                .collect::<std::io::Result<()>>()?;
3615846×
            for (i, plan) in plans.iter().enumerate() {
3625846×
                if *plan == Disk::Differs {
363148×
                    write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec)?;
3645698×
                }
365
            }
3665846×
            report.written += plans.iter().filter(|p| **p != Disk::Same).count();
3675846×
            for (((path, node, mode), (_, conflicted)), on_disk) in
368345×
                batch.iter().zip(rendered).zip(on_disk)
369
            {
3705846×
                let a = attrs.lookup(path);
3715846×
                report.conflicted |= conflicted;
3725846×
                entries.insert(
3735846×
                    path.clone(),
374
                    FsEntry {
3755846×
                        content_hash: Some(hex(&on_disk)),
3765846×
                        graph_key: (!conflicted && a.eol.is_none())
3775846×
                            .then(|| keys.get(node).copied())
3785846×
                            .flatten(),
3795846×
                        ..FsEntry::new(NodeKind::File, mode.exec, Vec::new())
380
                    },
381
                );
382
            }
383
        }
384
        // Lockable files are read-only until locked (spec §18), whether
385
        // written now or left as they were.
38610296×
        for (path, e) in &entries {
38710296×
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
3882×
                let _ = set_readonly(&self.root.join(path), true);
38910294×
            }
390
        }
391
        // Prune directories left empty, deepest first.
392457×
        for d in dirs_to_prune.iter().rev() {
39362×
            let mut d = d.clone();
39477×
            while d != self.root
39518×
                && fs::read_dir(&d)
39618×
                    .map(|mut i| i.next().is_none())
39718×
                    .unwrap_or(false)
398
            {
39915×
                fs::remove_dir(&d)?;
40015×
                let Some(p) = d.parent() else { break };
40115×
                d = p.to_path_buf();
402
            }
403
        }
404
405457×
        drop(_render);
406457×
        let recording = crate::timing::phase("checkout: record");
407457×
        let (op_ref, op) = self.head_op()?;
408457×
        let wc = self.new_working_copy(heads.clone(), "");
409457×
        let wc_hash = self.store.put_change(&wc)?;
410457×
        let mut view = op.view.clone();
411457×
        view.workspaces.insert(self.workspace, wc_hash);
412457×
        self.record_op(&[op_ref], command, view)?;
413457×
        drop(recording);
414457×
        let _t = crate::timing::phase("checkout: manifest");
415
        // The directories the new tree has, with any the old manifest kept
416
        // that still exist (holding only ignored files, say), statted now,
417
        // after the writes: the next check then need not list the tree. A
418
        // directory written just now is within the racy window, so for a
419
        // moment the check lists anyway.
420457×
        if !old_manifest.dirs.is_empty() {
421457×
            let mut dirs: BTreeSet<String> =
422554×
                old_manifest.dirs.iter().map(|(d, _)| d.clone()).collect();
423457×
            dirs.insert(String::new());
42410296×
            for p in entries.keys() {
42510296×
                let mut at = p.as_str();
42610432×
                while let Some((parent, _)) = at.rsplit_once('/') {
4279508×
                    if !dirs.insert(parent.to_string()) {
4289372×
                        break;
429136×
                    }
430136×
                    at = parent;
431
                }
432
            }
433
            use rayon::prelude::*;
434457×
            let root = &self.root;
435457×
            let dirs: Vec<(String, u128)> = dirs
436457×
                .into_par_iter()
437690×
                .filter_map(|d| {
438690×
                    let m = fs::metadata(root.join(&d)).ok().filter(|m| m.is_dir())?;
439675×
                    Some((d, prompt::mtime_ns(&m)))
440690×
                })
441457×
                .collect();
442457×
            let mut dirs = dirs;
443457×
            dirs.sort_unstable();
444457×
            *self.walked_dirs.borrow_mut() = Some((dirs, old_manifest.nested.clone()));
4450×
        }
446457×
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
447457×
        let _ = self.run_hook(
448457×
            "post-checkout",
449457×
            &format!(
450
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
451747×
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
452
                report.written,
453
                report.removed
454
            ),
455
        );
456457×
        Ok(report)
457460×
    }
458
459
    /// How many changes of the state at `from` the state `to` lacks: a walk
460
    /// down from `from` that stops at what `to` holds.
461458×
    fn count_lacking(&self, from: &[ChangeHash], to: &State) -> Result<usize> {
462458×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
463458×
        let mut stack: Vec<ChangeHash> = from.to_vec();
464870×
        while let Some(h) = stack.pop() {
465412×
            if to.contains(&h) || !seen.insert(h) {
466339×
                continue;
46773×
            }
46873×
            stack.extend(self.store.get_change_lazy(&h)?.0.deps);
469
        }
470458×
        Ok(seen.len())
471458×
    }
472
473
    /// Refuse to leave uncommitted work behind unless `discard`.
474272×
    pub(crate) fn refuse_dirty(&self, snap: &SnapshotResult, discard: bool) -> Result<()> {
475272×
        if discard || (snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty()) {
476270×
            return Ok(());
4772×
        }
4782×
        let list: Vec<String> = snap
4792×
            .statuses
4802×
            .iter()
4812×
            .take(8)
4823×
            .map(|s| format!("{} {}", status_word(s.status), s.path))
4832×
            .collect();
4842×
        fail(format!(
485
            "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
4862×
            list.join(", "),
4872×
            if snap.statuses.len() > 8 { ", …" } else { "" }
488
        ))
489272×
    }
490
491
    /// Whether the file at `full` already holds `bytes` with this executable
492
    /// bit, so writing it again can be skipped.
49315×
    fn same_on_disk(&self, full: &Path, bytes: &[u8], exec: bool) -> bool {
49415×
        match fs::symlink_metadata(full) {
4955×
            Ok(m) if m.is_file() && m.len() == bytes.len() as u64 => {
4964×
                (!self.platform.exec_bits || is_executable(&m) == exec)
4974×
                    && fs::read(full).is_ok_and(|b| b == bytes)
498
            }
49911×
            _ => false,
500
        }
50115×
    }
502
503
    /// The absolute path for a repository path, refusing anything that would
504
    /// escape the workspace or write through a symlink (spec §7.7).
5053260×
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
5063260×
        let mut full = self.root.clone();
5073260×
        let comps: Vec<&str> = rel.split('/').collect();
5086272×
        for (i, comp) in comps.iter().enumerate() {
5096272×
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
5100×
                return fail(format!("refusing unsafe path {rel:?}"));
5116272×
            }
5126272×
            if i == 0 && *comp == OXY_DIR {
5130×
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
5146272×
            }
5156272×
            if i + 1 < comps.len() {
5163013×
                full.push(comp);
5173013×
                if let Ok(m) = fs::symlink_metadata(&full) {
5183012×
                    if m.file_type().is_symlink() {
5191×
                        return fail(format!(
520
                            "refusing to write through symlink {}",
5211×
                            full.display()
522
                        ));
5233011×
                    }
5241×
                }
5253259×
            } else {
5263259×
                full.push(comp);
5273259×
            }
528
        }
5293259×
        Ok(full)
5303260×
    }
531
53221×
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
53321×
        let full = self.safe_path(rel)?;
53421×
        if let Some(parent) = full.parent() {
53521×
            fs::create_dir_all(parent)?;
5360×
        }
53721×
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
5380×
            remove_any(&full)?;
53921×
        }
54021×
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
5411×
            set_readonly(&full, false)?;
54220×
        }
54321×
        fs::write(&full, bytes)?;
54421×
        set_executable(&full, exec)?;
54521×
        Ok(())
54621×
    }
547
5480×
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
5490×
        let full = self.safe_path(rel)?;
5500×
        if let Some(parent) = full.parent() {
5510×
            fs::create_dir_all(parent)?;
5520×
        }
5530×
        if fs::symlink_metadata(&full).is_ok() {
5540×
            remove_any(&full)?;
5550×
        }
556
        #[cfg(unix)]
557
        {
5580×
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
5590×
            Ok(())
560
        }
561
        #[cfg(not(unix))]
562
        {
563
            // Spec §7.7: without symlink support, write the target as a plain file.
564
            fs::write(&full, target)?;
565
            Ok(())
566
        }
5670×
    }
568
}
569
570
/// How a refusal names a path's change: "removed" is a file of the working
571
/// copy's base that is missing on disk.
5723×
fn status_word(s: ChangeStatus) -> &'static str {
5733×
    match s {
5740×
        ChangeStatus::Added => "added",
5752×
        ChangeStatus::Modified => "modified",
5761×
        ChangeStatus::Removed => "removed",
5770×
        ChangeStatus::Renamed => "renamed",
5780×
        ChangeStatus::ModeChanged => "mode changed",
5790×
        ChangeStatus::ConflictEdited => "conflict edited",
5800×
        ChangeStatus::Resolved => "resolved",
581
    }
5823×
}
583
584
/// Refuse a path that could escape the workspace (spec §7.7): an empty,
585
/// `.` or `..` component, a backslash, or a first component `.oxy`.
5865846×
fn check_path_name(rel: &str) -> Result<()> {
58711114×
    for (i, comp) in rel.split('/').enumerate() {
58811114×
        if comp.is_empty() || comp == "." || comp == ".." || comp.contains('\\') {
5890×
            return fail(format!("refusing unsafe path {rel:?}"));
59011114×
        }
59111114×
        if i == 0 && comp == OXY_DIR {
5920×
            return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
59311114×
        }
594
    }
5955846×
    Ok(())
5965846×
}
597
598
/// A file on disk against what a checkout would write there.
599
#[derive(Clone, Copy, PartialEq, Eq)]
600
enum Disk {
601
    Same,
602
    Differs,
603
    Absent,
604
}
605
606
/// Whether the file at `full` already holds `bytes` with the right
607
/// executable bit. Touches no repository state, so it runs in parallel.
6085846×
fn compare_on_disk(full: &Path, bytes: &[u8], exec: bool, exec_bits: bool) -> Disk {
6095846×
    match fs::symlink_metadata(full) {
6106×
        Ok(m)
611154×
            if m.is_file()
612154×
                && m.len() == bytes.len() as u64
61324×
                && (!exec_bits || is_executable(&m) == exec)
61424×
                && fs::read(full).is_ok_and(|b| b == bytes) =>
615
        {
6166×
            Disk::Same
617
        }
618148×
        Ok(_) => Disk::Differs,
6195692×
        Err(_) => Disk::Absent,
620
    }
6215846×
}
622
623
/// Write a file whose directory exists, replacing whatever is there.
6245840×
fn write_file_at(full: &Path, bytes: &[u8], exec: bool) -> std::io::Result<()> {
6255840×
    match fs::symlink_metadata(full) {
626148×
        Ok(m) if m.is_file() => {
627148×
            if m.permissions().readonly() {
6280×
                set_readonly(full, false)?;
629148×
            }
630
        }
6310×
        Ok(_) => remove_any(full)?,
6325692×
        Err(_) => {}
633
    }
6345840×
    fs::write(full, bytes)?;
6355840×
    set_executable(full, exec)
6365840×
}