Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor: collapse more duplicated paths onto single sources (#2934)

Maximilian Roos987e3e0c630d
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 21595babc..627c1cdf2 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -333,13 +333,7 @@ pub fn scan_shell_configs(
// Iterate every supported shell. Shells the user doesn't have are filtered
// out of the Skipped output by `is_installed()` below, matching how
// bash/zsh/fish/nushell are handled.
- let default_shells = vec![
- Shell::Bash,
- Shell::Zsh,
- Shell::Fish,
- Shell::Nushell,
- Shell::PowerShell,
- ];
+ let default_shells = Shell::all();
// Detect whether the user is *running in* PowerShell or Nushell right now.
// This unlocks `allow_create` so we'll write a profile/autoload file even
@@ -935,14 +929,9 @@ fn scan_for_uninstall(
dry_run: bool,
cmd: &str,
) -> Result<UninstallScanResult, String> {
- // For uninstall, always include PowerShell to clean up any existing profiles
- let default_shells = vec![
- Shell::Bash,
- Shell::Zsh,
- Shell::Fish,
- Shell::Nushell,
- Shell::PowerShell,
- ];
+ // For uninstall, scan every shell (Shell::all includes PowerShell) to clean
+ // up any existing profiles.
+ let default_shells = Shell::all();
let shells = shell_filter.map_or(default_shells, |shell| vec![shell]);
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 33a78b498..1192181a3 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -290,7 +290,7 @@ fn spawn_detached_windows(
let shell = ShellConfig::get()?;
// Build the command based on shell type
- let mut cmd = if shell.is_posix() {
+ let mut cmd = if shell.is_posix {
// Git Bash available - use same syntax as Unix
let full_command = build_printf_pipe_command(command, context_json);
shell.command(&full_command)
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 37e97f7dc..86b4ad182 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -432,6 +432,29 @@ fn fetch_same_repo_branch(repo: &Repository, info: &RemoteRefInfo) -> anyhow::Re
Ok(())
}
+/// Parse a `pr:N` / `mr:N` shortcut into its ref type and number, first
+/// normalising a forge PR/MR web URL (e.g.
+/// `https://github.com/owner/repo/pull/123`) into the same literal shortcut so
+/// both forms flow through one dispatch. Returns `None` for a regular branch
+/// name, which callers resolve as an ordinary ref.
+fn parse_ref_shortcut(input: &str) -> Option<(RefType, u32)> {
+ let normalised = parse_ref_url(input);
+ let input = normalised.as_deref().unwrap_or(input);
+ if let Some(number) = input
+ .strip_prefix("pr:")
+ .and_then(|s| s.parse::<u32>().ok())
+ {
+ return Some((RefType::Pr, number));
+ }
+ if let Some(number) = input
+ .strip_prefix("mr:")
+ .and_then(|s| s.parse::<u32>().ok())
+ {
+ return Some((RefType::Mr, number));
+ }
+ None
+}
+
/// Resolve a `--base` value, expanding `pr:`/`mr:` shortcuts. Non-shortcut
/// inputs go through [`Repository::resolve_worktree_name`] (handles `@`/`-`/`^`).
///
@@ -449,22 +472,12 @@ fn resolve_base_ref(
repo: &Repository,
base: &str,
) -> anyhow::Result<(String, Option<(String, String)>)> {
- // Forge PR/MR web URLs (e.g. `https://github.com/owner/repo/pull/123`)
- // normalise into the literal `pr:N` / `mr:N` shortcut so the parsing
- // below handles both forms identically — no duplicate dispatch.
- let normalised = parse_ref_url(base);
- let base = normalised.as_deref().unwrap_or(base);
-
- if let Some(suffix) = base.strip_prefix("pr:")
- && let Ok(number) = suffix.parse::<u32>()
- {
- return resolve_pr_base(repo, number);
- }
-
- if let Some(suffix) = base.strip_prefix("mr:")
- && let Ok(number) = suffix.parse::<u32>()
- {
- return resolve_remote_ref_as_base(repo, &GitLabProvider, number);
+ match parse_ref_shortcut(base) {
+ Some((RefType::Pr, number)) => return resolve_pr_base(repo, number),
+ Some((RefType::Mr, number)) => {
+ return resolve_remote_ref_as_base(repo, &GitLabProvider, number);
+ }
+ None => {}
}
let resolved = repo.resolve_worktree_name(base)?;
@@ -533,24 +546,14 @@ fn resolve_switch_target(
create: bool,
base: Option<&str>,
) -> anyhow::Result<ResolvedTarget> {
- // Forge PR/MR web URLs (e.g. `https://github.com/owner/repo/pull/123`)
- // normalise into the literal `pr:N` / `mr:N` shortcut so the parsing
- // below handles both forms identically — no duplicate dispatch.
- let normalised = parse_ref_url(branch);
- let branch = normalised.as_deref().unwrap_or(branch);
-
- // Handle pr:<number> syntax — dispatches to GitHub, Gitea, or Azure DevOps based on remotes.
- if let Some(suffix) = branch.strip_prefix("pr:")
- && let Ok(number) = suffix.parse::<u32>()
- {
- return resolve_pr_target(repo, number, create, base);
- }
-
- // Handle mr:<number> syntax (GitLab MRs)
- if let Some(suffix) = branch.strip_prefix("mr:")
- && let Ok(number) = suffix.parse::<u32>()
- {
- return resolve_remote_ref(repo, &GitLabProvider, number, create, base);
+ // `pr:N` dispatches to GitHub, Gitea, or Azure DevOps based on remotes;
+ // `mr:N` to GitLab. Forge PR/MR web URLs normalise to the same shortcuts.
+ match parse_ref_shortcut(branch) {
+ Some((RefType::Pr, number)) => return resolve_pr_target(repo, number, create, base),
+ Some((RefType::Mr, number)) => {
+ return resolve_remote_ref(repo, &GitLabProvider, number, create, base);
+ }
+ None => {}
}
// Regular branch switch
diff --git a/src/config/mod.rs b/src/config/mod.rs
index bef2ced7e..648d6a6aa 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -100,6 +100,29 @@ pub(crate) fn is_default<T: Default + PartialEq>(value: &T) -> bool {
*value == T::default()
}
+/// Returns all valid top-level keys for a config type, derived from its
+/// JsonSchema. The schema flattens nested structs (e.g. `HooksConfig`), so all
+/// top-level keys appear in `properties`. Drives `WorktrunkConfig::is_valid_key`
+/// (misplaced-key classification) and the round-trip in `unknown_tree`.
+///
+/// `pre-create`/`post-create` are appended as silent serde aliases for the
+/// canonical `pre-start`/`post-start` hook keys (see `HooksConfig` in
+/// `src/config/hooks.rs`). The schema only knows canonical names from
+/// `#[serde(rename = ...)]`; adding the aliases here keeps the unknown-key
+/// round-trip from flagging an accepted name as unknown.
+pub(crate) fn schema_top_level_keys<T: schemars::JsonSchema>() -> Vec<String> {
+ let schema = schemars::SchemaGenerator::default().into_root_schema_for::<T>();
+ let mut keys: Vec<String> = schema
+ .as_object()
+ .and_then(|obj| obj.get("properties"))
+ .and_then(|p| p.as_object())
+ .map(|props| props.keys().cloned().collect())
+ .unwrap_or_default();
+ keys.push("pre-create".to_string());
+ keys.push("post-create".to_string());
+ keys
+}
+
// Re-export public types
pub use approvals::{Approvals, approvals_path, require_approvals_path};
pub use commands::{Command, CommandConfig, HookStep, append_aliases};
diff --git a/src/config/project.rs b/src/config/project.rs
index 1b1198f42..dba8acdd6 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -307,30 +307,12 @@ impl ProjectConfig {
}
}
-/// Returns all valid top-level keys in project config, derived from the JsonSchema.
-///
-/// This includes keys from ProjectConfig and HooksConfig (flattened).
-/// Public for use by the `WorktrunkConfig` trait implementation.
-///
-/// `pre-create`/`post-create` are appended as silent serde aliases for the
-/// canonical `pre-start`/`post-start` hook keys (see `HooksConfig` in
-/// `src/config/hooks.rs`). The schema only knows canonical names from
-/// `#[serde(rename = ...)]`; adding the aliases here keeps the unknown-key
-/// round-trip from flagging an accepted name as unknown.
+/// All valid top-level keys in project config (ProjectConfig + flattened
+/// HooksConfig), derived from the JsonSchema via
+/// `config::schema_top_level_keys`. Public for use by the
+/// `WorktrunkConfig` trait implementation.
pub fn valid_project_config_keys() -> Vec<String> {
- use schemars::SchemaGenerator;
-
- let schema = SchemaGenerator::default().into_root_schema_for::<ProjectConfig>();
-
- let mut keys: Vec<String> = schema
- .as_object()
- .and_then(|obj| obj.get("properties"))
- .and_then(|p| p.as_object())
- .map(|props| props.keys().cloned().collect())
- .unwrap_or_default();
- keys.push("pre-create".to_string());
- keys.push("post-create".to_string());
- keys
+ crate::config::schema_top_level_keys::<ProjectConfig>()
}
#[cfg(test)]
diff --git a/src/config/user/schema.rs b/src/config/user/schema.rs
index d4327c049..c779411c8 100644
--- a/src/config/user/schema.rs
+++ b/src/config/user/schema.rs
@@ -4,32 +4,11 @@
//! `WorktrunkConfig::is_valid_key` so unknown-key classification can tell
//! "belongs in the other config" from "truly unknown."
-use schemars::SchemaGenerator;
-
use super::UserConfig;
-/// Returns all valid top-level keys in user config, derived from the JsonSchema.
-///
-/// This includes keys from UserConfig and HooksConfig (flattened).
+/// All valid top-level keys in user config (UserConfig + flattened HooksConfig),
+/// derived from the JsonSchema via `config::schema_top_level_keys`.
/// Public for use by the `WorktrunkConfig` trait implementation.
-///
-/// `pre-create`/`post-create` are appended as silent serde aliases for the
-/// canonical `pre-start`/`post-start` hook keys (see `HooksConfig` in
-/// `src/config/hooks.rs`). The schema only knows canonical names from
-/// `#[serde(rename = ...)]`; adding the aliases here keeps the unknown-key
-/// round-trip from flagging an accepted name as unknown.
pub fn valid_user_config_keys() -> Vec<String> {
- let schema = SchemaGenerator::default().into_root_schema_for::<UserConfig>();
-
- // Extract property names from the schema
- // The schema flattens nested structs, so all top-level keys appear in properties
- let mut keys: Vec<String> = schema
- .as_object()
- .and_then(|obj| obj.get("properties"))
- .and_then(|p| p.as_object())
- .map(|props| props.keys().cloned().collect())
- .unwrap_or_default();
- keys.push("pre-create".to_string());
- keys.push("post-create".to_string());
- keys
+ crate::config::schema_top_level_keys::<UserConfig>()
}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index bf4c88717..e0ef91264 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -241,12 +241,7 @@ impl Merge for CommitConfig {
fn merge_with(&self, other: &Self) -> Self {
Self {
stage: other.stage.or(self.stage),
- generation: match (&self.generation, &other.generation) {
- (None, None) => None,
- (Some(s), None) => Some(s.clone()),
- (None, Some(o)) => Some(o.clone()),
- (Some(s), Some(o)) => Some(s.merge_with(o)),
- },
+ generation: merge_optional(self.generation.as_ref(), other.generation.as_ref()),
}
}
}
@@ -404,12 +399,7 @@ impl Merge for SwitchConfig {
fn merge_with(&self, other: &Self) -> Self {
Self {
cd: other.cd.or(self.cd),
- picker: match (&self.picker, &other.picker) {
- (None, None) => None,
- (Some(s), None) => Some(s.clone()),
- (None, Some(o)) => Some(o.clone()),
- (Some(s), Some(o)) => Some(s.merge_with(o)),
- },
+ picker: merge_optional(self.picker.as_ref(), other.picker.as_ref()),
}
}
}
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 66d5edf35..4a879ab97 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -71,6 +71,16 @@ pub struct MergeProbeResult {
/// tuning.
const PATCH_ID_SCAN_MAX_COMMITS: usize = 500;
+/// Outcome of `git merge-tree --write-tree`, classified by exit code.
+///
+/// Exit 0 → `Clean` carrying the resulting tree SHA; exit 1 → `Conflict`;
+/// anything else is an error (the helper bails). Both merge-tree callers
+/// share this dispatch; they differ only in what they do with a clean tree.
+enum MergeTreeOutcome {
+ Clean { tree: String },
+ Conflict,
+}
+
impl Repository {
/// Check if `base_sha` is an ancestor of `head_sha`, taking commit SHAs
/// directly. Hits the persistent SHA-keyed cache without going through
@@ -195,6 +205,28 @@ impl Repository {
self.run_merge_tree(base_sha, head_commit, base_sha, &cache_head)
}
+ /// Run `git merge-tree --write-tree <a> <b>` and classify the outcome by
+ /// exit code. Exit 1 → [`MergeTreeOutcome::Conflict`]; anything other than
+ /// success is an error; exit 0 → [`MergeTreeOutcome::Clean`] with the
+ /// resulting tree SHA (first line of stdout).
+ fn merge_tree_outcome(&self, a: &str, b: &str) -> anyhow::Result<MergeTreeOutcome> {
+ // Exit codes: 0 = clean merge, 1 = conflicts, 128+ = error (invalid ref, corrupt repo)
+ let output = self.run_command_output(&["merge-tree", "--write-tree", a, b])?;
+
+ if output.status.code() == Some(1) {
+ return Ok(MergeTreeOutcome::Conflict);
+ }
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("git merge-tree failed for {a} {b}: {}", stderr.trim());
+ }
+
+ // Clean merge — first line of stdout is the resulting tree SHA.
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let tree = stdout.lines().next().unwrap_or("").trim().to_string();
+ Ok(MergeTreeOutcome::Clean { tree })
+ }
+
/// Run merge-tree and cache the result.
///
/// `base_sha` and `head_sha` are passed to `git merge-tree` (must be
@@ -213,23 +245,12 @@ impl Repository {
return Ok(true);
}
- // Exit codes: 0 = clean merge, 1 = conflicts, 128+ = error (invalid ref, corrupt repo)
- let output =
- self.run_command_output(&["merge-tree", "--write-tree", base_sha, head_sha])?;
-
- if output.status.code() == Some(1) {
- super::sha_cache::put_merge_conflicts(self, cache_base, cache_head, true);
- return Ok(true);
- }
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!(
- "git merge-tree failed for {base_sha} {head_sha}: {}",
- stderr.trim()
- );
- }
- super::sha_cache::put_merge_conflicts(self, cache_base, cache_head, false);
- Ok(false)
+ let conflicts = matches!(
+ self.merge_tree_outcome(base_sha, head_sha)?,
+ MergeTreeOutcome::Conflict
+ );
+ super::sha_cache::put_merge_conflicts(self, cache_base, cache_head, conflicts);
+ Ok(conflicts)
}
/// Check if merging a branch into target would add anything (not already integrated).
@@ -245,30 +266,16 @@ impl Repository {
branch: &str,
target: &str,
) -> anyhow::Result<Option<bool>> {
- // Exit codes: 0 = clean merge, 1 = conflicts, 128+ = error (invalid ref, corrupt repo)
- let output = self.run_command_output(&["merge-tree", "--write-tree", target, branch])?;
-
- if output.status.code() == Some(1) {
- // Conflicts — caller should try patch-id fallback
- return Ok(None);
- }
- if !output.status.success() {
- let stderr = String::from_utf8_lossy(&output.stderr);
- anyhow::bail!(
- "git merge-tree failed for {target} {branch}: {}",
- stderr.trim()
- );
+ match self.merge_tree_outcome(target, branch)? {
+ // Conflicts — caller should try patch-id fallback.
+ MergeTreeOutcome::Conflict => Ok(None),
+ MergeTreeOutcome::Clean { tree } => {
+ // If the merge result differs from target's tree, merging would
+ // add something (the branch is not already integrated).
+ let target_tree = self.rev_parse_tree(&format!("{target}^{{tree}}"))?;
+ Ok(Some(tree != target_tree))
+ }
}
-
- // Clean merge — first line of stdout is the resulting tree SHA
- let merge_tree = String::from_utf8_lossy(&output.stdout);
- let merge_tree = merge_tree.lines().next().unwrap_or("").trim();
-
- // Get target's tree for comparison
- let target_tree = self.rev_parse_tree(&format!("{target}^{{tree}}"))?;
-
- // If merge result differs from target's tree, merging would add something
- Ok(Some(merge_tree != target_tree))
}
/// Detect squash merges via patch-id matching.
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 87cfb4c06..338543f3e 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1257,14 +1257,15 @@ impl Repository {
return Ok(Some("MERGING".to_string()));
}
- // Check for rebase
- if git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists() {
- let rebase_dir = if git_dir.join("rebase-merge").exists() {
- git_dir.join("rebase-merge")
- } else {
- git_dir.join("rebase-apply")
- };
-
+ // Check for rebase. `rebase-merge` (interactive/merge backend) and
+ // `rebase-apply` (am backend) are mutually exclusive; probe each once.
+ let rebase_merge = git_dir.join("rebase-merge");
+ let rebase_apply = git_dir.join("rebase-apply");
+ if let Some(rebase_dir) = rebase_merge
+ .exists()
+ .then_some(rebase_merge)
+ .or_else(|| rebase_apply.exists().then_some(rebase_apply))
+ {
if let (Ok(msgnum), Ok(end)) = (
std::fs::read_to_string(rebase_dir.join("msgnum")),
std::fs::read_to_string(rebase_dir.join("end")),
diff --git a/src/help_pager.rs b/src/help_pager.rs
index 1ce11f655..087cada20 100644
--- a/src/help_pager.rs
+++ b/src/help_pager.rs
@@ -55,7 +55,7 @@ fn detect_help_pager() -> Option<String> {
// Default to "less" only if we have a POSIX shell (Unix or Git Bash on Windows)
// Without Git Bash, less isn't typically available on Windows
- if shell.is_posix() {
+ if shell.is_posix {
Some("less".to_string())
} else {
log::debug!("No POSIX shell available, skipping pager (less not available)");
diff --git a/src/shell/mod.rs b/src/shell/mod.rs
index fe6004317..73dca1f84 100644
--- a/src/shell/mod.rs
+++ b/src/shell/mod.rs
@@ -43,6 +43,18 @@ pub enum Shell {
}
impl Shell {
+ /// All supported shells, in the order `wt config shell install` /
+ /// `uninstall` scan them. The single source for that scan list.
+ pub fn all() -> Vec<Shell> {
+ vec![
+ Shell::Bash,
+ Shell::Zsh,
+ Shell::Fish,
+ Shell::Nushell,
+ Shell::PowerShell,
+ ]
+ }
+
/// Whether this shell uses a standalone wrapper file as integration.
///
/// Wrapper-based shells (Fish, Nushell) install a complete function file that the shell
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index f8898d9f0..4605bb157 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -173,7 +173,12 @@ pub struct ShellConfig {
pub executable: PathBuf,
/// Arguments to pass before the command (e.g., ["-c"] for sh, ["/C"] for cmd)
pub args: Vec<String>,
- /// Whether this is a POSIX-compatible shell (bash/sh)
+ /// Whether this shell supports POSIX syntax (bash, sh, zsh, etc.).
+ ///
+ /// When true, commands can use POSIX features like:
+ /// - `{ cmd; } 1>&2` for stdout redirection
+ /// - `printf '%s' ... | cmd` for stdin piping
+ /// - `nohup ... &` for background execution
pub is_posix: bool,
/// Human-readable name for error messages
pub name: String,
@@ -201,16 +206,6 @@ impl ShellConfig {
cmd.arg(shell_command);
cmd
}
-
- /// Check if this shell supports POSIX syntax (bash, sh, zsh, etc.)
- ///
- /// When true, commands can use POSIX features like:
- /// - `{ cmd; } 1>&2` for stdout redirection
- /// - `printf '%s' ... | cmd` for stdin piping
- /// - `nohup ... &` for background execution
- pub fn is_posix(&self) -> bool {
- self.is_posix
- }
}
/// Detect the best available shell for the current platform
@@ -1815,13 +1810,6 @@ mod tests {
assert_eq!(config.args, cloned.args);
}
- #[test]
- fn test_shell_is_posix_method() {
- let config = ShellConfig::get().unwrap();
- // is_posix method should match the field
- assert_eq!(config.is_posix(), config.is_posix);
- }
-
// ========================================================================
// Cmd and timeout tests
// ========================================================================