OXYGENHUB

Coverage / crates/oxy-core/src/repo/subrepos.rs 79.8%

249 of 312 lines run, 26 of 60 functions · run #398 on subrepo-pin-state · run missed

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.
2813×
    pub fn note(&self, path: &str) -> Option<String> {
2913×
        match self {
306×
            SubrepoSync::Updated | SubrepoSync::UpToDate => None,
313×
            SubrepoSync::Missing => Some(format!(
323×
                "{path}: nested repository not present; run oxy submodule update --init"
333×
            )),
341×
            SubrepoSync::Dirty => Some(format!(
351×
                "{path}: nested repository has uncommitted changes; left as is"
361×
            )),
373×
            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)",
393×
                if *newer == 1 { "" } else { "s" }
40
            )),
410×
            SubrepoSync::Failed(e) => Some(format!("{path}: {e}")),
42
        }
4313×
    }
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
612×
fn git_out(dir: &Path, args: &[&str]) -> Result<String> {
622×
    let out = Command::new("git")
632×
        .arg("-C")
642×
        .arg(dir)
652×
        .args(args)
662×
        .output()
672×
        .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
682×
    if !out.status.success() {
690×
        return fail(format!(
70
            "git {} in {}: {}",
710×
            args.join(" "),
720×
            dir.display(),
730×
            String::from_utf8_lossy(&out.stderr).trim()
74
        ));
752×
    }
762×
    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
772×
}
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.
8287×
pub(crate) fn read_pin(dir: &Path, bookmark_hint: Option<&str>) -> Result<Pin> {
8387×
    if dir.join(OXY_DIR).exists() {
8483×
        let nested = Repo::open(dir)?;
85
        return Ok(Pin::Oxy {
8683×
            repo: nested.id()?,
8783×
            heads: nested.working_copy()?.1.deps,
8883×
            bookmark: nested.config.bookmark.clone(),
89
        });
904×
    }
914×
    if dir.join(".git").exists() {
922×
        let sha = git_out(dir, &["rev-parse", "HEAD"])?;
932×
        return Ok(Pin::Git {
942×
            sha,
952×
            branch: bookmark_hint.unwrap_or("HEAD").to_string(),
962×
        });
972×
    }
982×
    fail(format!("{} is not a repository", dir.display()))
9987×
}
100
101
/// Whether a nested repository has uncommitted work.
10210×
fn nested_dirty(dir: &Path) -> Result<bool> {
10310×
    if dir.join(OXY_DIR).exists() {
10410×
        let nested = Repo::open(dir)?;
10510×
        let snap = nested.snapshot("oxy submodule")?;
10610×
        return Ok(!snap.wc.tree_ops.is_empty() || !snap.wc.edits.is_empty());
1070×
    }
1080×
    Ok(!git_out(dir, &["status", "--porcelain"])?.is_empty())
10910×
}
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.
11511×
fn probe_oxy_url(url: &str, options: &RemoteOptions) -> std::result::Result<(), String> {
11611×
    if url.starts_with("http://") || url.starts_with("https://") {
1170×
        return crate::protocol::open_remote(url, options)
1180×
            .and_then(|r| r.repo_id())
1190×
            .map(|_| ())
1200×
            .map_err(|e| e.to_string());
12111×
    }
12211×
    let p = Path::new(url.strip_prefix("file://").unwrap_or(url));
12311×
    if p.join(OXY_DIR).exists() {
12411×
        Ok(())
125
    } else {
1260×
        Err(format!("{} has no {OXY_DIR} directory", p.display()))
127
    }
12811×
}
129
130
impl Repo {
1311649×
    pub(crate) fn modules_on_disk(&self) -> Modules {
1321649×
        fs::read_to_string(self.root.join(".oxymodules"))
1331649×
            .map(|t| Modules::parse(&t))
1341649×
            .unwrap_or_default()
1351649×
    }
136
13712×
    fn write_modules(&self, m: &Modules) -> Result<()> {
13812×
        if m.entries.is_empty() {
1391×
            let _ = fs::remove_file(self.root.join(".oxymodules"));
1401×
            return Ok(());
14111×
        }
14211×
        write_atomic(&self.root.join(".oxymodules"), m.to_text().as_bytes())
14312×
    }
144
145
    /// Bring the nested repository at `path` to `pin`, cloning it first when
146
    /// `init` and it is absent.
14718×
    pub(crate) fn sync_subrepo(&self, path: &str, pin: &Pin, init: bool) -> Result<SubrepoSync> {
14818×
        let dir = self.root.join(path);
14918×
        let module = self.modules_on_disk().entries.get(path).cloned();
15018×
        let present = dir.join(OXY_DIR).exists() || dir.join(".git").exists();
15118×
        let cloned = !present;
15218×
        if !present {
1536×
            if !init {
1544×
                return Ok(SubrepoSync::Missing);
1552×
            }
1562×
            let Some(m) = &module else {
1570×
                return Ok(SubrepoSync::Failed(
1580×
                    "no .oxymodules entry to clone from".into(),
1590×
                ));
160
            };
1612×
            if let Some(parent) = dir.parent() {
1622×
                fs::create_dir_all(parent)?;
1630×
            }
1642×
            let _ = fs::remove_dir(&dir);
1652×
            let r = match pin {
1661×
                Pin::Oxy { .. } => self.clone_as_subrepo(&m.url, &dir).map(|_| ()),
1671×
                Pin::Git { .. } => Command::new("git")
1681×
                    .args(["clone", "-q", &m.url])
1691×
                    .arg(&dir)
1701×
                    .status()
1711×
                    .map_err(|e| RepoError::Msg(e.to_string()))
1721×
                    .and_then(|s| {
1731×
                        if s.success() {
1741×
                            Ok(())
175
                        } else {
1760×
                            fail(format!("git clone {} failed", m.url))
177
                        }
1781×
                    }),
179
            };
1802×
            if let Err(e) = r {
1810×
                return Ok(SubrepoSync::Failed(format!("cloning {}: {e}", m.url)));
1822×
            }
18312×
        }
18414×
        let actual = read_pin(&dir, module.as_ref().and_then(|m| m.bookmark.as_deref()))?;
18514×
        let same = pin.same_state(&actual);
18614×
        if same {
1879×
            return Ok(if cloned {
1882×
                SubrepoSync::Updated
189
            } else {
1907×
                SubrepoSync::UpToDate
191
            });
1925×
        }
1935×
        if nested_dirty(&dir)? {
1941×
            return Ok(SubrepoSync::Dirty);
1954×
        }
1964×
        match pin {
1974×
            Pin::Oxy { heads, .. } => {
1984×
                let nested = Repo::open(&dir)?;
1994×
                if nested.load_state(heads).is_err() {
200
                    // The pinned changes are not here yet: fetch from origin.
2010×
                    if let Err(e) = nested.fetch("origin") {
2020×
                        return Ok(SubrepoSync::Failed(format!(
2030×
                            "fetching the pinned changes: {e}"
2040×
                        )));
2050×
                    }
2064×
                }
2074×
                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).
2114×
                        let bookmark = nested.config.bookmark.clone();
2124×
                        let at = nested.bookmark_heads().unwrap_or_default();
2134×
                        let newer = nested.state_gap(&at, heads).map(|g| g.lacks).unwrap_or(0);
2144×
                        if newer == 0 {
2151×
                            let _ = nested.bookmark_set(&bookmark, heads);
2161×
                            Ok(SubrepoSync::Updated)
217
                        } else {
2183×
                            Ok(SubrepoSync::KeptBookmark { bookmark, newer })
219
                        }
220
                    }
2210×
                    Err(e) => Ok(SubrepoSync::Failed(e.to_string())),
222
                }
223
            }
