OXYGENHUB
# b9bf7eec1f2d oxygen / crates / oxy-core / src / repo / checkout.rs
11.0 KiB · Rust · last changed Hold the working-copy lock through every working-copy write 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
    /// Nested repositories that could not be moved, and other remarks.
11
    pub notes: Vec<String>,
12
}
13
14
impl Repo {
15
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
16
    /// the working directory is rewritten to that state and a fresh
17
    /// working-copy change is started on it. The bookmark does not move.
18
    pub fn checkout(
19
        &self,
20
        heads: &[ChangeHash],
21
        discard: bool,
22
        command: &str,
23
    ) -> Result<CheckoutReport> {
24
        let _wc = self.lock_working_copy()?;
25
        let snap = self.snapshot(command)?;
26
        if !discard && (!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty()) {
27
            let list: Vec<String> = snap
28
                .statuses
29
                .iter()
30
                .take(8)
31
                .map(|s| format!("{} {}", status_word(s.status), s.path))
32
                .collect();
33
            return fail(format!(
34
                "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
35
                list.join(", "),
36
                if snap.statuses.len() > 8 { ", …" } else { "" }
37
            ));
38
        }
39
        let target_state = self.load_state(heads)?;
40
        let heads = target_state.maximal(heads);
41
        let target = target_state.materialize();
42
        let attrs = Repo::state_attributes(&target);
43
        let current = self.walk_working_copy()?;
44
        let mut report = CheckoutReport::default();
45
        // Paths this file system cannot hold side by side (spec §7.7).
46
        report.notes.extend(
47
            self.platform
48
                .problems(target.files.keys().map(String::as_str)),
49
        );
50
51
        // Remove tracked paths that the target does not have. A nested
52
        // repository is never deleted (spec §7.8); it is left in place.
53
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
54
        for (path, entry) in &current {
55
            if !target.files.contains_key(path) {
56
                if entry.kind == NodeKind::Subrepo {
57
                    report
58
                        .notes
59
                        .push(format!("{path}: nested repository left in place"));
60
                    continue;
61
                }
62
                let full = self.safe_path(path)?;
63
                fs::remove_file(&full)?;
64
                report.removed += 1;
65
                if let Some(parent) = full.parent() {
66
                    dirs_to_prune.insert(parent.to_path_buf());
67
                }
68
            }
69
        }
70
        // Write target files that differ (only inside the sparse filter).
71
        for (path, f) in &target.files {
72
            if !self.in_scope(path) {
73
                continue;
74
            }
75
            match &f.content {
76
                FileContent::Dir => continue,
77
                FileContent::Text { bytes, .. } => {
78
                    let a = attrs.lookup(path);
79
                    let on_disk: std::borrow::Cow<[u8]> =
80
                        if a.eol == Some(crate::attributes::Eol::Crlf) {
81
                            crate::attributes::to_crlf(bytes).into()
82
                        } else {
83
                            bytes.as_slice().into()
84
                        };
85
                    let same = current.get(path).is_some_and(|c| {
86
                        c.kind == NodeKind::File
87
                            && c.content == *on_disk
88
                            && (!self.platform.exec_bits || c.exec == f.mode.exec)
89
                    });
90
                    if !same {
91
                        self.write_file(path, &on_disk, f.mode.exec)?;
92
                        report.written += 1;
93
                    }
94
                    if a.lockable && !self.is_locked(path) {
95
                        let _ = set_readonly(&self.root.join(path), true);
96
                    }
97
                }
98
                FileContent::Opaque { blobs } => {
99
                    let Some(blob) = blobs.first() else { continue };
100
                    let bytes = self.read_blob(blob)?;
101
                    if f.kind == NodeKind::Subrepo {
102
                        let pin = crate::subrepo::Pin::decode(&bytes)?;
103
                        match self.sync_subrepo(path, &pin, false)? {
104
                            SubrepoSync::Updated => report.written += 1,
105
                            SubrepoSync::UpToDate => {}
106
                            SubrepoSync::Missing => report.notes.push(format!("{path}: nested repository not present; run oxy submodule update --init")),
107
                            SubrepoSync::Dirty => report.notes.push(format!("{path}: nested repository has uncommitted changes; left as is")),
108
                            SubrepoSync::Failed(e) => report.notes.push(format!("{path}: {e}")),
109
                        }
110
                        continue;
111
                    }
112
                    if f.kind == NodeKind::Symlink {
113
                        let same = current
114
                            .get(path)
115
                            .is_some_and(|c| c.kind == NodeKind::Symlink && c.content == bytes);
116
                        if !same {
117
                            self.write_symlink(path, &bytes)?;
118
                            report.written += 1;
119
                        }
120
                    } else {
121
                        let same = current.get(path).is_some_and(|c| {
122
                            c.kind == NodeKind::File
123
                                && c.content == bytes
124
                                && (!self.platform.exec_bits || c.exec == f.mode.exec)
125
                        });
126
                        if !same {
127
                            self.write_file(path, &bytes, f.mode.exec)?;
128
                            report.written += 1;
129
                        }
130
                        if attrs.lookup(path).lockable && !self.is_locked(path) {
131
                            let _ = set_readonly(&self.root.join(path), true);
132
                        }
133
                    }
134
                    if blobs.len() > 1 {
135
                        for (i, b) in blobs.iter().enumerate().skip(1) {
136
                            self.write_file(
137
                                &format!("{path}.oxy-conflict-{}", i + 1),
138
                                &self.read_blob(b)?,
139
                                f.mode.exec,
140
                            )?;
141
                        }
142
                    }
143
                }
144
            }
145
        }
146
        // Prune directories left empty, deepest first.
147
        for d in dirs_to_prune.iter().rev() {
148
            let mut d = d.clone();
149
            while d != self.root
150
                && fs::read_dir(&d)
151
                    .map(|mut i| i.next().is_none())
152
                    .unwrap_or(false)
153
            {
154
                fs::remove_dir(&d)?;
155
                let Some(p) = d.parent() else { break };
156
                d = p.to_path_buf();
157
            }
158
        }
159
160
        let (op_ref, op) = self.head_op()?;
161
        let wc = self.new_working_copy(heads.clone(), "");
162
        let wc_hash = self.store.put_change(&wc)?;
163
        let mut view = op.view.clone();
164
        view.workspaces.insert(self.workspace, wc_hash);
165
        self.record_op(&[op_ref], command, view)?;
166
        report.conflicted = target.is_conflicted();
167
        let blobs: HashMap<String, ObjectRef> = target
168
            .files
169
            .iter()
170
            .filter_map(|(p, f)| match &f.content {
171
                FileContent::Opaque { blobs } if f.kind == NodeKind::File && blobs.len() == 1 => {
172
                    Some((p.clone(), blobs[0]))
173
                }
174
                _ => None,
175
            })
176
            .collect();
177
        let entries = self.walk_working_copy_with(None, &Self::tracked_kinds(&target), None)?;
178
        self.write_manifest_entries(report.conflicted, false, &entries, &blobs)?;
179
        let _ = self.run_hook(
180
            "post-checkout",
181
            &format!(
182
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
183
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
184
                report.written,
185
                report.removed
186
            ),
187
        );
188
        Ok(report)
189
    }
190
191
    /// The absolute path for a repository path, refusing anything that would
192
    /// escape the workspace or write through a symlink (spec §7.7).
193
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
194
        let mut full = self.root.clone();
195
        let comps: Vec<&str> = rel.split('/').collect();
196
        for (i, comp) in comps.iter().enumerate() {
197
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
198
                return fail(format!("refusing unsafe path {rel:?}"));
199
            }
200
            if i == 0 && *comp == OXY_DIR {
201
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
202
            }
203
            if i + 1 < comps.len() {
204
                full.push(comp);
205
                if let Ok(m) = fs::symlink_metadata(&full) {
206
                    if m.file_type().is_symlink() {
207
                        return fail(format!(
208
                            "refusing to write through symlink {}",
209
                            full.display()
210
                        ));
211
                    }
212
                }
213
            } else {
214
                full.push(comp);
215
            }
216
        }
