Skip to content

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

refactor: extract append_aliases helper, add e2e alias test (#1731)

Maximilian Roos79dc6a229aaf
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index b890ecec0..7c2f28f21 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -12,7 +12,9 @@ use std::collections::HashMap;
use anyhow::{Context, bail};
use color_print::cformat;
-use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig, expand_template};
+use worktrunk::config::{
+ CommandConfig, ProjectConfig, UserConfig, append_aliases, expand_template,
+};
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::styling::{
eprintln, format_bash_with_gutter, info_message, progress_message, warning_message,
@@ -147,12 +149,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
// need approval regardless of whether user also defines the alias.
let mut aliases = user_config.aliases(project_id.as_deref());
if let Some(project_aliases) = project_config.as_ref().and_then(|pc| pc.aliases.as_ref()) {
- for (k, v) in project_aliases {
- aliases
- .entry(k.clone())
- .and_modify(|existing| *existing = existing.merge_append(v))
- .or_insert_with(|| v.clone());
- }
+ append_aliases(&mut aliases, project_aliases);
}
// Warn about aliases that shadow built-in step commands
diff --git a/src/completion.rs b/src/completion.rs
index 846a171ae..e609393f4 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -9,7 +9,7 @@ use clap_complete::env::CompleteEnv;
use crate::cli;
use crate::display::format_relative_time_short;
-use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};
+use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig, append_aliases};
use worktrunk::git::{BranchCategory, HookType, Repository};
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
@@ -439,14 +439,9 @@ fn load_aliases_for_completion() -> BTreeMap<String, CommandConfig> {
}
// Project config appends
if let Ok(Some(project_config)) = ProjectConfig::load(&repo, false)
- && let Some(project_aliases) = project_config.aliases
+ && let Some(ref project_aliases) = project_config.aliases
{
- for (k, v) in &project_aliases {
- aliases
- .entry(k.clone())
- .and_modify(|existing| *existing = existing.merge_append(v))
- .or_insert_with(|| v.clone());
- }
+ append_aliases(&mut aliases, project_aliases);
}
} else if let Ok(user_config) = UserConfig::load() {
aliases.extend(user_config.aliases(None));
diff --git a/src/config/commands.rs b/src/config/commands.rs
index cc7a0a73d..ba82cd27c 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -3,6 +3,8 @@
//! Handles parsing and representation of commands that run during various phases
//! of worktree and merge operations.
+use std::collections::BTreeMap;
+
use indexmap::IndexMap;
use schemars::JsonSchema;
use serde::ser::SerializeMap;
@@ -79,6 +81,21 @@ impl CommandConfig {
}
}
+/// Append alias commands from `additions` into `base`.
+///
+/// On name collision, commands are appended (base first, then additions),
+/// matching how hooks merge across config layers.
+pub fn append_aliases(
+ base: &mut BTreeMap<String, CommandConfig>,
+ additions: &BTreeMap<String, CommandConfig>,
+) {
+ for (k, v) in additions {
+ base.entry(k.clone())
+ .and_modify(|existing| *existing = existing.merge_append(v))
+ .or_insert_with(|| v.clone());
+ }
+}
+
// Custom deserialization to handle 2 TOML formats
impl<'de> Deserialize<'de> for CommandConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 3df84523e..87b1571c3 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -72,7 +72,7 @@ impl WorktrunkConfig for ProjectConfig {
// Re-export public types
pub use approvals::{Approvals, approvals_path};
-pub use commands::{Command, CommandConfig};
+pub use commands::{Command, CommandConfig, append_aliases};
pub use deprecation::DeprecationInfo;
pub use deprecation::Deprecations;
pub use deprecation::check_and_migrate;
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index 64e0211d8..e68a3bbe2 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -207,12 +207,7 @@ impl UserConfig {
.and_then(|p| self.projects.get(p))
.and_then(|proj| proj.overrides.aliases.as_ref())
{
- for (k, v) in proj_aliases {
- result
- .entry(k.clone())
- .and_modify(|existing| *existing = existing.merge_append(v))
- .or_insert_with(|| v.clone());
- }
+ crate::config::commands::append_aliases(&mut result, proj_aliases);
}
result
}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 8fcc85155..90b90d41f 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -539,12 +539,7 @@ fn merge_alias_maps(
(None, Some(o)) => Some(o.clone()),
(Some(b), Some(o)) => {
let mut merged = b.clone();
- for (k, v) in o {
- merged
- .entry(k.clone())
- .and_modify(|existing| *existing = existing.merge_append(v))
- .or_insert_with(|| v.clone());
- }
+ crate::config::commands::append_aliases(&mut merged, o);
Some(merged)
}
}
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 28bcb902c..9e6e8613a 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -287,6 +287,40 @@ shared = "echo user-version"
);
}
+/// Both global and per-project user aliases execute in order on name collision.
+///
+/// Uses project config (`.config/wt.toml`) + user config to verify the
+/// project-vs-user append, since `test_aliases_accessor_appends_on_collision`
+/// already covers the user-config internal append via unit test.
+#[rstest]
+fn test_alias_append_executes_both(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+greet = "echo PROJECT"
+"#,
+ );
+ repo.commit("Add alias config");
+ let feature_path = repo.add_worktree("feature");
+ repo.write_test_config(
+ r#"
+[aliases]
+greet = "echo USER"
+"#,
+ );
+
+ let settings = setup_snapshot_settings(&repo);
+ let _guard = settings.bind_to_scope();
+
+ // Both commands execute: user first, then project (--yes approves project alias)
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["greet", "--yes"],
+ Some(&feature_path),
+ ));
+}
+
// ============================================================================
// Approval tests
// ============================================================================
diff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snap
new file mode 100644
index 000000000..0cb519291
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_append_executes_both.snap
@@ -0,0 +1,48 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - step
+ - greet
+ - "--yes"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Running alias greet
+USER
+PROJECT