2240×
            Pin::Git { sha, .. } => {
2250×
                if git_out(&dir, &["cat-file", "-e", &format!("{sha}^{{commit}}")]).is_err() {
2260×
                    if let Err(e) = git_out(&dir, &["fetch", "-q", "origin"]) {
2270×
                        return Ok(SubrepoSync::Failed(e.to_string()));
2280×
                    }
2290×
                }
2300×
                match git_out(&dir, &["checkout", "-q", "--detach", sha]) {
2310×
                    Ok(_) => Ok(SubrepoSync::Updated),
2320×
                    Err(e) => Ok(SubrepoSync::Failed(e.to_string())),
233
                }
234
            }
235
        }
23618×
    }
237
238
    /// Every subrepo of the working copy's base state.
23929×
    pub fn subrepos(&self) -> Result<Vec<SubrepoInfo>> {
24029×
        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).
24529×
        let mut state = self.load_state_indexed(&wc.deps)?;
24629×
        let tree = self.tree_view(&mut state)?;
24729×
        let modules = self.modules_on_disk();
24829×
        let mut out = Vec::new();
24949×
        for (path, e) in tree.entries.iter() {
25049×
            if e.kind != NodeKind::Subrepo {
25142×
                continue;
2527×
            }
2537×
            let Some(b) = state.live_blobs(&e.node).first().copied() else {
2540×
                continue;
255
            };
2567×
            let pin = Pin::decode(&self.read_blob(&b)?)?;
2577×
            let dir = self.root.join(path);
2587×
            let present = dir.join(OXY_DIR).exists() || dir.join(".git").exists();
2597×
            let actual = if present {
2603×
                read_pin(
2613×
                    &dir,
2623×
                    modules
2633×
                        .entries
2643×
                        .get(path)
2653×
                        .and_then(|m| m.bookmark.as_deref()),
266
                )
2673×
                .ok()
268
            } else {
2694×
                None
270
            };
2717×
            let dirty = present && nested_dirty(&dir).unwrap_or(false);
2727×
            out.push(SubrepoInfo {
2737×
                path: path.clone(),
2747×
                pin,
2757×
                url: modules.entries.get(path).map(|m| m.url.clone()),
2767×
                actual,
2777×
                dirty,
278
                committed: true,
279
            });
280
        }