217
        Ok(full)
218
    }
219
220
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
221
        let full = self.safe_path(rel)?;
222
        if let Some(parent) = full.parent() {
223
            fs::create_dir_all(parent)?;
224
        }
225
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
226
            remove_any(&full)?;
227
        }
228
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
229
            set_readonly(&full, false)?;
230
        }
231
        fs::write(&full, bytes)?;
232
        set_executable(&full, exec)?;
233
        Ok(())
234
    }
235
236
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
237
        let full = self.safe_path(rel)?;
238
        if let Some(parent) = full.parent() {
239
            fs::create_dir_all(parent)?;
240
        }
241
        if fs::symlink_metadata(&full).is_ok() {
242
            remove_any(&full)?;
243
        }
244
        #[cfg(unix)]
245
        {
246
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
247
            Ok(())
248
        }
249
        #[cfg(not(unix))]
250
        {
251
            // Spec §7.7: without symlink support, write the target as a plain file.
252
            fs::write(&full, target)?;
253
            Ok(())
254
        }
255
    }
256
}
257
258
/// How a refusal names a path's change: "removed" is a file of the working
259
/// copy's base that is missing on disk.
260
fn status_word(s: ChangeStatus) -> &'static str {
261
    match s {
262
        ChangeStatus::Added => "added",
263
        ChangeStatus::Modified => "modified",
264
        ChangeStatus::Removed => "removed",
265
        ChangeStatus::Renamed => "renamed",
266
        ChangeStatus::ModeChanged => "mode changed",
267
        ChangeStatus::ConflictEdited => "conflict edited",
268
        ChangeStatus::Resolved => "resolved",
269
    }
270
}