Skip to main content

gkit_core/
submodules.rs

1//! Submodule traversal + parallel evaluation with deterministic output order.
2//!
3//! Mirrors the zsh recursion (`gitCoreLib.sh` `isEverythingCheckedIn` →
4//! `git submodule foreach`): each repo's submodules are checked before the repo
5//! itself, so the emit order is **post-order DFS** (children first, superproject
6//! last), siblings in submodule-config order. Checks run in parallel for speed,
7//! but results are buffered into fixed slots so output never depends on which
8//! thread finishes first.
9
10use crate::checks::{self, RepoStatus};
11use crate::git::Git;
12use std::path::{Path, PathBuf};
13
14/// One evaluated repo (or submodule).
15pub struct Entry {
16    pub path: PathBuf,
17    pub status: RepoStatus,
18}
19
20/// Direct submodule paths (absolute) of `dir`, in `git submodule status` order.
21/// Uninitialized submodules (status `-`) are skipped — nothing to check.
22fn direct_submodules(git: &dyn Git, dir: &Path) -> Vec<PathBuf> {
23    git.run(dir, &["submodule", "status"])
24        .stdout
25        .lines()
26        .filter_map(|line| {
27            let status = line.chars().next()?;
28            if status == '-' {
29                return None; // uninitialized
30            }
31            // Drop the 1-char status column; remainder is "<sha> <path> (<describe>)".
32            let path = line[1..].split_whitespace().nth(1)?;
33            Some(dir.join(path))
34        })
35        .collect()
36}
37
38/// All repos to check rooted at `root`, in post-order (submodules before parent,
39/// `root` last).
40/// Public: repos rooted at `root` in post-order DFS (submodules before parent,
41/// `root` last). Reused by `stmb` to walk the same tree.
42pub fn repo_paths(git: &dyn Git, root: &Path) -> Vec<PathBuf> {
43    collect_repos(git, root)
44}
45
46/// Is `dir` inside a git work tree? (`git rev-parse --is-inside-work-tree`
47/// prints `true` and exits 0). False for a missing dir or a plain directory.
48fn is_work_tree(git: &dyn Git, dir: &Path) -> bool {
49    let r = git.run(dir, &["rev-parse", "--is-inside-work-tree"]);
50    r.success && r.trimmed() == "true"
51}
52
53fn collect_repos(git: &dyn Git, root: &Path) -> Vec<PathBuf> {
54    fn visit(git: &dyn Git, dir: &Path, order: &mut Vec<PathBuf>) {
55        for sub in direct_submodules(git, dir) {
56            visit(git, &sub, order);
57        }
58        order.push(dir.to_path_buf());
59    }
60    let mut order = Vec::new();
61    visit(git, root, &mut order);
62    order
63}
64
65/// Evaluate `root` and all (recursive) submodules. Checks run in parallel; the
66/// returned Vec is in the fixed post-order DFS order.
67///
68/// `base_override` (the CLI `--base-branch`) applies only to the root; each
69/// submodule resolves its own base (`gkit.baseBranch`, then remote
70/// `origin/main`/`origin/master`) and its own `gkit.solo` / `gkit.allowDiverged`.
71/// Like the zsh, submodules are fetched before checking (when `fetch`), the root
72/// is not.
73pub fn evaluate_tree<G: Git + Sync>(
74    git: &G,
75    root: &Path,
76    base_override: Option<&str>,
77    fetch: bool,
78) -> Vec<Entry> {
79    // Guard the root: a non-repo (or missing) dir would otherwise pass every check
80    // vacuously. Only the root needs this — submodules come from a real repo's
81    // `git submodule status`, so they're already work trees.
82    if !is_work_tree(git, root) {
83        let reason = if root.exists() {
84            "not a git repository"
85        } else {
86            "no such directory"
87        };
88        return vec![Entry {
89            path: root.to_path_buf(),
90            status: RepoStatus::unusable(reason),
91        }];
92    }
93    let repos = collect_repos(git, root);
94    let last = repos.len().saturating_sub(1);
95    let mut slots: Vec<Option<RepoStatus>> = (0..repos.len()).map(|_| None).collect();
96
97    std::thread::scope(|scope| {
98        let mut handles = Vec::with_capacity(repos.len());
99        for (i, path) in repos.iter().enumerate() {
100            let is_root = i == last;
101            let ovr = if is_root { base_override } else { None };
102            let do_fetch = fetch && !is_root; // zsh fetches submodules, not the root
103            let path = path.clone();
104            let handle = scope.spawn(move || {
105                if do_fetch {
106                    let _ = git.run(&path, &["fetch", "--quiet"]);
107                    let _ = git.run(&path, &["remote", "prune", "origin"]);
108                }
109                let base = crate::config::resolve_base(git, &path, ovr);
110                let solo = crate::config::resolve_solo(git, &path);
111                let allow_diverged = crate::config::resolve_allow_diverged(git, &path);
112                checks::evaluate(git, &path, &base, solo, allow_diverged)
113            });
114            handles.push((i, handle));
115        }
116        for (i, handle) in handles {
117            slots[i] = Some(handle.join().expect("gkit: a check thread panicked"));
118        }
119    });
120
121    repos
122        .into_iter()
123        .zip(slots)
124        .map(|(path, status)| Entry {
125            path,
126            status: status.expect("every slot filled"),
127        })
128        .collect()
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use crate::git::test_support::FakeGit;
135
136    #[test]
137    fn collect_repos_is_post_order_dfs() {
138        // /r has submodules a, b ; b has submodule c. Expect children before parents.
139        let git = FakeGit::new()
140            .ok_in("/r", "submodule status", " sha a (x)\n sha b (x)")
141            .ok_in("/r/a", "submodule status", "")
142            .ok_in("/r/b", "submodule status", " sha c (x)")
143            .ok_in("/r/b/c", "submodule status", "");
144        let order = collect_repos(&git, Path::new("/r"));
145        // Normalize separators: `Path::join` yields `\` on Windows, `/` elsewhere.
146        let got: Vec<String> = order
147            .iter()
148            .map(|p| p.display().to_string().replace('\\', "/"))
149            .collect();
150        assert_eq!(got, vec!["/r/a", "/r/b/c", "/r/b", "/r"]);
151    }
152
153    #[test]
154    fn non_repo_root_is_flagged_not_passed() {
155        // A root that isn't a work tree (rev-parse fails) must yield ONE entry that
156        // fails the gate — not a vacuous pass.
157        let git = FakeGit::new().fail("rev-parse --is-inside-work-tree");
158        let entries = evaluate_tree(&git, Path::new("/not/a/repo"), None, false);
159        assert_eq!(entries.len(), 1);
160        assert!(!entries[0].status.ok());
161        assert!(entries[0].status.problem.is_some());
162    }
163
164    #[test]
165    fn skips_uninitialized_submodules() {
166        let git = FakeGit::new().ok_in("/r", "submodule status", "-sha a (x)\n sha b (x)\n");
167        let subs = direct_submodules(&git, Path::new("/r"));
168        let got: Vec<String> = subs
169            .iter()
170            .map(|p| p.display().to_string().replace('\\', "/"))
171            .collect();
172        assert_eq!(got, vec!["/r/b"]); // 'a' (uninitialized, '-') skipped
173    }
174}