OXYGENHUB

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

489 of 529 lines run, 88 of 98 functions · run #422 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.
28584×
    pub fn checkout(
29584×
        &self,
30584×
        heads: &[ChangeHash],
31584×
        discard: bool,
32584×
        command: &str,
33584×
    ) -> Result<CheckoutReport> {
34584×
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
35584×
    }
36
37
    /// [`Repo::checkout`], leaving the nested repositories at
38
    /// `keep_subrepos` as they are (their pins are carried work).
39589×
    pub(crate) fn checkout_keeping(
40589×
        &self,
41589×
        heads: &[ChangeHash],
42589×
        discard: bool,
43589×
        command: &str,
44589×
        keep_subrepos: &BTreeSet<String>,
45589×
    ) -> Result<CheckoutReport> {
46589×
        let _wc = self.lock_working_copy()?;
47589×
        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).
53589×
        let changed_paths: Vec<String> = if self.clean_by_manifest()? {
54250×
            Vec::new()
55
        } else {
56339×
            let snap = self.snapshot_status(command)?;
57339×
            self.refuse_dirty(&snap, discard)?;
58337×
            snap.statuses.iter().map(|s| s.path.clone()).collect()
59
        };
60587×
        let (_, wc_now) = self.working_copy()?;
61587×
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
62587×
        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.
66587×
        let mut target = self.load_state_indexed(heads)?;
67587×
        let heads = target.maximal(heads);
68587×
        let tv = crate::timing::phase("checkout: target view");
69587×
        let tview = self.tree_view(&mut target)?;
70587×
        drop(tv);
71587×
        let mut report = CheckoutReport::default();
72
        // Paths this file system cannot hold side by side (spec §7.7).
73587×
        report.notes.extend(
74587×
            self.platform
75587×
                .problems(tview.entries.keys().map(String::as_str)),
76
        );
77587×
        report.conflicted = tview.is_conflicted();
78587×
        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).
82587×
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
83587×
        let gone: BTreeSet<&str> = old_manifest
84587×
            .entries
85587×
            .keys()
86587×
            .map(String::as_str)
87587×
            .chain(changed.iter().copied())
887813×
            .filter(|p| !tview.entries.contains_key(*p))
89587×
            .collect();
903076×
        for path in gone {
913076×
            let dir = self.root.join(path);
923076×
            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;
973074×
            }
983074×
            let full = self.safe_path(path)?;
993074×
            if fs::symlink_metadata(&full).is_err() {
1001×
                continue;
1013073×
            }
1023073×
            fs::remove_file(&full)?;
1033073×
            report.removed += 1;
1043073×
            if report.removed_paths.len() < 5 {
105123×
                report.removed_paths.push(path.to_string());
1062950×
            }
1073073×
            if let Some(parent) = full.parent() {
1083073×
                dirs_to_prune.insert(parent.to_path_buf());
1093073×
            }
110
        }
111
112
        // The manifest after the checkout, built from what is known.
113587×
        let plan = crate::timing::phase("checkout: plan");
114587×
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
1155930×
        let hex = |b: &[u8]| *blake3::hash(b).as_bytes();
116
        // Text files to render, attribute files first (the others need them).
117587×
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
11810652×
        for (path, e) in tview.entries.iter() {
11910652×
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
120216×
                continue;
12110436×
            }
122
            // The manifest entry of a file the working copy has not changed,
123
            // with the right executable bit.
12410436×
            let exec_ok =
1254697×
                |m: &prompt::ManifestEntry| !self.platform.exec_bits || m.exec == e.mode.exec;
12610436×
            let entry = old_manifest
12710436×
                .entries
12810436×
                .get(path)
12910436×
                .filter(|m| !changed.contains(path.as_str()) && exec_ok(m));
13010436×
            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.
13410379×
                let key = target.graph_key(&e.node);
13510379×
                let proven = |m: &&prompt::ManifestEntry| {
1364662×
                    !is_attributes(path) && key.is_some() && m.graph == key
1374662×
                };
13810379×
                match entry.filter(proven) {
1394473×
                    Some(m) => {
1404473×
                        entries.insert(
1414473×
                            path.clone(),
1424473×
                            FsEntry {
1434473×
                                content_hash: Some(m.hash),
1444473×
                                graph_key: m.graph,
1454473×
                                unchanged: true,
1464473×
                                stat: Some((m.size, m.mtime_ns)),
1474473×
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
1484473×
                            },
1494473×
                        );
1504473×
                    }
1515906×
                    None => texts.push((path.clone(), e.node, e.mode)),
152
                }
