OXYGENHUB
# 214a3f27f8f6 oxygen / crates / oxy-core / src / repo / checkout.rs
9.7 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 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 snap = self.snapshot(command)?;
25
        if !discard && (!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty()) {
26
            return fail("the working copy has changes; commit them first or pass --discard");
27
        }
28
        let target_state = self.load_state(heads)?;
29
        let heads = target_state.maximal(heads);
30
        let target = target_state.materialize();
31
        let attrs = Repo::state_attributes(&target);
32
        let current = self.walk_working_copy()?;
33
        let mut report = CheckoutReport::default();
34
35
        // Remove tracked paths that the target does not have. A nested
36
        // repository is never deleted (spec §7.8); it is left in place.
37
        let mut dirs_to_prune: BTreeSet<PathBuf> = BTreeSet::new();
38
        for (path, entry) in &current {
39
            if !target.files.contains_key(path) {
40
                if entry.kind == NodeKind::Subrepo {
41
                    report
42
                        .notes
43
                        .push(format!("{path}: nested repository left in place"));
44
                    continue;
45
                }
46
                let full = self.safe_path(path)?;
47
                fs::remove_file(&full)?;
48
                report.removed += 1;
49
                if let Some(parent) = full.parent() {
50
                    dirs_to_prune.insert(parent.to_path_buf());
51
                }
52
            }
53
        }
54
        // Write target files that differ (only inside the sparse filter).
55
        for (path, f) in &target.files {
56
            if !self.in_scope(path) {
57
                continue;
58
            }
59
            match &f.content {
60
                FileContent::Dir => continue,
61
                FileContent::Text { bytes, .. } => {
62
                    let a = attrs.lookup(path);
63
                    let on_disk: std::borrow::Cow<[u8]> =
64
                        if a.eol == Some(crate::attributes::Eol::Crlf) {
65
                            crate::attributes::to_crlf(bytes).into()
66
                        } else {
67
                            bytes.as_slice().into()
68
                        };
69
                    let same = current.get(path).is_some_and(|c| {
70
                        c.kind == NodeKind::File && c.content == *on_disk && c.exec == f.mode.exec
71
                    });
72
                    if !same {
73
                        self.write_file(path, &on_disk, f.mode.exec)?;
74
                        report.written += 1;
75
                    }
76
                    if a.lockable && !self.is_locked(path) {
77
                        let _ = set_readonly(&self.root.join(path), true);
78
                    }
79
                }
80
                FileContent::Opaque { blobs } => {
81
                    let Some(blob) = blobs.first() else { continue };
82
                    let bytes = self.read_blob(blob)?;
83
                    if f.kind == NodeKind::Subrepo {
84
                        let pin = crate::subrepo::Pin::decode(&bytes)?;
85
                        match self.sync_subrepo(path, &pin, false)? {
86
                            SubrepoSync::Updated => report.written += 1,
87
                            SubrepoSync::UpToDate => {}
88
                            SubrepoSync::Missing => report.notes.push(format!("{path}: nested repository not present; run oxy submodule update --init")),
89
                            SubrepoSync::Dirty => report.notes.push(format!("{path}: nested repository has uncommitted changes; left as is")),
90
                            SubrepoSync::Failed(e) => report.notes.push(format!("{path}: {e}")),
91
                        }
92
                        continue;
93
                    }
94
                    if f.kind == NodeKind::Symlink {
95
                        let same = current
96
                            .get(path)
97
                            .is_some_and(|c| c.kind == NodeKind::Symlink && c.content == bytes);
98
                        if !same {
99
                            self.write_symlink(path, &bytes)?;
100
                            report.written += 1;
101
                        }
102
                    } else {
103
                        let same = current.get(path).is_some_and(|c| {
104
                            c.kind == NodeKind::File && c.content == bytes && c.exec == f.mode.exec
105
                        });
106
                        if !same {
107
                            self.write_file(path, &bytes, f.mode.exec)?;
108
                            report.written += 1;
109
                        }
110
                        if attrs.lookup(path).lockable && !self.is_locked(path) {
111
                            let _ = set_readonly(&self.root.join(path), true);
112
                        }
113
                    }
114
                    if blobs.len() > 1 {
115
                        for (i, b) in blobs.iter().enumerate().skip(1) {
116
                            self.write_file(
117
                                &format!("{path}.oxy-conflict-{}", i + 1),
118
                                &self.read_blob(b)?,
119
                                f.mode.exec,
120
                            )?;
121
                        }
122
                    }
123
                }
124
            }
125
        }
