OXYGENHUB
# cdb5beba7f05 oxygen / crates / oxy-core / src / repo / checkout.rs
7.1 KiB · Rust · last changed .oxyattributes: binary, text, eol=lf|crlf, nocompress (raw chunks in packs), lockable with advisory local oxy lock/unlock (spec 0.6j) 1 month ago source blame history raw
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
}
11
12
impl Repo {
13
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
14
    /// the working directory is rewritten to that state and a fresh
15
    /// working-copy change is started on it. The bookmark does not move.
16
    pub fn checkout(&self, heads: &[ChangeHash], discard: bool, command: &str) -> Result<CheckoutReport> {
17
        let snap = self.snapshot(command)?;
18
        if !discard && (!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty()) {
19
            return fail("the working copy has changes; commit them first or pass --discard");
20
        }
21
        let target_state = self.load_state(heads)?;
22
        let heads = target_state.maximal(heads);
23
        let target = target_state.materialize();
24
        let attrs = Repo::state_attributes(&target);
25
        let current = self.walk_working_copy()?;
26
        let mut report = CheckoutReport::default();
27
28
        // Remove tracked paths that the target does not have.
29
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
30
        for path in current.keys() {
31
            if !target.files.contains_key(path) {
32
                let full = self.safe_path(path)?;
33
                fs::remove_file(&full)?;
34
                report.removed += 1;
35
                if let Some(parent) = full.parent() {
36
                    dirs_to_prune.insert(parent.to_path_buf());
37
                }
38
            }
39
        }
40
        // Write target files that differ (only inside the sparse filter).
41
        for (path, f) in &target.files {
42
            if !self.in_scope(path) {
43
                continue;
44
            }
45
            match &f.content {
46
                FileContent::Dir => continue,
47
                FileContent::Text { bytes, .. } => {
48
                    let a = attrs.lookup(path);
49
                    let on_disk: std::borrow::Cow<[u8]> = if a.eol == Some(crate::attributes::Eol::Crlf) { crate::attributes::to_crlf(bytes).into() } else { bytes.as_slice().into() };
50
                    let same = current.get(path).is_some_and(|c| c.kind == NodeKind::File && c.content == *on_disk && c.exec == f.mode.exec);
51
                    if !same {
52
                        self.write_file(path, &on_disk, f.mode.exec)?;
53
                        report.written += 1;
54
                    }
55
                    if a.lockable && !self.is_locked(path) {
56
                        let _ = set_readonly(&self.root.join(path), true);
57
                    }
58
                }
59
                FileContent::Opaque { blobs } => {
60
                    let Some(blob) = blobs.first() else { continue };
61
                    let bytes = self.read_blob(blob)?;
62
                    if f.kind == NodeKind::Symlink {
63
                        let same = current.get(path).is_some_and(|c| c.kind == NodeKind::Symlink && c.content == bytes);
64
                        if !same {
65
                            self.write_symlink(path, &bytes)?;
66
                            report.written += 1;
67
                        }
68
                    } else {
69
                        let same = current.get(path).is_some_and(|c| c.kind == NodeKind::File && c.content == bytes && c.exec == f.mode.exec);
70
                        if !same {
71
                            self.write_file(path, &bytes, f.mode.exec)?;
72
                            report.written += 1;
73
                        }
74
                        if attrs.lookup(path).lockable && !self.is_locked(path) {
75
                            let _ = set_readonly(&self.root.join(path), true);
76
                        }
77
                    }
78
                    if blobs.len() > 1 {
79
                        for (i, b) in blobs.iter().enumerate().skip(1) {
80
                            self.write_file(&format!("{path}.oxy-conflict-{}", i + 1), &self.read_blob(b)?, f.mode.exec)?;
81
                        }
82
                    }
83
                }
84
            }
85
        }
86
        // Prune directories left empty, deepest first.
87
        for d in dirs_to_prune.iter().rev() {
88
            let mut d = d.clone();
89
            while d != self.root && fs::read_dir(&d).map(|mut i| i.next().is_none()).unwrap_or(false) {
90
                fs::remove_dir(&d)?;
91
                let Some(p) = d.parent() else { break };
92
                d = p.to_path_buf();
93
            }
94
        }
95
96
        let (op_ref, op) = self.head_op()?;
97
        let wc = self.new_working_copy(heads, "");
98
        let wc_hash = self.store.put_change(&wc)?;
99
        let mut view = op.view.clone();
100
        view.workspaces.insert(self.workspace, wc_hash);
101
        self.record_op(&[op_ref], command, view)?;
102
        report.conflicted = target.is_conflicted();
103
        self.write_manifest(report.conflicted, false)?;
104
        Ok(report)
105
    }
106
107
    /// The absolute path for a repository path, refusing anything that would
108
    /// escape the workspace or write through a symlink (spec §7.7).
109
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
110
        let mut full = self.root.clone();
111
        let comps: Vec<&str> = rel.split('/').collect();
112
        for (i, comp) in comps.iter().enumerate() {
113
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
114
                return fail(format!("refusing unsafe path {rel:?}"));
115
            }
116
            if i == 0 && *comp == OXY_DIR {
117
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
118
            }
119
            if i + 1 < comps.len() {
120
                full.push(comp);
121
                if let Ok(m) = fs::symlink_metadata(&full) {
122
                    if m.file_type().is_symlink() {
123
                        return fail(format!("refusing to write through symlink {}", full.display()));
124
                    }
125
                }
126
            } else {
127
                full.push(comp);
128
            }
129
        }
130
        Ok(full)
131
    }
132
133
    fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
134
        let full = self.safe_path(rel)?;
135
        if let Some(parent) = full.parent() {
136
            fs::create_dir_all(parent)?;
137
        }
138
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
139
            remove_any(&full)?;
140
        }
141
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
142
            set_readonly(&full, false)?;
143
        }
144
        fs::write(&full, bytes)?;
145
        set_executable(&full, exec)?;
146
        Ok(())
147
    }
148
149
    fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
150
        let full = self.safe_path(rel)?;
151
        if let Some(parent) = full.parent() {
152
            fs::create_dir_all(parent)?;
153
        }
154
        if fs::symlink_metadata(&full).is_ok() {
155
            remove_any(&full)?;
156
        }
157
        #[cfg(unix)]
158
        {
159
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
160
            Ok(())
161
        }
162
        #[cfg(not(unix))]
163
        {
164
            // Spec §7.7: without symlink support, write the target as a plain file.
165
            fs::write(&full, target)?;
166
            Ok(())
167
        }
168
    }
169
}