15310379×
                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)?;
16910×
                if matches!(
17013×
                    sync,
171
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
1723×
                ) {
1733×
                    report.written += 1;
17410×
                }
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
231587×
        drop(plan);
232587×
        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.
23510978×
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
236587×
        let keys: HashMap<NodeId, [u8; 32]> = texts
237587×
            .iter()
2385906×
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
239587×
            .collect();
240587×
        let mut attrs = crate::attributes::Attributes::default();
2415906×
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
242587×
        let mut done = 0usize;
243587×
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
244587×
        if attr_count > 0 {
2456×
            batches.push(&texts[..attr_count]);
246581×
        }
247587×
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
248587×
        for batch in batches {
249
            use rayon::prelude::*;
250424×
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
251
            // A file added once and never edited is its text: no graph.
252424×
            let single: Vec<Option<crate::objects::TextRef>> =
2535906×
                nodes.iter().map(|n| target.single_text(n)).collect();
254424×
            let graphs: Vec<NodeId> = nodes
255424×
                .iter()
256424×
                .zip(&single)
2575906×
                .filter(|(_, s)| s.is_none())
258424×
                .map(|(n, _)| *n)
259424×
                .collect();
260424×
            let mut texts = {
261424×
                let _t = crate::timing::phase("checkout: read single texts");
262424×
                let wanted: Vec<crate::objects::TextRef> =
263424×
                    single.iter().flatten().copied().collect();
264424×
                self.single_texts(&wanted)?.into_iter()
265
            };
266
            {
267424×
                let _t = crate::timing::phase("checkout: build graphs");
268424×
                self.load_graphs_of(&mut target, &graphs)?;
269
            }
270424×
            let rendered: Vec<(Vec<u8>, bool)> = {
271424×
                let _t = crate::timing::phase("checkout: render");
272424×
                let mut out: Vec<Option<(Vec<u8>, bool)>> = single
273424×
                    .iter()
2745906×
                    .map(|s| s.as_ref().and_then(|_| texts.next().map(|t| (t, false))))
275424×
                    .collect();
276424×
                let from_graphs: Vec<(Vec<u8>, bool)> = graphs
277424×
                    .par_iter()
278424×
                    .map(|n| {
279344×
                        let (bytes, m) = target.render_file(n);
280344×
                        (bytes, m.is_conflicted())
281344×
                    })
282424×
                    .collect();
283424×
                let mut from_graphs = from_graphs.into_iter();
2845906×
                for o in out.iter_mut().filter(|o| o.is_none()) {
285344×
                    *o = from_graphs.next();
286344×
                }
287424×
                out.into_iter()
2885906×
                    .map(|o| o.expect("every file rendered"))
289424×
                    .collect()
290
            };
291
            #[cfg(test)]
292
            {
293232×
                let singles: Vec<NodeId> = nodes
294232×
                    .iter()
295232×
                    .zip(&single)
2965379×
                    .filter(|(_, s)| s.is_some())
297232×
                    .map(|(n, _)| *n)
298232×
                    .collect();
299232×
                self.load_graphs_of(&mut target, &singles)?;
3005379×
                for (n, (bytes, _)) in nodes.iter().zip(&rendered) {
3015379×
                    assert_eq!(
302
                        *bytes,
3035379×
                        target.render_file(n).0,
304
                        "a single text is its file's rendering"
305
                    );
306
                }
307
            }
308424×
            target.drop_graphs(&nodes);
309424×
            let _t = crate::timing::phase("checkout: write");
310424×
            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
                );
317418×
            }
318424×
            done += batch.len();
319424×
            let on_disk: Vec<Vec<u8>> = batch
320424×
                .iter()
321424×
                .zip(rendered.iter())
3225906×
                .map(|((path, _, _), (bytes, _))| {
3235906×
                    if attrs.lookup(path).eol == Some(crate::attributes::Eol::Crlf) {
3242×
                        crate::attributes::to_crlf(bytes)
325
                    } else {
3265904×
                        bytes.clone()
327
                    }
3285906×
                })
329424×
                .collect();
330
            // Each directory checked (no symlink on the way) and made once,
331
            // then the files compared and written on every core.
332424×
            let mut dirs: BTreeSet<&str> = BTreeSet::new();
3335906×
            for (path, _, _) in batch {
3345906×
                if let Some((dir, _)) = path.rsplit_once('/') {
3355254×
                    dirs.insert(dir);
3365254×
                }
337
            }
