OXYGENHUB

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

489 of 529 lines run, 88 of 98 functions · run #426 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
    /// Union files whose adjacent insertions were settled by keeping both
17
    /// sides (oxygen#145).
18
    pub kept_both: Vec<KeptBoth>,
19
}
20
21
/// Text files rendered at a time by a checkout: bounds its memory.
22
const CHECKOUT_BATCH: usize = 2048;
23
24
impl Repo {
25
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
26
    /// the working directory is rewritten to that state and a fresh
27
    /// working-copy change is started on it. The bookmark does not move.
28589×
    pub fn checkout(
29589×
        &self,
30589×
        heads: &[ChangeHash],
31589×
        discard: bool,
32589×
        command: &str,
33589×
    ) -> Result<CheckoutReport> {
34589×
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
35589×
    }
36
37
    /// [`Repo::checkout`], leaving the nested repositories at
38
    /// `keep_subrepos` as they are (their pins are carried work).
39594×
    pub(crate) fn checkout_keeping(
40594×
        &self,
41594×
        heads: &[ChangeHash],
42594×
        discard: bool,
43594×
        command: &str,
44594×
        keep_subrepos: &BTreeSet<String>,
45594×
    ) -> Result<CheckoutReport> {
46594×
        let _wc = self.lock_working_copy()?;
47594×
        let _all = crate::timing::phase("checkout");
48
        // A working copy clean by the manifest needs no snapshot; otherwise a
49
        // status snapshot records what changed, and rewrites the manifest
50
        // with the graph key of every file it proves unchanged. Either way
51
        // the manifest then says, for each file on disk, which graph it
52
        // renders, so the base state itself is not needed (oxygen#35).
53594×
        let changed_paths: Vec<String> = if self.clean_by_manifest()? {
54254×
            Vec::new()
55
        } else {
56340×
            let snap = self.snapshot_status(command)?;
57340×
            self.refuse_dirty(&snap, discard)?;
58338×
            snap.statuses.iter().map(|s| s.path.clone()).collect()
59
        };
60592×
        let (_, wc_now) = self.working_copy()?;
61592×
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
62592×
        let changed: HashSet<&str> = changed_paths.iter().map(String::as_str).collect();
63
        // The target's history; its file graphs are built a batch at a time
64
        // for the files that must be written, and dropped after. It becomes
65
        // the working copy's base, which the state index holds.
66592×
        let mut target = self.load_state_indexed(heads)?;
67592×
        let heads = target.maximal(heads);
68592×
        let tv = crate::timing::phase("checkout: target view");
69592×
        let tview = self.tree_view(&mut target)?;
70592×
        drop(tv);
71592×
        let mut report = CheckoutReport::default();
72
        // Paths this file system cannot hold side by side (spec §7.7).
73592×
        report.notes.extend(
74592×
            self.platform
75592×
                .problems(tview.entries.keys().map(String::as_str)),
76
        );
77592×
        report.conflicted = tview.is_conflicted();
78592×
        report.lacks = self.count_lacking(&wc_now.deps, &target)?;
79
80
        // Remove what the base or the working copy has and the target does
81
        // not. A nested repository is never deleted (spec §7.8).
82592×
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
83592×
        let gone: BTreeSet<&str> = old_manifest
84592×
            .entries
85592×
            .keys()
86592×
            .map(String::as_str)
87592×
            .chain(changed.iter().copied())
887827×
            .filter(|p| !tview.entries.contains_key(*p))
89592×
            .collect();
903071×
        for path in gone {
913071×
            let dir = self.root.join(path);
923071×
            if dir.join(OXY_DIR).exists() || dir.join(".git").exists() {
932×
                report
942×
                    .notes
952×
                    .push(format!("{path}: nested repository left in place"));
962×
                continue;
973069×
            }
983069×
            let full = self.safe_path(path)?;
993069×
            if fs::symlink_metadata(&full).is_err() {
1001×
                continue;
1013068×
            }
1023068×
            fs::remove_file(&full)?;
1033068×
            report.removed += 1;
1043068×
            if report.removed_paths.len() < 5 {
105118×
                report.removed_paths.push(path.to_string());
1062950×
            }
1073068×
            if let Some(parent) = full.parent() {
1083068×
                dirs_to_prune.insert(parent.to_path_buf());
1093068×
            }
110
        }
111
112
        // The manifest after the checkout, built from what is known.
113592×
        let plan = crate::timing::phase("checkout: plan");
114592×
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1155938×
        let hex = |b: &[u8]| *blake3::hash(b).as_bytes();
116
        // Text files to render, attribute files first (the others need them).
117592×
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
11810679×
        for (path, e) in tview.entries.iter() {
11910679×
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
120223×
                continue;
12110456×
            }
122
            // The manifest entry of a file the working copy has not changed,
123
            // with the right executable bit.
12410456×
            let exec_ok =
1254716×
                |m: &prompt::ManifestEntry| !self.platform.exec_bits || m.exec == e.mode.exec;
12610456×
            let entry = old_manifest
12710456×
                .entries
12810456×
                .get(path)
12910456×
                .filter(|m| !changed.contains(path.as_str()) && exec_ok(m));
13010456×
            if e.kind == NodeKind::File && !e.mode.opaque {
131
                // The manifest proves the file on disk equal to the rendering
132
                // of a graph whose key is the target's: nothing to read,
133
                // render or write.
13410399×
                let key = target.graph_key(&e.node);
13510399×
                let proven = |m: &&prompt::ManifestEntry| {
1364681×
                    !is_attributes(path) && key.is_some() && m.graph == key
1374681×
                };
13810399×
                match entry.filter(proven) {
1394485×
                    Some(m) => {
1404485×
                        entries.insert(
1414485×
                            path.clone(),
1424485×
                            FsEntry {
1434485×
                                content_hash: Some(m.hash),
1444485×
                                graph_key: m.graph,
1454485×
                                unchanged: true,
1464485×
                                stat: Some((m.size, m.mtime_ns)),
1474485×
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
1484485×
                            },
1494485×
                        );
1504485×
                    }
1515914×
                    None => texts.push((path.clone(), e.node, e.mode)),
152
                }
15310399×
                continue;
15457×
            }
155
            // Opaque files, symlinks and subrepos: their blobs.
15657×
            let blobs = target.live_blobs(&e.node);
15757×
            if blobs.len() > 1 {
1583×
                report.conflicted = true;
15954×
            }
16057×
            let Some(blob) = blobs.first().copied() else {
1610×
                continue;
162
            };
16357×
            if e.kind == NodeKind::Subrepo {
16414×
                if keep_subrepos.contains(path) {
1651×
                    continue;
16613×
                }
16713×
                let pin = crate::subrepo::Pin::decode(&self.read_blob(&blob)?)?;
16813×
                let sync = self.sync_subrepo(path, &pin, false)?;
1699×
                if matches!(
17013×
                    sync,
171
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
1724×
                ) {
1734×
                    report.written += 1;
1749×
                }
17513×
                report.notes.extend(sync.note(path));
17613×
                continue;
17743×
            }
17843×
            if let Some(m) = entry
17943×
                .filter(|m| e.kind == NodeKind::File && blobs.len() == 1 && m.blob == Some(blob))
180
            {
18117×
                entries.insert(
18217×
                    path.clone(),
18317×
                    FsEntry {
18417×
                        content_hash: Some(m.hash),
18517×
                        blob: (e.kind == NodeKind::File).then_some(blob),
18617×
                        stat: Some((m.size, m.mtime_ns)),
18717×
                        ..FsEntry::new(e.kind, e.mode.exec, Vec::new())
18817×
                    },
189
                );
19017×
                continue;
19126×
            }
19226×
            let bytes = self.read_blob(&blob)?;
19326×
            let full = self.root.join(path);
19426×
            if e.kind == NodeKind::Symlink {
1950×
                let same = fs::read_link(&full)
1960×
                    .is_ok_and(|t| t.to_string_lossy().as_bytes() == bytes.as_slice());
1970×
                if !same {
1980×
                    self.write_symlink(path, &bytes)?;
1990×
                    report.written += 1;
2000×
                }
2010×
                entries.insert(
2020×
                    path.clone(),
2030×
                    FsEntry {
2040×
                        content_hash: Some(hex(&bytes)),
2050×
                        ..FsEntry::new(NodeKind::Symlink, false, Vec::new())
2060×
                    },
207
                );
208
            } else {
20926×
                if !self.same_on_disk(&full, &bytes, e.mode.exec) {
21024×
                    self.write_file(path, &bytes, e.mode.exec)?;
21124×
                    report.written += 1;
2122×
                }
21326×
                entries.insert(
21426×
                    path.clone(),
21526×
                    FsEntry {
21626×
                        content_hash: Some(hex(&bytes)),
21726×
                        blob: (blobs.len() == 1).then_some(blob),
21826×
                        ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
21926×
                    },
220
                );
221
            }
22226×
            for (i, b) in blobs.iter().enumerate().skip(1) {
2232×
                self.write_file(
2242×
                    &format!("{path}.oxy-conflict-{}", i + 1),
2252×
                    &self.read_blob(b)?,
2262×
                    e.mode.exec,
2270×
                )?;
228
            }
229
        }
230
231592×
        drop(plan);
232592×
        let _render = crate::timing::phase("checkout: render and write");
233
        // Render and write text files a batch at a time; attribute files
234
        // come first, since the others' line endings and locks follow them.
23510982×
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
236592×
        let keys: HashMap<NodeId, [u8; 32]> = texts
237592×
            .iter()
2385914×
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
239592×
            .collect();
240592×
        let mut attrs = crate::attributes::Attributes::default();
2415914×
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
242592×
        let mut done = 0usize;
243592×
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
244592×
        if attr_count > 0 {
2456×
            batches.push(&texts[..attr_count]);
246586×
        }
247592×
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
248592×
        for batch in batches {
249
            use rayon::prelude::*;
250430×
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
251
            // A file added once and never edited is its text: no graph.
252430×
            let single: Vec<Option<crate::objects::TextRef>> =
2535914×
                nodes.iter().map(|n| target.single_text(n)).collect();
254430×
            let graphs: Vec<NodeId> = nodes
255430×
                .iter()
256430×
                .zip(&single)
2575914×
                .filter(|(_, s)| s.is_none())
258430×
                .map(|(n, _)| *n)
259430×
                .collect();
260430×
            let mut texts = {
261430×
                let _t = crate::timing::phase("checkout: read single texts");
262430×
                let wanted: Vec<crate::objects::TextRef> =
263430×
                    single.iter().flatten().copied().collect();
264430×
                self.single_texts(&wanted)?.into_iter()
265
            };
266
            {
267430×
                let _t = crate::timing::phase("checkout: build graphs");
268430×
                self.load_graphs_of(&mut target, &graphs)?;
269
            }
270430×
            let rendered: Vec<(Vec<u8>, bool)> = {
271430×
                let _t = crate::timing::phase("checkout: render");
272430×
                let mut out: Vec<Option<(Vec<u8>, bool)>> = single
273430×
                    .iter()
2745914×
                    .map(|s| s.as_ref().and_then(|_| texts.next().map(|t| (t, false))))
275430×
                    .collect();
276430×
                let from_graphs: Vec<(Vec<u8>, bool)> = graphs
277430×
                    .par_iter()
278430×
                    .map(|n| {
279347×
                        let (bytes, m) = target.render_file(n);
280347×
                        (bytes, m.is_conflicted())
281347×
                    })
282430×
                    .collect();
283430×
                let mut from_graphs = from_graphs.into_iter();
2845914×
                for o in out.iter_mut().filter(|o| o.is_none()) {
285347×
                    *o = from_graphs.next();
286347×
                }
287430×
                out.into_iter()
2885914×
                    .map(|o| o.expect("every file rendered"))
289430×
                    .collect()
290
            };
291
            #[cfg(test)]
292
            {
293233×
                let singles: Vec<NodeId> = nodes
294233×
                    .iter()
295233×
                    .zip(&single)
2965380×
                    .filter(|(_, s)| s.is_some())
297233×
                    .map(|(n, _)| *n)
298233×
                    .collect();
299233×
                self.load_graphs_of(&mut target, &singles)?;
3005380×
                for (n, (bytes, _)) in nodes.iter().zip(&rendered) {
3015380×
                    assert_eq!(
302
                        *bytes,
3035380×
                        target.render_file(n).0,
304
                        "a single text is its file's rendering"
305
                    );
306
                }
307
            }
308430×
            target.drop_graphs(&nodes);
309430×
            let _t = crate::timing::phase("checkout: write");
310430×
            if done == 0 && attr_count > 0 {
3116×
                attrs = crate::attributes::Attributes::from_files(
3126×
                    batch
3136×
                        .iter()
3146×
                        .zip(&rendered)
3156×
                        .map(|((p, _, _), (b, _))| (p.as_str(), b.as_slice())),
316
                );
317424×
            }
318430×
            done += batch.len();
319430×
            let on_disk: Vec<Vec<u8>> = batch
320430×
                .iter()
321430×
                .zip(rendered.iter())
3225914×
                .map(|((path, _, _), (bytes, _))| {
3235914×
                    if attrs.lookup(path).eol == Some(crate::attributes::Eol::Crlf) {
3242×
                        crate::attributes::to_crlf(bytes)
325
                    } else {
3265912×
                        bytes.clone()
327
                    }
3285914×
                })
329430×
                .collect();
330
            // Each directory checked (no symlink on the way) and made once,
331
            // then the files compared and written on every core.
332430×
            let mut dirs: BTreeSet<&str> = BTreeSet::new();
3335914×
            for (path, _, _) in batch {
3345914×
                if let Some((dir, _)) = path.rsplit_once('/') {
3355261×
                    dirs.insert(dir);
3365261×
                }
337
            }
338430×
            for dir in dirs {
339170×
                let full = self.safe_path(dir)?;
340169×
                if !full.is_dir() {
341132×
                    if fs::symlink_metadata(&full).is_ok() {
3420×
                        remove_any(&full)?;
343132×
                    }
344132×
                    fs::create_dir_all(&full)?;
34537×
                }
346
            }
3475912×
            for (path, _, _) in batch {
3485912×
                check_path_name(path)?;
349
            }
350429×
            let (root, exec_bits) = (&self.root, self.platform.exec_bits);
351
            // Compared on every core; new files written on every core too,
352
            // but files that exist rewritten one at a time: on ext4,
353
            // rewriting in parallel was six times slower (each truncation
354
            // starts writing back the old blocks).
355429×
            let plans: Vec<Disk> = batch
356429×
                .par_iter()
357429×
                .zip(on_disk.par_iter())
3585912×
                .map(|((path, _, mode), bytes)| {
3595912×
                    compare_on_disk(&root.join(path), bytes, mode.exec, exec_bits)
3605912×
                })
361429×
                .collect();
362429×
            let fresh: Vec<usize> = (0..batch.len())
3635912×
                .filter(|&i| plans[i] == Disk::Absent)
364429×
                .collect();
365429×
            fresh
366429×
                .par_iter()
3675706×
                .map(|&i| write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec))
368429×
                .collect::<std::io::Result<()>>()?;
3695912×
            for (i, plan) in plans.iter().enumerate() {
3705912×
                if *plan == Disk::Differs {
371171×
                    write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec)?;
3725741×
                }
373
            }
