1use 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
30pub const DEFAULT_CHECK_TIMEOUT_SECS: u64 = 1800;
34
35pub 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
64pub fn remote() -> Result<String> {
66 Ok(git::config_get(REMOTE_KEY)?.unwrap_or_else(|| DEFAULT_REMOTE.to_owned()))
67}
68
69pub fn gitlab_host() -> Result<Option<String>> {
73 git::config_get(GITLAB_HOST_KEY)
74}
75
76pub fn gitea_host() -> Result<Option<String>> {
80 git::config_get(GITEA_HOST_KEY)
81}
82
83pub 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
94pub 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 Ok((seconds > 0).then(|| Duration::from_secs(seconds)))
112}
113
114pub fn bool_setting(key: &str) -> Result<bool> {
116 Ok(git::config_get_bool(key)?.unwrap_or(false))
117}
118
119pub fn use_pr_template() -> Result<bool> {
124 Ok(git::config_get_bool(USE_PR_TEMPLATE_KEY)?.unwrap_or(true))
125}
126
127pub 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
136pub 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
145pub 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
171pub 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 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}