OXYGENHUB
# a17fc622ca43 oxygen / crates / oxy-core / src / repo / checkout.rs
16.8 KiB · Rust · last changed Render a file that is one chain of lines without contracting it 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
/// Text files rendered at a time by a checkout: bounds its memory.
15
const CHECKOUT_BATCH: usize = 2048;
16
17
impl Repo {
18
    /// Move the working copy to the state whose heads are `heads` (spec §12.3):
19
    /// the working directory is rewritten to that state and a fresh
20
    /// working-copy change is started on it. The bookmark does not move.
21
    pub fn checkout(
22
        &self,
23
        heads: &[ChangeHash],
24
        discard: bool,
25
        command: &str,
26
    ) -> Result<CheckoutReport> {
27
        self.checkout_keeping(heads, discard, command, &BTreeSet::new())
28
    }
29
30
    /// [`Repo::checkout`], leaving the nested repositories at
31
    /// `keep_subrepos` as they are (their pins are carried work).
32
    pub(crate) fn checkout_keeping(
33
        &self,
34
        heads: &[ChangeHash],
35
        discard: bool,
36
        command: &str,
37
        keep_subrepos: &BTreeSet<String>,
38
    ) -> Result<CheckoutReport> {
39
        let _wc = self.lock_working_copy()?;
40
        // A status snapshot: files the manifest proves unchanged are neither
41
        // read nor rendered, and its base is history only (oxygen#35).
42
        let snap = self.snapshot_status(command)?;
43
        if !discard && (!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty()) {
44
            let list: Vec<String> = snap
45
                .statuses
46
                .iter()
47
                .take(8)
48
                .map(|s| format!("{} {}", status_word(s.status), s.path))
49
                .collect();
50
            return fail(format!(
51
                "the working copy has changes ({}{}); commit them, take them along with --carry, or drop them with --discard",
52
                list.join(", "),
53
                if snap.statuses.len() > 8 { ", …" } else { "" }
54
            ));
55
        }
56
        let old_manifest = self.read_manifest()?.map(|(_, _, m)| m).unwrap_or_default();
57
        let base = &snap.base;
58
        let base_files = &snap.base_snapshot.files;
59
        let changed: HashSet<&str> = snap.statuses.iter().map(|s| s.path.as_str()).collect();
60
        // The target's history; its file graphs are built a batch at a time
61
        // for the files that must be written, and dropped after.
62
        let mut target = self.load_state_history(heads)?;
63
        let heads = target.maximal(heads);
64
        let tview = target.tree().view();
65
        let mut report = CheckoutReport::default();
66
        // Paths this file system cannot hold side by side (spec §7.7).
67
        report.notes.extend(
68
            self.platform
69
                .problems(tview.entries.keys().map(String::as_str)),
70
        );
71
        report.conflicted = tview.is_conflicted();
72
73
        // Remove what the base or the working copy has and the target does
74
        // not. A nested repository is never deleted (spec §7.8).
75
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
76
        let gone: BTreeSet<&str> = base_files
77
            .iter()
78
            .filter(|(_, f)| f.kind != NodeKind::Dir)
79
            .map(|(p, _)| p.as_str())
80
            .chain(changed.iter().copied())
81
            .filter(|p| !tview.entries.contains_key(*p))
82
            .collect();
83
        for path in gone {
84
            if base_files
85
                .get(path)
86
                .is_some_and(|f| f.kind == NodeKind::Subrepo)
87
            {
88
                report
89
                    .notes
90
                    .push(format!("{path}: nested repository left in place"));
91
                continue;
92
            }
93
            let full = self.safe_path(path)?;
94
            if fs::symlink_metadata(&full).is_err() {
95
                continue;
96
            }
97
            fs::remove_file(&full)?;
98
            report.removed += 1;
99
            if let Some(parent) = full.parent() {
100
                dirs_to_prune.insert(parent.to_path_buf());
101
            }
102
        }
103
104
        // The manifest after the checkout, built from what is known.
105
        let mut entries: BTreeMap<String, FsEntry> = BTreeMap::new();
106
        let hex = |b: &[u8]| blake3::hash(b).to_hex().to_string();
107
        // Text files to render, attribute files first (the others need them).
108
        let mut texts: Vec<(String, NodeId, Mode)> = Vec::new();
109
        for (path, e) in &tview.entries {
110
            if e.kind == NodeKind::Dir || !self.in_scope(path) {
111
                continue;
112
            }
113
            let untouched = !changed.contains(path.as_str())
114
                && base_files
115
                    .get(path)
116
                    .is_some_and(|b| b.node == e.node && b.kind == e.kind && b.mode == e.mode);
117
            if e.kind == NodeKind::File && !e.mode.opaque {
118
                // Unchanged on disk (unrendered by the snapshot) and the same
119
                // graph in both states: nothing to read, render or write.
120
                let same_graph = untouched
121
                    && snap.base_snapshot.unrendered.contains(path)
122
                    && !is_attributes(path)
123
                    && base.graph_key(&e.node).is_some()
124
                    && base.graph_key(&e.node) == target.graph_key(&e.node);
125
                match old_manifest.entries.get(path).filter(|_| same_graph) {
126
                    Some(m) => {
127
                        entries.insert(
128
                            path.clone(),
129
                            FsEntry {
130
                                content_hash: Some(m.hash.clone()),
131
                                graph_key: m.graph.clone(),
132
                                unchanged: true,
133
                                ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
134
                            },
135
                        );
136
                    }
137
                    None => texts.push((path.clone(), e.node, e.mode)),
138
                }
139
                continue;
140
            }
141
            // Opaque files, symlinks and subrepos: their blobs.
142
            let blobs = target.live_blobs(&e.node);
143
            if blobs.len() > 1 {
144
                report.conflicted = true;
145
            }
146
            let Some(blob) = blobs.first().copied() else {
147
                continue;
148
            };
149
            if e.kind == NodeKind::Subrepo {
150
                if keep_subrepos.contains(path) {
151
                    continue;
152
                }
153
                let pin = crate::subrepo::Pin::decode(&self.read_blob(&blob)?)?;
154
                let sync = self.sync_subrepo(path, &pin, false)?;
155
                if matches!(
156
                    sync,
157
                    SubrepoSync::Updated | SubrepoSync::KeptBookmark { .. }
158
                ) {
159
                    report.written += 1;
160
                }
161
                report.notes.extend(sync.note(path));
162
                continue;
163
            }
164
            let same_blob = untouched && base.live_blobs(&e.node) == blobs;
165
            if let Some(m) = old_manifest
166
                .entries
167
                .get(path)
168
                .filter(|_| same_blob && blobs.len() == 1)
169
            {
170
                entries.insert(
171
                    path.clone(),
172
                    FsEntry {
173
                        content_hash: Some(m.hash.clone()),
174
                        blob: (e.kind == NodeKind::File).then_some(blob),
175
                        ..FsEntry::new(e.kind, e.mode.exec, Vec::new())
176
                    },
177
                );
178
                continue;
179
            }
180
            let bytes = self.read_blob(&blob)?;
181
            let full = self.root.join(path);
182
            if e.kind == NodeKind::Symlink {
183
                let same = fs::read_link(&full)
184
                    .is_ok_and(|t| t.to_string_lossy().as_bytes() == bytes.as_slice());
185
                if !same {
186
                    self.write_symlink(path, &bytes)?;
187
                    report.written += 1;
188
                }
189
                entries.insert(
190
                    path.clone(),
191
                    FsEntry {
192
                        content_hash: Some(hex(&bytes)),
193
                        ..FsEntry::new(NodeKind::Symlink, false, Vec::new())
194
                    },
195
                );
196
            } else {
197
                if !self.same_on_disk(&full, &bytes, e.mode.exec) {
198
                    self.write_file(path, &bytes, e.mode.exec)?;
199
                    report.written += 1;
200
                }
201
                entries.insert(
202
                    path.clone(),
203
                    FsEntry {
204
                        content_hash: Some(hex(&bytes)),
205
                        blob: (blobs.len() == 1).then_some(blob),
206
                        ..FsEntry::new(NodeKind::File, e.mode.exec, Vec::new())
207
                    },
208
                );
209
            }
210
            for (i, b) in blobs.iter().enumerate().skip(1) {
211
                self.write_file(
212
                    &format!("{path}.oxy-conflict-{}", i + 1),
213
                    &self.read_blob(b)?,
214
                    e.mode.exec,
215
                )?;
216
            }
217
        }
218
219
        // Render and write text files a batch at a time; attribute files
220
        // come first, since the others' line endings and locks follow them.
221
        texts.sort_by_key(|(p, _, _)| !is_attributes(p));
222
        let keys: HashMap<NodeId, [u8; 32]> = texts
223
            .iter()
224
            .filter_map(|(_, n, _)| Some((*n, target.graph_key(n)?)))
225
            .collect();
226
        let mut attrs = crate::attributes::Attributes::default();
227
        let attr_count = texts.iter().filter(|(p, _, _)| is_attributes(p)).count();
228
        let mut done = 0usize;
229
        let mut batches: Vec<&[(String, NodeId, Mode)]> = Vec::new();
230
        if attr_count > 0 {
231
            batches.push(&texts[..attr_count]);
232
        }
233
        batches.extend(texts[attr_count..].chunks(CHECKOUT_BATCH));
234
        for batch in batches {
235
            use rayon::prelude::*;
236
            let nodes: Vec<NodeId> = batch.iter().map(|(_, n, _)| *n).collect();
237
            {
238
                let _t = crate::timing::phase("checkout: build graphs");
239
                self.load_graphs_of(&mut target, &nodes)?;
240
            }
241
            let rendered: Vec<(Vec<u8>, bool)> = {
242
                let _t = crate::timing::phase("checkout: render");
243
                nodes
244
                    .par_iter()
245
                    .map(|n| {
246
                        let (bytes, m) = target.render_file(n);
247
                        (bytes, m.is_conflicted())
248
                    })
249
                    .collect()
250
            };
251
            target.drop_graphs(&nodes);
252
            let _t = crate::timing::phase("checkout: write");
253
            if done == 0 && attr_count > 0 {
254
                attrs = crate::attributes::Attributes::from_files(
255
                    batch
256
                        .iter()
257
                        .zip(&rendered)
258
                        .map(|((p, _, _), (b, _))| (p.as_str(), b.as_slice())),
259
                );
260
            }
261
            done += batch.len();
262
            for ((path, node, mode), (bytes, conflicted)) in batch.iter().zip(rendered) {
263
                let a = attrs.lookup(path);
264
                let crlf = a.eol == Some(crate::attributes::Eol::Crlf);
265
                let on_disk: Vec<u8> = if crlf {
266
                    crate::attributes::to_crlf(&bytes)
267
                } else {
268
                    bytes
269
                };
270
                if !self.same_on_disk(&self.root.join(path), &on_disk, mode.exec) {
271
                    self.write_file(path, &on_disk, mode.exec)?;
272
                    report.written += 1;
273
                }
274
                report.conflicted |= conflicted;
275
                entries.insert(
276
                    path.clone(),
277
                    FsEntry {
278
                        content_hash: Some(hex(&on_disk)),
279
                        graph_key: (!conflicted && a.eol.is_none())
280
                            .then(|| keys.get(node).map(|k| ObjectRef(*k).to_hex()))
281
                            .flatten(),
282
                        ..FsEntry::new(NodeKind::File, mode.exec, Vec::new())
283
                    },
284
                );
285
            }
286
        }
287
        // Lockable files are read-only until locked (spec §18), whether
288
        // written now or left as they were.
289
        for (path, e) in &entries {
290
            if e.kind == NodeKind::File && attrs.lookup(path).lockable && !self.is_locked(path) {
291
                let _ = set_readonly(&self.root.join(path), true);
292
            }
293
        }
294
        // Prune directories left empty, deepest first.
295
        for d in dirs_to_prune.iter().rev() {
296
            let mut d = d.clone();
297
            while d != self.root
298
                && fs::read_dir(&d)
299
                    .map(|mut i| i.next().is_none())
300
                    .unwrap_or(false)
301
            {
302
                fs::remove_dir(&d)?;
303
                let Some(p) = d.parent() else { break };
304
                d = p.to_path_buf();
305
            }
306
        }
307
308
        let (op_ref, op) = self.head_op()?;
309
        let wc = self.new_working_copy(heads.clone(), "");
310
        let wc_hash = self.store.put_change(&wc)?;
311
        let mut view = op.view.clone();
312
        view.workspaces.insert(self.workspace, wc_hash);
313
        self.record_op(&[op_ref], command, view)?;
314
        self.write_manifest_entries(report.conflicted, false, &entries, &HashMap::new())?;
315
        let _ = self.run_hook(
316
            "post-checkout",
317
            &format!(
318
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
319
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
320
                report.written,
321
                report.removed
322
            ),
323
        );
324
        Ok(report)
325
    }
326
327
    /// Whether the file at `full` already holds `bytes` with this executable
328
    /// bit, so writing it again can be skipped.
329
    fn same_on_disk(&self, full: &Path, bytes: &[u8], exec: bool) -> bool {
330
        match fs::symlink_metadata(full) {
331
            Ok(m) if m.is_file() && m.len() == bytes.len() as u64 => {
332
                (!self.platform.exec_bits || is_executable(&m) == exec)
333
                    && fs::read(full).is_ok_and(|b| b == bytes)
334
            }
335
            _ => false,
336
        }
337
    }
338
339
    /// The absolute path for a repository path, refusing anything that would
340
    /// escape the workspace or write through a symlink (spec §7.7).
341
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
342
        let mut full = self.root.clone();
343
        let comps: Vec<&str> = rel.split('/').collect();
344
        for (i, comp) in comps.iter().enumerate() {
345
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
346
                return fail(format!("refusing unsafe path {rel:?}"));
347
            }
348
            if i == 0 && *comp == OXY_DIR {
349
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
350
            }
351
            if i + 1 < comps.len() {
352
                full.push(comp);
353
                if let Ok(m) = fs::symlink_metadata(&full) {
354
                    if m.file_type().is_symlink() {
355
                        return fail(format!(
356
                            "refusing to write through symlink {}",
357
                            full.display()
358
                        ));
359
                    }
360
                }
361
            } else {
362
                full.push(comp);
363
            }
364
        }