281
        // Registered but not committed yet: pinned at what they are now.
28229×
        for (path, m) in &modules.entries {
28311×
            if tree.entries.contains_key(path) {
2847×
                continue;
2854×
            }
2864×
            let dir = self.root.join(path);
2874×
            let Ok(pin) = read_pin(&dir, m.bookmark.as_deref()) else {
2882×
                continue;
289
            };
2902×
            out.push(SubrepoInfo {
2912×
                path: path.clone(),
2922×
                pin: pin.clone(),
2932×
                url: Some(m.url.clone()),
2942×
                actual: Some(pin),
2952×
                dirty: nested_dirty(&dir).unwrap_or(false),
2962×
                committed: false,
2972×
            });
298
        }
29929×
        out.sort_by(|a, b| a.path.cmp(&b.path));
30029×
        Ok(out)
30129×
    }
302
303
    /// `.oxymodules` entries with no subrepo behind them: never added, so
304
    /// there is no pin to clone or check out (oxygen#72).
3053×
    pub fn unpinned_modules(&self) -> Result<Vec<(String, Module)>> {
3063×
        let pinned: Vec<String> = self.subrepos()?.into_iter().map(|s| s.path).collect();
3073×
        Ok(self
3083×
            .modules_on_disk()
3093×
            .entries
3103×
            .into_iter()
3113×
            .filter(|(path, _)| !pinned.contains(path))
3123×
            .collect())
3133×
    }
314
315
    /// Clone `url` at `path`, register it in `.oxymodules`, and return the
316
    /// pin the next snapshot will record.