3745912×
            report.written += plans.iter().filter(|p| **p != Disk::Same).count();
3755912×
            for (((path, node, mode), (_, conflicted)), on_disk) in
376429×
                batch.iter().zip(rendered).zip(on_disk)
377
            {
3785912×
                let a = attrs.lookup(path);
3795912×
                report.conflicted |= conflicted;
3805912×
                entries.insert(
3815912×
                    path.clone(),
382
                    FsEntry {
3835912×
                        content_hash: Some(hex(&on_disk)),
3845912×
                        graph_key: (!conflicted && a.eol.is_none())
3855912×
                            .then(|| keys.get(node).copied())
3865912×
                            .flatten(),
3875912×
                        ..FsEntry::new(NodeKind::File, mode.exec, Vec::new())
388
                    },
389
                );
390
            }
391
        }
392
        // Lockable files are read-only until locked (spec §18), whether
393
        // written now or left as they were.
39410440×
        for (path, e) in &entries {
39510440×
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
3962×
                let _ = set_readonly(&self.root.join(path), true);
39710438×
            }
398
        }
399
        // Prune directories left empty, deepest first.
400591×
        for d in dirs_to_prune.iter().rev() {
40172×
            let mut d = d.clone();
40288×
            while d != self.root
40319×
                && fs::read_dir(&d)
40419×
                    .map(|mut i| i.next().is_none())
40519×
                    .unwrap_or(false)
406
            {
40716×
                fs::remove_dir(&d)?;
40816×
                let Some(p) = d.parent() else { break };
40916×
                d = p.to_path_buf();
410
            }
411
        }