365
        Ok(full)
366
    }
367
368
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
369
        let full = self.safe_path(rel)?;
370
        if let Some(parent) = full.parent() {
371
            fs::create_dir_all(parent)?;
372
        }
373
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
374
            remove_any(&full)?;
375
        }
376
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
377
            set_readonly(&full, false)?;
378
        }
379
        fs::write(&full, bytes)?;
380
        set_executable(&full, exec)?;
381
        Ok(())
382
    }
383
384
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
385
        let full = self.safe_path(rel)?;
386
        if let Some(parent) = full.parent() {
387
            fs::create_dir_all(parent)?;
388
        }
389
        if fs::symlink_metadata(&full).is_ok() {
390
            remove_any(&full)?;
391
        }
392
        #[cfg(unix)]
393
        {
394
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
395
            Ok(())
396
        }
397
        #[cfg(not(unix))]
398
        {
399
            // Spec §7.7: without symlink support, write the target as a plain file.
400
            fs::write(&full, target)?;
401
            Ok(())
402
        }
403
    }
404
}
405
406
/// How a refusal names a path's change: "removed" is a file of the working
407
/// copy's base that is missing on disk.
408
fn status_word(s: ChangeStatus) -> &'static str {
409
    match s {
410
        ChangeStatus::Added => "added",
411
        ChangeStatus::Modified => "modified",
412
        ChangeStatus::Removed => "removed",
413
        ChangeStatus::Renamed => "renamed",
414
        ChangeStatus::ModeChanged => "mode changed",
415
        ChangeStatus::ConflictEdited => "conflict edited",
416
        ChangeStatus::Resolved => "resolved",
417
    }
418
}