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