Skip to main content

git_stk/
settings.rs

1//! Every stk-owned git config key and its resolution logic, in one place.
2
3use std::time::Duration;
4
5use anyhow::{Context, Result, bail};
6
7use crate::cli::{FetchMode, PushMode};
8use crate::git;
9
10pub const PROVIDER_KEY: &str = "stk.provider";
11pub const REMOTE_KEY: &str = "stk.remote";
12pub const UPDATE_REFS_KEY: &str = "stk.updateRefs";
13pub const FETCH_BEFORE_RESTACK_KEY: &str = "stk.fetchBeforeRestack";
14pub const PUSH_ON_RESTACK_KEY: &str = "stk.pushOnRestack";
15pub const PUSH_ON_SUBMIT_KEY: &str = "stk.pushOnSubmit";
16pub const SUBMIT_STACK_KEY: &str = "stk.submitStack";
17pub const MERGE_STRATEGY_KEY: &str = "stk.mergeStrategy";
18pub const MERGE_WAIT_KEY: &str = "stk.mergeWait";
19pub const SUBMIT_DRAFT_KEY: &str = "stk.submitDraft";
20pub const NO_UPDATE_CHECK_KEY: &str = "stk.noUpdateCheck";
21pub const ABSORB_INCLUDE_UNSTAGED_KEY: &str = "stk.absorbIncludeUnstaged";
22pub const GITLAB_HOST_KEY: &str = "stk.gitlabHost";
23pub const GITEA_HOST_KEY: &str = "stk.giteaHost";
24pub const CHECK_TIMEOUT_KEY: &str = "stk.checkTimeout";
25pub const USE_PR_TEMPLATE_KEY: &str = "stk.usePrTemplate";
26pub const WORKTREE_DIR_KEY: &str = "stk.worktreeDir";
27pub const DEFAULT_REMOTE: &str = "origin";
28
29/// How long `merge --wait` polls a review's checks before giving up, unless
30/// `stk.checkTimeout` overrides it. Generous so a slow-but-real CI is not cut
31/// off; the point is to bound a pipeline that never settles, not a long one.
32pub const DEFAULT_CHECK_TIMEOUT_SECS: u64 = 1800;
33
34/// Every `[stk]` setting the tool reads, with its default behavior. Shown by
35/// `git stk config`.
36pub const SETTINGS: &[(&str, &str)] = &[
37    (PROVIDER_KEY, "auto-detect from the remote URL"),
38    (REMOTE_KEY, DEFAULT_REMOTE),
39    (UPDATE_REFS_KEY, "false"),
40    (FETCH_BEFORE_RESTACK_KEY, "false"),
41    (PUSH_ON_RESTACK_KEY, "false"),
42    (PUSH_ON_SUBMIT_KEY, "false"),
43    (SUBMIT_STACK_KEY, "false"),
44    (MERGE_STRATEGY_KEY, "squash"),
45    (MERGE_WAIT_KEY, "false"),
46    (SUBMIT_DRAFT_KEY, "false"),
47    (NO_UPDATE_CHECK_KEY, "false"),
48    (ABSORB_INCLUDE_UNSTAGED_KEY, "false"),
49    (GITLAB_HOST_KEY, "none; gitlab.com is always detected"),
50    (
51        GITEA_HOST_KEY,
52        "none; gitea.com and codeberg.org are always detected",
53    ),
54    (CHECK_TIMEOUT_KEY, "1800 (30m); 0 waits indefinitely"),
55    (USE_PR_TEMPLATE_KEY, "true"),
56    (
57        WORKTREE_DIR_KEY,
58        "a <repo>-worktrees directory beside the repo",
59    ),
60];
61
62/// The remote used for provider detection, trunk discovery, and pushes.
63pub fn remote() -> Result<String> {
64    Ok(git::config_get(REMOTE_KEY)?.unwrap_or_else(|| DEFAULT_REMOTE.to_owned()))
65}
66
67/// A self-hosted GitLab host (e.g. `gitlab.example.com`) to recognize as
68/// GitLab alongside gitlab.com (`stk.gitlabHost`). `glab` reads the host from
69/// the git remote on its own, so this only widens stk's provider detection.
70pub fn gitlab_host() -> Result<Option<String>> {
71    git::config_get(GITLAB_HOST_KEY)
72}
73
74/// A self-hosted Gitea/Forgejo host (e.g. `gitea.example.com`) to recognize as
75/// Gitea alongside gitea.com and codeberg.org (`stk.giteaHost`). `tea` reads
76/// the host from the git remote itself, so this only widens stk's detection.
77pub fn gitea_host() -> Result<Option<String>> {
78    git::config_get(GITEA_HOST_KEY)
79}
80
81/// The merge strategy for `git stk merge`: squash, rebase, or merge.
82pub fn merge_strategy() -> Result<String> {
83    let strategy = git::config_get(MERGE_STRATEGY_KEY)?.unwrap_or_else(|| "squash".to_owned());
84    match strategy.as_str() {
85        "squash" | "rebase" | "merge" => Ok(strategy),
86        other => anyhow::bail!(
87            "unsupported stk.mergeStrategy value {other:?}; expected squash, rebase, or merge"
88        ),
89    }
90}
91
92/// How long `merge --wait` keeps polling a review's checks before giving up,
93/// from `stk.checkTimeout` (whole seconds). `0` waits indefinitely; unset uses
94/// [`DEFAULT_CHECK_TIMEOUT_SECS`].
95pub fn check_timeout() -> Result<Option<Duration>> {
96    parse_check_timeout(git::config_get(CHECK_TIMEOUT_KEY)?.as_deref())
97}
98
99fn parse_check_timeout(value: Option<&str>) -> Result<Option<Duration>> {
100    let seconds = match value {
101        Some(raw) => raw.trim().parse::<u64>().map_err(|_| {
102            anyhow::anyhow!(
103                "invalid {CHECK_TIMEOUT_KEY} value {raw:?}; expected a whole number of seconds"
104            )
105        })?,
106        None => DEFAULT_CHECK_TIMEOUT_SECS,
107    };
108    // Zero is the explicit "wait forever" escape hatch.
109    Ok((seconds > 0).then(|| Duration::from_secs(seconds)))
110}
111
112/// A boolean setting's value, defaulting to false when unset.
113pub fn bool_setting(key: &str) -> Result<bool> {
114    Ok(git::config_get_bool(key)?.unwrap_or(false))
115}
116
117/// Whether to seed a new review's body from the repo's PR/MR template
118/// (`stk.usePrTemplate`). Defaults to true - unlike most bool settings - so
119/// the template is honored out of the box; set false to opt into a lean,
120/// git-stk-only body.
121pub fn use_pr_template() -> Result<bool> {
122    Ok(git::config_get_bool(USE_PR_TEMPLATE_KEY)?.unwrap_or(true))
123}
124
125/// Resolve a `--push`/`--no-push` flag pair against its config-key default.
126pub fn push_enabled(mode: PushMode, key: &str) -> Result<bool> {
127    match mode {
128        PushMode::Config => Ok(git::config_get_bool(key)?.unwrap_or(false)),
129        PushMode::Enabled => Ok(true),
130        PushMode::Disabled => Ok(false),
131    }
132}
133
134/// Resolve a `--fetch`/`--no-fetch` flag pair against `stk.fetchBeforeRestack`.
135pub fn fetch_enabled(mode: FetchMode) -> Result<bool> {
136    match mode {
137        FetchMode::Config => Ok(git::config_get_bool(FETCH_BEFORE_RESTACK_KEY)?.unwrap_or(false)),
138        FetchMode::Enabled => Ok(true),
139        FetchMode::Disabled => Ok(false),
140    }
141}
142
143/// Where `new --worktree` puts a branch's worktree. From `stk.worktreeDir`, or a
144/// sibling of the repo root named `<repo>-worktrees` - outside the repo, so the
145/// worktrees do not land in its own file watchers, ignore rules, or `git status`.
146///
147/// Anchored on the *main* worktree, not the current one, so every worktree of a
148/// repo agrees on one directory: derived from wherever the command ran, `new
149/// --worktree` inside a worktree would nest the next one under it, and `repair`
150/// would look for owned worktrees somewhere they were never put.
151pub fn worktree_dir() -> Result<std::path::PathBuf> {
152    if let Some(configured) = git::config_get(WORKTREE_DIR_KEY)?
153        && !configured.trim().is_empty()
154    {
155        return std::path::absolute(configured.trim()).context("failed to resolve stk.worktreeDir");
156    }
157
158    let root = git::main_worktree_root()?;
159    let name = root
160        .file_name()
161        .map(|name| name.to_string_lossy().into_owned())
162        .unwrap_or_else(|| "repo".to_owned());
163    let parent = root
164        .parent()
165        .context("repository root has no parent directory")?;
166    Ok(parent.join(format!("{name}-worktrees")))
167}
168
169/// The worktree directory for `branch`, under [`worktree_dir`]. Branch names nest
170/// as real directories, so `feat/a` lands at `<dir>/feat/a` and its basename
171/// still matches the branch tail - the way git's own path-to-branch guessing
172/// reads a worktree path.
173pub fn worktree_path_for(branch: &str) -> Result<std::path::PathBuf> {
174    let mut path = worktree_dir()?;
175    for component in branch.split('/').filter(|part| !part.is_empty()) {
176        if component == "." || component == ".." {
177            bail!("branch name {branch} cannot be used as a worktree path");
178        }
179        path.push(component);
180    }
181    Ok(path)
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn check_timeout_defaults_when_unset() {
190        assert_eq!(
191            parse_check_timeout(None).unwrap(),
192            Some(Duration::from_secs(DEFAULT_CHECK_TIMEOUT_SECS))
193        );
194    }
195
196    #[test]
197    fn check_timeout_zero_waits_indefinitely() {
198        assert_eq!(parse_check_timeout(Some("0")).unwrap(), None);
199    }
200
201    #[test]
202    fn check_timeout_reads_whole_seconds() {
203        assert_eq!(
204            parse_check_timeout(Some("300")).unwrap(),
205            Some(Duration::from_secs(300))
206        );
207        // Surrounding whitespace is tolerated (git config values can carry it).
208        assert_eq!(
209            parse_check_timeout(Some(" 60 ")).unwrap(),
210            Some(Duration::from_secs(60))
211        );
212    }
213
214    #[test]
215    fn check_timeout_rejects_non_numbers() {
216        let error = parse_check_timeout(Some("soon")).unwrap_err();
217        assert!(
218            error.to_string().contains("stk.checkTimeout"),
219            "unexpected error: {error:#}"
220        );
221    }
222}