126
        // Prune directories left empty, deepest first.
127
        for d in dirs_to_prune.iter().rev() {
128
            let mut d = d.clone();
129
            while d != self.root
130
                && fs::read_dir(&d)
131
                    .map(|mut i| i.next().is_none())
132
                    .unwrap_or(false)
133
            {
134
                fs::remove_dir(&d)?;
135
                let Some(p) = d.parent() else { break };
136
                d = p.to_path_buf();
137
            }
138
        }
139
140
        let (op_ref, op) = self.head_op()?;
141
        let wc = self.new_working_copy(heads.clone(), "");
142
        let wc_hash = self.store.put_change(&wc)?;
143
        let mut view = op.view.clone();
144
        view.workspaces.insert(self.workspace, wc_hash);
145
        self.record_op(&[op_ref], command, view)?;
146
        report.conflicted = target.is_conflicted();
147
        let blobs: HashMap<String, ObjectRef> = target
148
            .files
149
            .iter()
150
            .filter_map(|(p, f)| match &f.content {
151
                FileContent::Opaque { blobs } if f.kind == NodeKind::File && blobs.len() == 1 => {
152
                    Some((p.clone(), blobs[0]))
153
                }
154
                _ => None,
155
            })
156
            .collect();
157
        let entries = self.walk_working_copy_with(None, &Self::tracked_kinds(&target))?;
158
        self.write_manifest_entries(report.conflicted, false, &entries, &blobs)?;
159
        let _ = self.run_hook(
160
            "post-checkout",
161
            &format!(
162
                "{{\"event\":\"post-checkout\",\"heads\":{},\"written\":{},\"removed\":{}}}",
163
                json_array(heads.iter().map(|h| json_str(&h.to_hex()))),
164
                report.written,
165
                report.removed
166
            ),
167
        );
168
        Ok(report)
169
    }
170
171
    /// The absolute path for a repository path, refusing anything that would
172
    /// escape the workspace or write through a symlink (spec §7.7).
173
    fn safe_path(&self, rel: &str) -> Result<PathBuf> {
174
        let mut full = self.root.clone();
175
        let comps: Vec<&str> = rel.split('/').collect();
176
        for (i, comp) in comps.iter().enumerate() {
177
            if comp.is_empty() || *comp == "." || *comp == ".." || comp.contains('\\') {
178
                return fail(format!("refusing unsafe path {rel:?}"));
179
            }
180
            if i == 0 && *comp == OXY_DIR {
181
                return fail(format!("refusing to write inside {OXY_DIR}: {rel:?}"));
182
            }
183
            if i + 1 < comps.len() {
184
                full.push(comp);
185
                if let Ok(m) = fs::symlink_metadata(&full) {
186
                    if m.file_type().is_symlink() {
187
                        return fail(format!(
188
                            "refusing to write through symlink {}",
189
                            full.display()
190
                        ));
191
                    }
192
                }
193
            } else {
194
                full.push(comp);
195
            }
196
        }
197
        Ok(full)
198
    }
199
200
    pub(crate) fn write_file(&self, rel: &str, bytes: &[u8], exec: bool) -> Result<()> {
201
        let full = self.safe_path(rel)?;
202
        if let Some(parent) = full.parent() {
203
            fs::create_dir_all(parent)?;
204
        }
205
        if fs::symlink_metadata(&full).is_ok_and(|m| m.file_type().is_symlink() || m.is_dir()) {
206
            remove_any(&full)?;
207
        }
208
        if fs::metadata(&full).is_ok_and(|m| m.permissions().readonly()) {
209
            set_readonly(&full, false)?;
210
        }
211
        fs::write(&full, bytes)?;
212
        set_executable(&full, exec)?;
213
        Ok(())
214
    }
215
216
    pub(crate) fn write_symlink(&self, rel: &str, target: &[u8]) -> Result<()> {
217
        let full = self.safe_path(rel)?;
218
        if let Some(parent) = full.parent() {
219
            fs::create_dir_all(parent)?;
220
        }
221
        if fs::symlink_metadata(&full).is_ok() {
222
            remove_any(&full)?;
223
        }
224
        #[cfg(unix)]
225
        {
226
            std::os::unix::fs::symlink(String::from_utf8_lossy(target).as_ref(), &full)?;
227
            Ok(())
228
        }
229
        #[cfg(not(unix))]
230
        {
231
            // Spec §7.7: without symlink support, write the target as a plain file.
232
            fs::write(&full, target)?;
233
            Ok(())
234
        }
235
    }
236
}