412
413591×
        drop(_render);
414
        // How the files rendered: which way each graph was ordered, summed
415
        // over every core (`OXY_TIMINGS`).
416591×
        crate::timing::report_totals();
417591×
        let recording = crate::timing::phase("checkout: record");
418591×
        let (op_ref, op) = self.head_op()?;
419591×
        let wc = self.new_working_copy(heads.clone(), "");
420591×
        let wc_hash = self.store.put_change(&wc)?;
421591×
        let mut view = op.view.clone();
422591×
        view.workspaces.insert(self.workspace, wc_hash);
423591×
        self.record_op(&[op_ref], command, view)?;
424591×
        drop(recording);
425591×
        let _t = crate::timing::phase("checkout: manifest");
426
        // The directories the new tree has, with any the old manifest kept
427
        // that still exist (holding only ignored files, say), statted now,
428
        // after the writes: the next check then need not list the tree. A
429
        // directory written just now is within the racy window, so for a
430
        // moment the check lists anyway.
431591×
        if !old_manifest.dirs.is_empty() {
432591×
            let mut dirs: BTreeSet<String> =
433690×
                old_manifest.dirs.iter().map(|(d, _)| d.clone()).collect();
434591×
            dirs.insert(String::new());
43510440×
            for p in entries.keys() {
43610440×
                let mut at = p.as_str();
43710573×
                while let Some((parent, _)) = at.rsplit_once('/') {
4389501×
                    if !dirs.insert(parent.to_string()) {
4399368×
                        break;
440133×
                    }
441133×
                    at = parent;
442
                }
443
            }
444
            use rayon::prelude::*;
445591×
            let root = &self.root;
446591×
            let dirs: Vec<(String, u128)> = dirs
447591×
                .into_par_iter()
448823×
                .filter_map(|d| {
449823×
                    let m = fs::metadata(root.join(&d)).ok().filter(|m| m.is_dir())?;
450807×
                    Some((d, prompt::mtime_ns(&m)))
451823×
                })
452591×
                .collect();
453591×
            let mut dirs = dirs;
454591×
            dirs.sort_unstable();
455591×
            *self.walked_dirs.borrow_mut() = Some((dirs, old_manifest.nested.clone()));
4560×
        }
