OXYGENHUB
◆ v0.9.0 oxygen / crates / oxy-core / src / repo / subrepos.rs
16.2 KiB · Rust · last changed A subrepo at its pinned state is unmodified on any bookmark (closes #147) 9 days ago source blame history raw
1
//! Subrepositories in the working copy (spec §7.8): reading pins from
2
//! nested repositories, moving them to pins, and the `oxy submodule`
3
//! commands.
4
5
use super::*;
6
use crate::subrepo::{Module, Modules, Pin};
7
use std::process::Command;
8
9
/// What syncing a nested repository to its pin did.
10
#[derive(Clone, Debug, PartialEq, Eq)]
11
pub enum SubrepoSync {
12
    Updated,
13
    UpToDate,
14
    Missing,
15
    Dirty,
16
    /// The working copy was brought to the pin, but the nested repository's
17
    /// bookmark has changes the pin lacks, so it was left where it is: a
18
    /// bookmark is never moved backwards (spec §7.8).
19
    KeptBookmark {
20
        bookmark: String,
21
        newer: usize,
22
    },
23
    Failed(String),
24
}
25
26
impl SubrepoSync {
27
    /// A note for a checkout report, when there is something to say.
28
    pub fn note(&self, path: &str) -> Option<String> {
29
        match self {
30
            SubrepoSync::Updated | SubrepoSync::UpToDate => None,
31
            SubrepoSync::Missing => Some(format!(
32
                "{path}: nested repository not present; run oxy submodule update --init"
33
            )),
34
            SubrepoSync::Dirty => Some(format!(
35
                "{path}: nested repository has uncommitted changes; left as is"
36
            )),
37
            SubrepoSync::KeptBookmark { bookmark, newer } => Some(format!(
38
                "{path}: checked out at the pin; its bookmark {bookmark} keeps {newer} newer change{} (oxy bookmark switch {bookmark} there to return to them)",
39
                if *newer == 1 { "" } else { "s" }
40
            )),
41
            SubrepoSync::Failed(e) => Some(format!("{path}: {e}")),
42
        }
43
    }
44
}
45
46
/// One subrepo as `oxy submodule status` shows it.
47
#[derive(Clone, Debug)]
48
pub struct SubrepoInfo {
49
    pub path: String,
50
    pub pin: Pin,
51
    pub url: Option<String>,
52
    /// The nested repository's own pin now, if present.
53
    pub actual: Option<Pin>,
54
    pub dirty: bool,
55
    /// Whether the working copy's base records it. An added subrepo
56
    /// (registered in `.oxymodules`, not committed yet) has `pin` set to
57
    /// what the next commit records.
58
    pub committed: bool,
59
}
60
61
fn git_out(dir: &Path, args: &[&str]) -> Result<String> {
62
    let out = Command::new("git")
63
        .arg("-C")
64
        .arg(dir)
65
        .args(args)
66
        .output()
67
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
68
    if !out.status.success() {
69
        return fail(format!(
70
            "git {} in {}: {}",
71
            args.join(" "),
72
            dir.display(),
73
            String::from_utf8_lossy(&out.stderr).trim()
74
        ));
75
    }
76
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
77
}
78
79
/// The pin a nested repository at `dir` is at: the base of its working
80
/// copy for an Oxygen repository (which is its bookmark's heads unless a
81
/// parent checked out an older pin), `HEAD` for a Git one.
82
pub(crate) fn read_pin(dir: &Path, bookmark_hint: Option<&str>) -> Result<Pin> {
83
    if dir.join(OXY_DIR).exists() {
84
        let nested = Repo::open(dir)?;
85
        return Ok(Pin::Oxy {
86
            repo: nested.id()?,
87
            heads: nested.working_copy()?.1.deps,
88
            bookmark: nested.config.bookmark.clone(),
89
        });
90
    }
91
    if dir.join(".git").exists() {
92
        let sha = git_out(dir, &["rev-parse", "HEAD"])?;
93
        return Ok(Pin::Git {
94
            sha,
95
            branch: bookmark_hint.unwrap_or("HEAD").to_string(),
96
        });
97
    }
98
    fail(format!("{} is not a repository", dir.display()))
99
}
100
101
/// Whether a nested repository has uncommitted work.
102
fn nested_dirty(dir: &Path) -> Result<bool> {
103
    if dir.join(OXY_DIR).exists() {
104
        let nested = Repo::open(dir)?;
105
        let snap = nested.snapshot("oxy submodule")?;
106
        return Ok(!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty());
107
    }
108
    Ok(!git_out(dir, &["status", "--porcelain"])?.is_empty())
109
}
110
111
/// Whether `url` is an Oxygen repository (else it is taken to be Git),
112
/// probed with `options`, the credentials a clone of it would use; with
113
/// the probe's error when it is not, to report if Git cannot clone it
114
/// either.
115
fn probe_oxy_url(url: &str, options: &RemoteOptions) -> std::result::Result<(), String> {
116
    if url.starts_with("http://") || url.starts_with("https://") {
117
        return crate::protocol::open_remote(url, options)
118
            .and_then(|r| r.repo_id())
119
            .map(|_| ())
120
            .map_err(|e| e.to_string());
121
    }
122
    let p = Path::new(url.strip_prefix("file://").unwrap_or(url));
123
    if p.join(OXY_DIR).exists() {
124
        Ok(())
125
    } else {
126
        Err(format!("{} has no {OXY_DIR} directory", p.display()))
127
    }
128
}
129
130
impl Repo {
131
    pub(crate) fn modules_on_disk(&self) -> Modules {
132
        fs::read_to_string(self.root.join(".oxymodules"))
133
            .map(|t| Modules::parse(&t))
134
            .unwrap_or_default()
135
    }
136
137
    fn write_modules(&self, m: &Modules) -> Result<()> {
138
        if m.entries.is_empty() {
139
            let _ = fs::remove_file(self.root.join(".oxymodules"));
140
            return Ok(());
141
        }
142
        write_atomic(&self.root.join(".oxymodules"), m.to_text().as_bytes())
143
    }
144
145
    /// Bring the nested repository at `path` to `pin`, cloning it first when
146
    /// `init` and it is absent.
147
    pub(crate) fn sync_subrepo(&self, path: &str, pin: &Pin, init: bool) -> Result<SubrepoSync> {
148
        let dir = self.root.join(path);
149
        let module = self.modules_on_disk().entries.get(path).cloned();
150
        let present = dir.join(OXY_DIR).exists() || dir.join(".git").exists();
151
        let cloned = !present;
152
        if !present {
153
            if !init {
154
                return Ok(SubrepoSync::Missing);
155
            }
156
            let Some(m) = &module else {
157
                return Ok(SubrepoSync::Failed(
158
                    "no .oxymodules entry to clone from".into(),
159
                ));
160
            };
161
            if let Some(parent) = dir.parent() {
162
                fs::create_dir_all(parent)?;
163
            }
164
            let _ = fs::remove_dir(&dir);
165
            let r = match pin {
166
                Pin::Oxy { .. } => self.clone_as_subrepo(&m.url, &dir).map(|_| ()),
167
                Pin::Git { .. } => Command::new("git")
168
                    .args(["clone", "-q", &m.url])
169
                    .arg(&dir)
170
                    .status()
171
                    .map_err(|e| RepoError::Msg(e.to_string()))
172
                    .and_then(|s| {
173
                        if s.success() {
174
                            Ok(())
175
                        } else {
176
                            fail(format!("git clone {} failed", m.url))
177
                        }
178
                    }),
179
            };
180
            if let Err(e) = r {
181
                return Ok(SubrepoSync::Failed(format!("cloning {}: {e}", m.url)));
182
            }
183
        }
184
        let actual = read_pin(&dir, module.as_ref().and_then(|m| m.bookmark.as_deref()))?;
185
        let same = pin.same_state(&actual);
186
        if same {
187
            return Ok(if cloned {
188
                SubrepoSync::Updated
189
            } else {
190
                SubrepoSync::UpToDate
191
            });
192
        }
193
        if nested_dirty(&dir)? {
194
            return Ok(SubrepoSync::Dirty);
195
        }
196
        match pin {
197
            Pin::Oxy { heads, .. } => {
198
                let nested = Repo::open(&dir)?;
199
                if nested.load_state(heads).is_err() {
200
                    // The pinned changes are not here yet: fetch from origin.
201
                    if let Err(e) = nested.fetch("origin") {
202
                        return Ok(SubrepoSync::Failed(format!(
203
                            "fetching the pinned changes: {e}"
204
                        )));
205
                    }
206
                }
207
                match nested.checkout(heads, false, "oxy submodule update") {
208
                    Ok(_) => {
209
                        // Its bookmark follows only forward: work it has
210
                        // beyond the pin stays on it (metalgear, oxygen#38).
211
                        let bookmark = nested.config.bookmark.clone();
212
                        let at = nested.bookmark_heads().unwrap_or_default();
213
                        let newer = nested.state_gap(&at, heads).map(|g| g.lacks).unwrap_or(0);
214
                        if newer == 0 {
215
                            let _ = nested.bookmark_set(&bookmark, heads);
216
                            Ok(SubrepoSync::Updated)
217
                        } else {
218
                            Ok(SubrepoSync::KeptBookmark { bookmark, newer })
219
                        }
220
                    }
221
                    Err(e) => Ok(SubrepoSync::Failed(e.to_string())),
222
                }
223
            }
224
            Pin::Git { sha, .. } => {
225
                if git_out(&dir, &["cat-file", "-e", &format!("{sha}^{{commit}}")]).is_err() {
226
                    if let Err(e) = git_out(&dir, &["fetch", "-q", "origin"]) {
227
                        return Ok(SubrepoSync::Failed(e.to_string()));
228
                    }
229
                }
230
                match git_out(&dir, &["checkout", "-q", "--detach", sha]) {
231
                    Ok(_) => Ok(SubrepoSync::Updated),
232
                    Err(e) => Ok(SubrepoSync::Failed(e.to_string())),
233
                }
234
            }
235
        }
236
    }
237
238
    /// Every subrepo of the working copy's base state.
239
    pub fn subrepos(&self) -> Result<Vec<SubrepoInfo>> {
240
        let (_, wc) = self.working_copy()?;
241
        // The tree and the subrepos' pins only: a materialized state
242
        // rendered every file of the tree to find them, after each clone,
243
        // pull, switch and `workspace add` (in the VS Code history, ~70 s
244
        // and 11 GB; oxygen#137).
245
        let mut state = self.load_state_indexed(&wc.deps)?;
246
        let tree = self.tree_view(&mut state)?;
247
        let modules = self.modules_on_disk();
248
        let mut out = Vec::new();
249
        for (path, e) in tree.entries.iter() {
250
            if e.kind != NodeKind::Subrepo {
251
                continue;
252
            }
253
            let Some(b) = state.live_blobs(&e.node).first().copied() else {
254
                continue;
255
            };
256
            let pin = Pin::decode(&self.read_blob(&b)?)?;
257
            let dir = self.root.join(path);
258
            let present = dir.join(OXY_DIR).exists() || dir.join(".git").exists();
259
            let actual = if present {
260
                read_pin(
261
                    &dir,
262
                    modules
263
                        .entries
264
                        .get(path)
265
                        .and_then(|m| m.bookmark.as_deref()),
266
                )
267
                .ok()
268
            } else {
269
                None
270
            };
271
            let dirty = present && nested_dirty(&dir).unwrap_or(false);
272
            out.push(SubrepoInfo {
273
                path: path.clone(),
274
                pin,
275
                url: modules.entries.get(path).map(|m| m.url.clone()),
276
                actual,
277
                dirty,
278
                committed: true,
279
            });
280
        }
281
        // Registered but not committed yet: pinned at what they are now.
282
        for (path, m) in &modules.entries {
283
            if tree.entries.contains_key(path) {
284
                continue;
285
            }
286
            let dir = self.root.join(path);
287
            let Ok(pin) = read_pin(&dir, m.bookmark.as_deref()) else {
288
                continue;
289
            };
290
            out.push(SubrepoInfo {
291
                path: path.clone(),
292
                pin: pin.clone(),
293
                url: Some(m.url.clone()),
294
                actual: Some(pin),
295
                dirty: nested_dirty(&dir).unwrap_or(false),
296
                committed: false,
297
            });
298
        }
299
        out.sort_by(|a, b| a.path.cmp(&b.path));
300
        Ok(out)
301
    }
302
303
    /// `.oxymodules` entries with no subrepo behind them: never added, so
304
    /// there is no pin to clone or check out (oxygen#72).
305
    pub fn unpinned_modules(&self) -> Result<Vec<(String, Module)>> {
306
        let pinned: Vec<String> = self.subrepos()?.into_iter().map(|s| s.path).collect();
307
        Ok(self
308
            .modules_on_disk()
309
            .entries
310
            .into_iter()
311
            .filter(|(path, _)| !pinned.contains(path))
312
            .collect())
313
    }
314
315
    /// Clone `url` at `path`, register it in `.oxymodules`, and return the
316
    /// pin the next snapshot will record.
317
    pub fn submodule_add(&self, url: &str, path: &str, bookmark: Option<&str>) -> Result<Pin> {
318
        let path = path.trim_end_matches('/').to_string();
319
        if path.is_empty()
320
            || path.starts_with('/')
321
            || path.split('/').any(|c| c == ".." || c == ".")
322
        {
323
            return fail(format!("{path:?} is not a valid subrepo path"));
324
        }
325
        let dir = self.root.join(&path);
326
        if dir.exists() && fs::read_dir(&dir)?.next().is_some() {
327
            return fail(format!("{path} exists and is not empty"));
328
        }
329
        if let Some(parent) = dir.parent() {
330
            fs::create_dir_all(parent)?;
331
        }
332
        let probe = probe_oxy_url(url, &self.credentials_for(url));
333
        let git = probe.is_err();
334
        if git {
335
            let mut cmd = Command::new("git");
336
            cmd.args(["clone", "-q"]);
337
            if let Some(b) = bookmark {
338
                cmd.args(["--branch", b]);
339
            }
340
            let status = cmd
341
                .arg(url)
342
                .arg(&dir)
343
                .status()
344
                .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
345
            if !status.success() {
346
                let oxy_error = probe.err().unwrap_or_default();
347
                return fail(format!(
348
                    "git clone {url} failed; as an Oxygen repository: {oxy_error}"
349
                ));
350
            }
351
        } else {
352
            let _ = fs::remove_dir(&dir);
353
            let mut nested = self.clone_as_subrepo(url, &dir)?;
354
            if let Some(b) = bookmark {
355
                nested.bookmark_switch(b, true)?;
356
            }
357
        }
358
        let mut modules = self.modules_on_disk();
359
        modules.entries.insert(
360
            path.clone(),
361
            Module {
362
                url: url.to_string(),
363
                bookmark: bookmark.map(str::to_string),
364
                git,
365
            },
366
        );
367
        self.write_modules(&modules)?;
368
        read_pin(&dir, bookmark)
369
    }
370
371
    /// Bring nested repositories to their pins (`paths` empty = all).
372
    pub fn submodule_update(
373
        &self,
374
        init: bool,
375
        paths: &[String],
376
    ) -> Result<Vec<(String, SubrepoSync)>> {
377
        let mut out = Vec::new();
378
        for s in self.subrepos()? {
379
            if !paths.is_empty() && !paths.iter().any(|p| p.trim_end_matches('/') == s.path) {
380
                continue;
381
            }
382
            let r = self.sync_subrepo(&s.path, &s.pin, init)?;
383
            out.push((s.path, r));
384
        }
385
        Ok(out)
386
    }
387
388
    /// Drop the `.oxymodules` entry; the node goes with the next snapshot
389
    /// only if the directory is removed, since a registered or tracked
390
    /// nested repository keeps contributing its pin. Here the directory is
391
    /// left in place and the node is removed explicitly from the working
392
    /// copy's next change by unregistering and moving the directory aside.
393
    pub fn submodule_remove(&self, path: &str) -> Result<()> {
394
        let path = path.trim_end_matches('/').to_string();
395
        let mut modules = self.modules_on_disk();
396
        let known = modules.entries.remove(&path).is_some()
397
            || self.subrepos()?.iter().any(|s| s.path == path);
398
        if !known {
399
            return fail(format!("{path} is not a subrepo"));
400
        }
401
        self.write_modules(&modules)?;
402
        // The directory stays; the walker ignores an unregistered nested
403
        // repository unless tracked, so mark it as removed for the next
404
        // snapshot by recording an explicit removal.
405
        let dir = self.oxy.join("subrepos-removed");
406
        fs::create_dir_all(&dir)?;
407
        write_atomic(&dir.join(path.replace('/', "%2F")), b"")?;
408
        Ok(())
409
    }
410
411
    /// Paths whose subrepo node was removed with `oxy submodule remove` and
412
    /// whose directory is still on disk.
413
    pub(crate) fn removed_subrepos(&self) -> BTreeSet<String> {
414
        let mut out = BTreeSet::new();
415
        if let Ok(rd) = fs::read_dir(self.oxy.join("subrepos-removed")) {
416
            for e in rd.flatten() {
417
                out.insert(e.file_name().to_string_lossy().replace("%2F", "/"));
418
            }
419
        }
420
        out
421
    }
422
423
    pub(crate) fn clear_removed_subrepo(&self, path: &str) {
424
        let _ = fs::remove_file(
425
            self.oxy
426
                .join("subrepos-removed")
427
                .join(path.replace('/', "%2F")),
428
        );
429
    }
430
}