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