457591×
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
458591×
        if report.conflicted && !self.bare {
45969×
            report.kept_both = self.settle_conflicts(command)?;
460522×
        }
461591×
        let _ = self.run_hook(
462591×
            "post-checkout",
463591×
            &format!(
464
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
465921×
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
466
                report.written,
467
                report.removed
468
            ),
469
        );
470591×
        Ok(report)
471594×
    }
472
473
    /// How many changes of the state at `from` the state `to` lacks: a walk
474
    /// down from `from` that stops at what `to` holds.
475592×
    fn count_lacking(&self, from: &[ChangeHash], to: &State) -> Result<usize> {
476592×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
477592×
        let mut stack: Vec<ChangeHash> = from.to_vec();
4781130×
        while let Some(h) = stack.pop() {
479538×
            if to.contains(&h) || !seen.insert(h) {
480425×
                continue;
481113×
            }
482113×
            stack.extend(self.store.get_change_lazy(&h)?.0.deps);
483
        }
484592×
        Ok(seen.len())
485592×
    }
486
487
    /// Refuse to leave uncommitted work behind unless `discard`.
488340×
    pub(crate) fn refuse_dirty(&self, snap: &SnapshotResult, discard: bool) -> Result<()> {
489340×
        if discard || (snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty()) {
490338×
            return Ok(());
4912×
        }
4922×
        let list: Vec<String> = snap
4932×
            .statuses
4942×
            .iter()
4952×
            .take(8)
4963×
            .map(|s| format!("{} {}", status_word(s.status), s.path))
4972×
            .collect();
4982×
        fail(format!(
499
            "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
5002×
            list.join(", "),
5012×
            if snap.statuses.len() > 8 { ", …" } else { "" }
502
        ))
503340×
    }