338424×
            for dir in dirs {
339163×
                let full = self.safe_path(dir)?;
340162×
                if !full.is_dir() {
341130×
                    if fs::symlink_metadata(&full).is_ok() {
3420×
                        remove_any(&full)?;
343130×
                    }
344130×
                    fs::create_dir_all(&full)?;
34532×
                }
346
            }
3475904×
            for (path, _, _) in batch {
3485904×
                check_path_name(path)?;
349
            }
350423×
            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).
355423×
            let plans: Vec<Disk> = batch
356423×
                .par_iter()
357423×
                .zip(on_disk.par_iter())
3585904×
                .map(|((path, _, mode), bytes)| {
3595904×
                    compare_on_disk(&root.join(path), bytes, mode.exec, exec_bits)
3605904×
                })
361423×
                .collect();
362423×
            let fresh: Vec<usize> = (0..batch.len())
3635904×
                .filter(|&i| plans[i] == Disk::Absent)
364423×
                .collect();
365423×
            fresh
366423×
                .par_iter()
3675705×
                .map(|&i| write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec))
368423×
                .collect::<std::io::Result<()>>()?;
3695904×
            for (i, plan) in plans.iter().enumerate() {
3705904×
                if *plan == Disk::Differs {
371167×
                    write_file_at(&root.join(&batch[i].0), &on_disk[i], batch[i].2.exec)?;
3725737×
                }
373
            }
3745904×
            report.written += plans.iter().filter(|p| **p != Disk::Same).count();
3755904×
            for (((path, node, mode), (_, conflicted)), on_disk) in
376423×
                batch.iter().zip(rendered).zip(on_disk)
377
            {
3785904×
                let a = attrs.lookup(path);
3795904×
                report.conflicted |= conflicted;
3805904×
                entries.insert(
3815904×
                    path.clone(),
382
                    FsEntry {
3835904×
                        content_hash: Some(hex(&on_disk)),
3845904×
                        graph_key: (!conflicted && a.eol.is_none())
3855904×
                            .then(|| keys.get(node).copied())
3865904×
                            .flatten(),
3875904×
                        ..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.
39410420×
        for (path, e) in &entries {
39510420×
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
3962×
                let _ = set_readonly(&self.root.join(path), true);
39710418×
            }
398
        }
399
        // Prune directories left empty, deepest first.
400586×
        for d in dirs_to_prune.iter().rev() {
40177×
            let mut d = d.clone();
40294×
            while d != self.root
40320×
                && fs::read_dir(&d)
40420×
                    .map(|mut i| i.next().is_none())
40520×
                    .unwrap_or(false)
406
            {
40717×
                fs::remove_dir(&d)?;
40817×
                let Some(p) = d.parent() else { break };
40917×
                d = p.to_path_buf();
410
            }
411
        }
412
413586×
        drop(_render);
414
        // How the files rendered: which way each graph was ordered, summed
415
        // over every core (`OXY_TIMINGS`).
416586×
        crate::timing::report_totals();
417586×
        let recording = crate::timing::phase("checkout: record");
418586×
        let (op_ref, op) = self.head_op()?;
419586×
        let wc = self.new_working_copy(heads.clone(), "");
420586×
        let wc_hash = self.store.put_change(&wc)?;
421586×
        let mut view = op.view.clone();
422586×
        view.workspaces.insert(self.workspace, wc_hash);
423586×
        self.record_op(&[op_ref], command, view)?;
424586×
        drop(recording);
425586×
        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.
431586×
        if !old_manifest.dirs.is_empty() {
432586×
            let mut dirs: BTreeSet<String> =
433683×
                old_manifest.dirs.iter().map(|(d, _)| d.clone()).collect();
434586×
            dirs.insert(String::new());
43510420×
            for p in entries.keys() {
43610420×
                let mut at = p.as_str();
43710551×
                while let Some((parent, _)) = at.rsplit_once('/') {
4389494×
                    if !dirs.insert(parent.to_string()) {
4399363×
                        break;
440131×
                    }
441131×
                    at = parent;
442
                }
443
            }
444
            use rayon::prelude::*;
445586×
            let root = &self.root;
446586×
            let dirs: Vec<(String, u128)> = dirs
447586×
                .into_par_iter()
448814×
                .filter_map(|d| {
449814×
                    let m = fs::metadata(root.join(&d)).ok().filter(|m| m.is_dir())?;
450797×
                    Some((d, prompt::mtime_ns(&m)))
451814×
                })
452586×
                .collect();
453586×
            let mut dirs = dirs;
454586×
            dirs.sort_unstable();
455586×
            *self.walked_dirs.borrow_mut() = Some((dirs, old_manifest.nested.clone()));
4560×
        }
457586×
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
458586×
        if report.conflicted && !self.bare {
45977×
            report.kept_both = self.settle_conflicts(command)?;
460509×
        }
461586×
        let _ = self.run_hook(
462586×
            "post-checkout",
463586×
            &format!(
464
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
465895×
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
466
                report.written,
467
                report.removed
468
            ),
469
        );
470586×
        Ok(report)
471589×
    }
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.
475587×
    fn count_lacking(&self, from: &[ChangeHash], to: &State) -> Result<usize> {
476587×
        let mut seen: HashSet<ChangeHash> = HashSet::new();
477587×
        let mut stack: Vec<ChangeHash> = from.to_vec();
4781115×
        while let Some(h) = stack.pop() {
479528×
            if to.contains(&h) || !seen.insert(h) {
480416×
                continue;
481112×
            }
482112×
            stack.extend(self.store.get_change_lazy(&h)?.0.deps);
483
        }
484587×
        Ok(seen.len())
485587×
    }
486
487
    /// Refuse to leave uncommitted work behind unless `discard`.
488339×
    pub(crate) fn refuse_dirty(&self, snap: &SnapshotResult, discard: bool) -> Result<()> {
489339×
        if discard || (snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty()) {
490337×
            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
        ))
503339×
    }
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).
5193270×
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
5203270×
        let mut full = self.root.clone();