31711×
    pub fn submodule_add(&self, url: &str, path: &str, bookmark: Option<&str>) -> Result<Pin> {
31811×
        let path = path.trim_end_matches('/').to_string();
31911×
        if path.is_empty()
32011×
            || path.starts_with('/')
32121×
            || path.split('/').any(|c| c == ".." || c == ".")
322
        {
3230×
            return fail(format!("{path:?} is not a valid subrepo path"));
32411×
        }
32511×
        let dir = self.root.join(&path);
32611×
        if dir.exists() && fs::read_dir(&dir)?.next().is_some() {
3270×
            return fail(format!("{path} exists and is not empty"));
32811×
        }
32911×
        if let Some(parent) = dir.parent() {
33011×
            fs::create_dir_all(parent)?;
3310×
        }
33211×
        let probe = probe_oxy_url(url, &self.credentials_for(url));
33311×
        let git = probe.is_err();
33411×
        if git {
3350×
            let mut cmd = Command::new("git");
3360×
            cmd.args(["clone", "-q"]);
3370×
            if let Some(b) = bookmark {
3380×
                cmd.args(["--branch", b]);
3390×
            }
3400×
            let status = cmd
3410×
                .arg(url)
3420×
                .arg(&dir)
3430×
                .status()
3440×
                .map_err(|e| RepoError::Msg(format!("running git: {e}")))?;
3450×
            if !status.success() {
3460×
                let oxy_error = probe.err().unwrap_or_default();
3470×
                return fail(format!(
348
                    "git clone {url} failed; as an Oxygen repository: {oxy_error}"
349
                ));
3500×
            }
351
        } else {
35211×
            let _ = fs::remove_dir(&dir);
35311×
            let mut nested = self.clone_as_subrepo(url, &dir)?;
35411×
            if let Some(b) = bookmark {
3550×
                nested.bookmark_switch(b, true)?;
35611×
            }
357
        }
35811×
        let mut modules = self.modules_on_disk();
35911×
        modules.entries.insert(
36011×
            path.clone(),
36111×
            Module {
36211×
                url: url.to_string(),
36311×
                bookmark: bookmark.map(str::to_string),
36411×
                git,
36511×
            },
366
        );
36711×
        self.write_modules(&modules)?;
36811×
        read_pin(&dir, bookmark)
36911×
    }
370
371
    /// Bring nested repositories to their pins (`paths` empty = all).
3725×
    pub fn submodule_update(
3735×
        &self,
3745×
        init: bool,
3755×
        paths: &[String],
3765×
    ) -> Result<Vec<(String, SubrepoSync)>> {
3775×
        let mut out = Vec::new();
3785×
        for s in self.subrepos()? {
3794×
            if !paths.is_empty() && !paths.iter().any(|p| p.trim_end_matches('/') == s.path) {
3800×
                continue;
3814×
            }
3824×
            let r = self.sync_subrepo(&s.path, &s.pin, init)?;
3834×
            out.push((s.path, r));
384
        }
3855×
        Ok(out)
3865×
    }
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.
3931×
    pub fn submodule_remove(&self, path: &str) -> Result<()> {
3941×
        let path = path.trim_end_matches('/').to_string();
3951×
        let mut modules = self.modules_on_disk();
3961×
        let known = modules.entries.remove(&path).is_some()
3970×
            || self.subrepos()?.iter().any(|s| s.path == path);
3981×
        if !known {
3990×
            return fail(format!("{path} is not a subrepo"));
4001×
        }
4011×
        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.
4051×
        let dir = self.oxy.join("subrepos-removed");
4061×
        fs::create_dir_all(&dir)?;
4071×
        write_atomic(&dir.join(path.replace('/', "%2F")), b"")?;
4081×
        Ok(())
4091×
    }
410
411
    /// Paths whose subrepo node was removed with `oxy submodule remove` and
412
    /// whose directory is still on disk.
4131566×
    pub(crate) fn removed_subrepos(&self) -> BTreeSet<String> {
4141566×
        let mut out = BTreeSet::new();
4151566×
        if let Ok(rd) = fs::read_dir(self.oxy.join("subrepos-removed")) {
4163×
            for e in rd.flatten() {
4173×
                out.insert(e.file_name().to_string_lossy().replace("%2F", "/"));
4183×
            }
4191563×
        }
4201566×
        out
4211566×
    }
422
4231×
    pub(crate) fn clear_removed_subrepo(&self, path: &str) {
4241×
        let _ = fs::remove_file(
4251×
            self.oxy
4261×
                .join("subrepos-removed")
4271×
                .join(path.replace('/', "%2F")),
4281×
        );
4291×
    }
430
}