504
505
    /// Whether the file at `full` already holds `bytes` with this executable
506
    /// bit, so writing it again can be skipped.
50726×
    fn same_on_disk(&self, full: &Path, bytes: &[u8], exec: bool) -> bool {
50826×
        match fs::symlink_metadata(full) {
5098×
            Ok(m) if m.is_file() && m.len() == bytes.len() as u64 => {
5107×
                (!self.platform.exec_bits || is_executable(&m) == exec)
5117×
                    && fs::read(full).is_ok_and(|b| b == bytes)
512
            }
51319×
            _ => false,
514
        }
51526×
    }
516
517
    /// The absolute path for a repository path, refusing anything that would
518
    /// escape the workspace or write through a symlink (spec §7.7).
5193272×
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
5203272×
        let mut full = self.root.clone();
5213272×
        let comps: Vec<&str> = rel.split('/').collect();
5226285×
        for (i, comp) in comps.iter().enumerate() {
5236285×
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
5240×
                return fail(format!("refusing unsafe path {rel:?}"));
5256285×
            }
5266285×
            if i == 0 && *comp == OXY_DIR {
5270×
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
5286285×
            }
529
            // A `.git` path could plant hooks a side-by-side Git would run;
530
            // Git refuses them at any depth and in any case, and so does oxy.