5213270×
        let comps: Vec<&str> = rel.split('/').collect();
5226284×
        for (i, comp) in comps.iter().enumerate() {
5236284×
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
5240×
                return fail(format!("refusing unsafe path {rel:?}"));
5256284×
            }
5266284×
            if i == 0 && *comp == OXY_DIR {
5270×
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
5286284×
            }
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.
5316284×
            if comp.eq_ignore_ascii_case(".git") {
5320×
                return fail(format!("refusing to write a .git path: {rel:?}"));
5336284×
            }
5346284×
            if i + 1 < comps.len() {
5353015×
                full.push(comp);
5363015×
                if let Ok(m) = fs::symlink_metadata(&full) {
5373014×
                    if m.file_type().is_symlink() {
5381×
                        return fail(format!(
539
                            "refusing to write through symlink {}",
5401×
                            full.display()
541
                        ));
5423013×
                    }
5431×
                }
5443269×
            } else {
5453269×
                full.push(comp);
5463269×
            }
547
        }
5483269×
        Ok(full)
5493270×
    }
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).
6065914×
fn check_path_name(rel: &str) -> Result<()> {
60711174×
    for (i, comp) in rel.split('/').enumerate() {
60811174×
        if comp.is_empty() || comp == "." || comp == ".." || comp.contains('\\') {
6091×
            return fail(format!("refusing unsafe path {rel:?}"));
61011173×
        }
61111173×
        if i == 0 && comp == OXY_DIR {
6121×
            return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
61311172×
        }
61411172×
        if comp.eq_ignore_ascii_case(".git") {
6154×
            return fail(format!("refusing to write a .git path: {rel:?}"));
61611168×
        }
617
    }
6185908×
    Ok(())
6195914×
}
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.
6315904×
fn compare_on_disk(full: &Path, bytes: &[u8], exec: bool, exec_bits: bool) -> Disk {
6325904×
    match fs::symlink_metadata(full) {
63332×
        Ok(m)
634199×
            if m.is_file()
635199×
                && m.len() == bytes.len() as u64
63657×
                && (!exec_bits || is_executable(&m) == exec)
63756×
                && fs::read(full).is_ok_and(|b| b == bytes) =>
638
        {
63932×
            Disk::Same
640
        }
641167×
        Ok(_) => Disk::Differs,
6425705×
        Err(_) => Disk::Absent,
643
    }
6445904×
}
645
646
/// Write a file whose directory exists, replacing whatever is there.
6475872×
fn write_file_at(full: &Path, bytes: &[u8], exec: bool) -> std::io::Result<()> {
6485872×
    match fs::symlink_metadata(full) {
649167×
        Ok(m) if m.is_file() => {
650167×
            if m.permissions().readonly() {
6510×
                set_readonly(full, false)?;
652167×
            }
653
        }
6540×
        Ok(_) => remove_any(full)?,
6555705×
        Err(_) => {}
656
    }
6575872×
    fs::write(full, bytes)?;
6585872×
    set_executable(full, exec)
6595872×
}
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
}