Skip to main content

gkit_core/
config.rs

1//! Resolve a repo's base/integration branch — the single branch gkit treats as
2//! "the trunk" for the correct-branch check. Replaces the zsh's hardcoded
3//! `dev|main|master`. Resolution order:
4//!   1. explicit CLI `--base-branch`
5//!   2. per-repo `git config gkit.baseBranch`
6//!   3. a remote-tracking branch — `origin/main`, else `origin/master`
7//!   4. otherwise **unresolved**: a base couldn't be determined (e.g. a
8//!      single-branch clone of a feature branch). The correct-branch check then
9//!      fails rather than silently passing against the wrong base.
10
11use crate::git::Git;
12use std::collections::HashSet;
13use std::path::Path;
14
15/// Where a resolved base branch came from — surfaced by `logoff --verbose`.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum BaseSource {
18    /// Explicit CLI `--base-branch`.
19    Flag,
20    /// `git config gkit.baseBranch`.
21    Config,
22    /// Derived from a remote-tracking branch (`origin/main`, else `origin/master`).
23    Remote,
24    /// Could not be determined from any source.
25    Unresolved,
26}
27
28/// A base branch plus where it was resolved from. `name` is `None` only when
29/// `source` is [`BaseSource::Unresolved`].
30#[derive(Debug, Clone)]
31pub struct ResolvedBase {
32    pub name: Option<String>,
33    pub source: BaseSource,
34}
35
36impl ResolvedBase {
37    fn flag(name: &str) -> Self {
38        Self {
39            name: Some(name.to_string()),
40            source: BaseSource::Flag,
41        }
42    }
43    fn config(name: &str) -> Self {
44        Self {
45            name: Some(name.to_string()),
46            source: BaseSource::Config,
47        }
48    }
49    fn remote(name: &str) -> Self {
50        Self {
51            name: Some(name.to_string()),
52            source: BaseSource::Remote,
53        }
54    }
55    /// The unresolved sentinel: no base, fails the correct-branch check.
56    pub fn unresolved() -> Self {
57        Self {
58            name: None,
59            source: BaseSource::Unresolved,
60        }
61    }
62
63    /// Human-readable "branch (how it was derived)" for `logoff --verbose`.
64    pub fn describe(&self) -> String {
65        match (&self.name, self.source) {
66            (Some(b), BaseSource::Flag) => format!("{b} (from --base-branch)"),
67            (Some(b), BaseSource::Config) => format!("{b} (from git config gkit.baseBranch)"),
68            (Some(b), BaseSource::Remote) => format!("{b} (derived from remote origin/{b})"),
69            _ => "UNRESOLVED — gkit.baseBranch unset and no origin/main or origin/master \
70                  (correct-branch can't be checked)"
71                .to_string(),
72        }
73    }
74}
75
76/// Resolve the base branch for the `logoff` correct-branch check (see module docs).
77pub fn resolve_base(git: &dyn Git, dir: &Path, cli_override: Option<&str>) -> ResolvedBase {
78    if let Some(b) = cli_override {
79        let b = b.trim();
80        if !b.is_empty() {
81            return ResolvedBase::flag(b);
82        }
83    }
84    let cfg = git.run(dir, &["config", "--get", "gkit.baseBranch"]);
85    if cfg.success && !cfg.trimmed().is_empty() {
86        return ResolvedBase::config(cfg.trimmed());
87    }
88    // Derive from remote-tracking branches: main first, then master. A single-branch
89    // clone of a feature branch has neither -> unresolved (correct-branch fails).
90    let remotes: HashSet<String> = git
91        .run(
92            dir,
93            &[
94                "for-each-ref",
95                "--format=%(refname:short)",
96                "refs/remotes/origin/*",
97            ],
98        )
99        .stdout
100        .lines()
101        .filter_map(|l| l.trim().strip_prefix("origin/").map(str::to_string))
102        .collect();
103    for cand in ["main", "master"] {
104        if remotes.contains(cand) {
105            return ResolvedBase::remote(cand);
106        }
107    }
108    ResolvedBase::unresolved()
109}
110
111/// Read `gkit.solo` (a bool) for a repo. Default `false` (team workflow) when
112/// unset or unparsable. When `true`, the correct-branch check additionally flags
113/// sitting on an integration branch while feature branches exist on the remote —
114/// meaningful for a solo developer where every remote branch is their own.
115/// Honors git's config layering: `--global` for a personal default, repo config
116/// to override. Stamped by `gkit clone` from the conf's `solo` field.
117pub fn resolve_solo(git: &dyn Git, dir: &Path) -> bool {
118    let o = git.run(dir, &["config", "--get", "--bool", "gkit.solo"]);
119    o.success && o.trimmed() == "true"
120}
121
122/// Current branch, or `None` if HEAD is detached (no symbolic ref).
123pub fn current_branch_opt(git: &dyn Git, dir: &Path) -> Option<String> {
124    let o = git.run(dir, &["symbolic-ref", "--short", "HEAD"]);
125    if o.success {
126        Some(o.trimmed().to_string())
127    } else {
128        None
129    }
130}
131
132/// Resolve the base branch to *switch to* (for stmb). Unlike [`resolve_base`]
133/// this never falls back to HEAD (HEAD is the feature branch here): CLI override →
134/// `gkit.baseBranch` → `origin/HEAD` default branch. `None` if undeterminable.
135pub fn resolve_switch_base(
136    git: &dyn Git,
137    dir: &Path,
138    cli_override: Option<&str>,
139) -> Option<String> {
140    if let Some(b) = cli_override {
141        if !b.trim().is_empty() {
142            return Some(b.trim().to_string());
143        }
144    }
145    let cfg = git.run(dir, &["config", "--get", "gkit.baseBranch"]);
146    if cfg.success && !cfg.trimmed().is_empty() {
147        return Some(cfg.trimmed().to_string());
148    }
149    let head = git.run(
150        dir,
151        &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
152    );
153    if head.success {
154        return head.trimmed().strip_prefix("origin/").map(str::to_string);
155    }
156    None
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162    use crate::git::test_support::FakeGit;
163    use std::path::Path;
164
165    fn d() -> &'static Path {
166        Path::new("/x")
167    }
168
169    /// `for-each-ref refs/remotes/origin/*` stub listing the given remote branches.
170    fn with_remotes(g: FakeGit, branches: &[&str]) -> FakeGit {
171        let listing = branches
172            .iter()
173            .map(|b| format!("origin/{b}"))
174            .collect::<Vec<_>>()
175            .join("\n");
176        g.ok(
177            "for-each-ref --format=%(refname:short) refs/remotes/origin/*",
178            &listing,
179        )
180    }
181
182    #[test]
183    fn cli_override_wins() {
184        let g = FakeGit::new().ok("config --get gkit.baseBranch", "dev");
185        let r = resolve_base(&g, d(), Some("main"));
186        assert_eq!(r.name.as_deref(), Some("main"));
187        assert_eq!(r.source, BaseSource::Flag);
188    }
189
190    #[test]
191    fn falls_back_to_git_config() {
192        let g = FakeGit::new().ok("config --get gkit.baseBranch", "dev");
193        let r = resolve_base(&g, d(), None);
194        assert_eq!(r.name.as_deref(), Some("dev"));
195        assert_eq!(r.source, BaseSource::Config);
196    }
197
198    #[test]
199    fn derives_main_from_remote_when_config_unset() {
200        let g = with_remotes(
201            FakeGit::new().fail("config --get gkit.baseBranch"),
202            &["feature-x", "main", "master"],
203        );
204        let r = resolve_base(&g, d(), None);
205        // main wins over master.
206        assert_eq!(r.name.as_deref(), Some("main"));
207        assert_eq!(r.source, BaseSource::Remote);
208    }
209
210    #[test]
211    fn derives_master_when_no_main() {
212        let g = with_remotes(
213            FakeGit::new().fail("config --get gkit.baseBranch"),
214            &["master", "feature-y"],
215        );
216        let r = resolve_base(&g, d(), None);
217        assert_eq!(r.name.as_deref(), Some("master"));
218        assert_eq!(r.source, BaseSource::Remote);
219    }
220
221    #[test]
222    fn unresolved_when_no_config_and_no_main_master() {
223        // e.g. a single-branch clone of a feature branch.
224        let g = with_remotes(
225            FakeGit::new().fail("config --get gkit.baseBranch"),
226            &["feature-only"],
227        );
228        let r = resolve_base(&g, d(), None);
229        assert_eq!(r.name, None);
230        assert_eq!(r.source, BaseSource::Unresolved);
231    }
232
233    #[test]
234    fn resolve_solo_defaults_false_and_reads_bool() {
235        // unset / failing config -> false
236        assert!(!resolve_solo(
237            &FakeGit::new().fail("config --get --bool gkit.solo"),
238            d()
239        ));
240        // explicit true / false
241        assert!(resolve_solo(
242            &FakeGit::new().ok("config --get --bool gkit.solo", "true"),
243            d()
244        ));
245        assert!(!resolve_solo(
246            &FakeGit::new().ok("config --get --bool gkit.solo", "false"),
247            d()
248        ));
249    }
250
251    #[test]
252    fn current_branch_opt_detects_detached() {
253        let on = FakeGit::new().ok("symbolic-ref --short HEAD", "feat");
254        assert_eq!(current_branch_opt(&on, d()), Some("feat".into()));
255        let detached = FakeGit::new().fail("symbolic-ref --short HEAD");
256        assert_eq!(current_branch_opt(&detached, d()), None);
257    }
258
259    #[test]
260    fn switch_base_uses_origin_head_not_current() {
261        // config unset -> use origin/HEAD default, NOT the (feature) HEAD
262        let g = FakeGit::new().fail("config --get gkit.baseBranch").ok(
263            "symbolic-ref --short refs/remotes/origin/HEAD",
264            "origin/dev",
265        );
266        assert_eq!(resolve_switch_base(&g, d(), None), Some("dev".into()));
267        // override still wins
268        assert_eq!(
269            resolve_switch_base(&g, d(), Some("main")),
270            Some("main".into())
271        );
272    }
273}