5316285×
            if comp.eq_ignore_ascii_case(".git") {
5320×
                return fail(format!("refusing to write a .git path: {rel:?}"));
5336285×
            }
5346285×
            if i + 1 < comps.len() {
5353014×
                full.push(comp);
5363014×
                if let Ok(m) = fs::symlink_metadata(&full) {
5373013×
                    if m.file_type().is_symlink() {
5381×
                        return fail(format!(
539
                            "refusing to write through symlink {}",
5401×
                            full.display()
541
                        ));
5423012×
                    }
5431×
                }
5443271×
            } else {
5453271×
                full.push(comp);
5463271×
            }
547
        }
5483271×
        Ok(full)
5493272×
    }
550
55133×
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
55233×
        let full = self.safe_path(rel)?;
55333×
        if let Some(parent) = full.parent() {
55433×
            fs::create_dir_all(parent)?;
5550×
        }
55633×
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
5570×
            remove_any(&full)?;
55833×
        }
55933×
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
5601×
            set_readonly(&full, false)?;
56132×
        }
56233×
        fs::write(&full, bytes)?;
56333×
        set_executable(&full, exec)?;
56433×
        Ok(())
56533×
    }
566
5670×
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
5680×
        let full = self.safe_path(rel)?;
5690×
        if let Some(parent) = full.parent() {
5700×
            fs::create_dir_all(parent)?;
5710×
        }
5720×
        if fs::symlink_metadata(&full).is_ok() {
5730×
            remove_any(&full)?;
5740×
        }
575
        #[cfg(unix)]
576
        {
5770×
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
5780×
            Ok(())
579
        }
580
        #[cfg(not(unix))]
581
        {
582
            // Spec §7.7: without symlink support, write the target as a plain file.
583
            fs::write(&full, target)?;
584
            Ok(())
585
        }
5860×
    }
587
}
588
589
/// How a refusal names a path's change: "removed" is a file of the working
590
/// copy's base that is missing on disk.
5913×
fn status_word(s: ChangeStatus) -> &'static str {
5923×
    match s {
5930×
        ChangeStatus::Added => "added",
5942×
        ChangeStatus::Modified => "modified",
5951×
        ChangeStatus::Removed => "removed",
5960×
        ChangeStatus::Renamed => "renamed",
5970×
        ChangeStatus::ModeChanged => "mode changed",
5980×
        ChangeStatus::ConflictEdited => "conflict edited",
5990×
        ChangeStatus::Resolved => "resolved",
600
    }
6013×
}
602
603
/// Refuse a path that could escape the workspace (spec §7.7): an empty,
604
/// `.` or `..` component, a backslash, a first component `.oxy`, or a
605
/// `.git` component anywhere (it could plant Git hooks).
6065922×
fn check_path_name(rel: &str) -> Result<()> {
60711189×
    for (i, comp) in rel.split('/').enumerate() {
60811189×
        if comp.is_empty() || comp == "." || comp == ".." || comp.contains('\\') {
6091×
            return fail(format!("refusing unsafe path {rel:?}"));
61011188×
        }
61111188×
        if i == 0 && comp == OXY_DIR {
6121×
            return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
61311187×
        }
61411187×
        if comp.eq_ignore_ascii_case(".git") {
6154×
            return fail(format!("refusing to write a .git path: {rel:?}"));
61611183×
        }
617
    }
6185916×
    Ok(())
6195922×
}
620
621
/// A file on disk against what a checkout would write there.
622
#[derive(Clone, Copy, PartialEq, Eq)]
623
enum Disk {
624
    Same,
625
    Differs,
626
    Absent,
627
}
628
629
/// Whether the file at `full` already holds `bytes` with the right
630
/// executable bit. Touches no repository state, so it runs in parallel.
6315912×
fn compare_on_disk(full: &Path, bytes: &[u8], exec: bool, exec_bits: bool) -> Disk {
6325912×
    match fs::symlink_metadata(full) {
63335×
        Ok(m)
634206×
            if m.is_file()
635206×
                && m.len() == bytes.len() as u64
63660×
                && (!exec_bits || is_executable(&m) == exec)
63759×
                && fs::read(full).is_ok_and(|b| b == bytes) =>
638
        {
63935×
            Disk::Same
640
        }
641171×
        Ok(_) => Disk::Differs,
6425706×
        Err(_) => Disk::Absent,
643
    }
6445912×
}
645
646
/// Write a file whose directory exists, replacing whatever is there.
6475877×
fn write_file_at(full: &Path, bytes: &[u8], exec: bool) -> std::io::Result<()> {
6485877×
    match fs::symlink_metadata(full) {
649171×
        Ok(m) if m.is_file() => {
650171×
            if m.permissions().readonly() {
6510×
                set_readonly(full, false)?;
652171×
            }
653
        }
6540×
        Ok(_) => remove_any(full)?,
6555706×
        Err(_) => {}
656
    }
6575877×
    fs::write(full, bytes)?;
6585877×
    set_executable(full, exec)
6595877×
}
660
661
#[cfg(test)]
662
mod path_name_tests {
663
    use super::check_path_name;
664
665
    #[test]
6661×
    fn git_paths_are_refused_at_any_depth_and_case() {
6676×
        for bad in [
6681×
            ".git/hooks/post-checkout",
6691×
            "sub/.git/config",
6701×
            ".GIT/hooks/x",
6711×
            "a/.Git",
6721×
            ".oxy/x",
6731×
            "../x",
6741×
        ] {
6756×
            assert!(check_path_name(bad).is_err(), "{bad}");
676
        }
6774×
        for good in [
6781×
            "src/main.rs",
6791×
            ".gitignore",
6801×
            ".github/workflows/ci.yml",
6811×
            "a/.gitmodules",
6821×
        ] {
6834×
            assert!(check_path_name(good).is_ok(), "{good}");
684
        }
6851×
    }
686
}