Skip to content

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

feat: use append semantics for alias merging (#1724)

Maximilian Roos9ad642f874e8
diff --git a/dev/config.example.toml b/dev/config.example.toml
index d431fb20f..1601b6018 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -140,7 +140,7 @@
#
# #### Setting overrides [experimental]
#
-# Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run. Aliases merge — per-project aliases override global aliases on name collision.
+# Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks and aliases append — both global and per-project versions run (global first).
#
# [projects."github.com/user/repo"]
# worktree-path = ".worktrees/{{ branch | sanitize }}"
diff --git a/docs/content/config.md b/docs/content/config.md
index 2e9912359..cc103632b 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -232,7 +232,7 @@ Entries are keyed by project identifier (e.g., `github.com/user/repo`).
#### Setting overrides <span class="badge-experimental"></span>
-Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run. Aliases merge — per-project aliases override global aliases on name collision.
+Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks and aliases append — both global and per-project versions run (global first).
```toml
[projects."github.com/user/repo"]
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index 0cc1f191d..8ee266662 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -223,7 +223,7 @@ Entries are keyed by project identifier (e.g., `github.com/user/repo`).
#### Setting overrides [experimental]
-Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run. Aliases merge — per-project aliases override global aliases on name collision.
+Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks and aliases append — both global and per-project versions run (global first).
```toml
[projects."github.com/user/repo"]
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 0d4ceaa53..5ea307912 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1790,7 +1790,7 @@ Entries are keyed by project identifier (e.g., `github.com/user/repo`).
#### Setting overrides [experimental]
-Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run. Aliases merge — per-project aliases override global aliases on name collision.
+Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks and aliases append — both global and per-project versions run (global first).
```toml
[projects."github.com/user/repo"]
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index a4ecbdbc5..66b3e1c4f 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -12,13 +12,13 @@ use std::collections::{BTreeMap, HashMap};
use anyhow::{Context, bail};
use color_print::cformat;
-use worktrunk::config::{ProjectConfig, UserConfig, expand_template};
+use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig, expand_template};
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::styling::{
eprintln, format_bash_with_gutter, info_message, progress_message, warning_message,
};
-use crate::commands::command_approval::approve_alias;
+use crate::commands::command_approval::approve_alias_commands;
use crate::commands::command_executor::{CommandContext, build_hook_context};
use crate::commands::for_each::{CommandError, run_command_streaming};
@@ -111,14 +111,14 @@ fn alias_needs_approval(
project_config: &Option<ProjectConfig>,
user_config: &UserConfig,
project_id: Option<&str>,
-) -> Option<String> {
+) -> Option<CommandConfig> {
// Check if alias exists in project config
- let project_template = project_config
+ let project_commands = project_config
.as_ref()
.and_then(|pc| pc.aliases.as_ref())
.and_then(|a| a.get(alias_name));
- let project_template = project_template?;
+ let project_commands = project_commands?;
// Check if user config overrides this alias (user overrides are trusted)
let user_aliases = user_config.aliases(project_id);
@@ -126,7 +126,7 @@ fn alias_needs_approval(
return None;
}
- Some(project_template.clone())
+ Some(project_commands.clone())
}
/// Find the closest match for `input` among `candidates` using Jaro similarity.
@@ -146,16 +146,17 @@ fn find_closest_match<'a>(input: &str, candidates: &[&'a str]) -> Option<&'a str
/// Run a configured alias by name.
///
/// Looks up the alias in merged config (project config + user config),
-/// expands the template, and executes it. Project-config aliases require
-/// command approval before execution.
+/// expands each command template, and executes them in order. Project-config
+/// aliases require command approval before execution.
pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
let repo = Repository::current()?;
let user_config = UserConfig::load()?;
let project_id = repo.project_identifier().ok();
let project_config = ProjectConfig::load(&repo, true)?;
- // Merge aliases: project config first, then user config overrides
- let mut aliases: BTreeMap<String, String> = project_config
+ // Merge aliases: start with project config, user config replaces on collision
+ // (user aliases are trusted; project aliases need approval)
+ let mut aliases: BTreeMap<String, CommandConfig> = project_config
.as_ref()
.and_then(|pc| pc.aliases.clone())
.unwrap_or_default();
@@ -183,7 +184,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
);
}
- let Some(template) = aliases.get(&opts.name) else {
+ let Some(cmd_config) = aliases.get(&opts.name) else {
// Check for typos against both built-in commands and aliases
let mut all_candidates: Vec<&str> = BUILTIN_STEP_COMMANDS.to_vec();
// Only include non-shadowed aliases as candidates
@@ -226,7 +227,7 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
// project_id is required for approval — re-derive with error propagation
// rather than using the .ok() from above.
if !opts.dry_run
- && let Some(project_template) = alias_needs_approval(
+ && let Some(project_commands) = alias_needs_approval(
&opts.name,
&project_config,
&user_config,
@@ -236,7 +237,8 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
let project_id = repo
.project_identifier()
.context("Cannot determine project identifier for alias approval")?;
- let approved = approve_alias(&project_template, &opts.name, &project_id, opts.yes)?;
+ let approved =
+ approve_alias_commands(&project_commands, &opts.name, &project_id, opts.yes)?;
if !approved {
return Ok(());
}
@@ -261,15 +263,27 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- let command = expand_template(template, &vars, true, &repo, &opts.name)?;
+ // Build JSON context for stdin
+ let context_json = serde_json::to_string(&context_map)
+ .expect("HashMap<String, String> serialization should never fail");
+
+ let commands = cmd_config.commands();
if opts.dry_run {
+ let expanded: Vec<_> = commands
+ .iter()
+ .map(|cmd| expand_template(&cmd.template, &vars, true, &repo, &opts.name))
+ .collect::<Result<_, _>>()?;
eprintln!(
"{}",
info_message(cformat!(
"Alias <bold>{}</> would run:\n{}",
opts.name,
- format_bash_with_gutter(&command)
+ expanded
+ .iter()
+ .map(|c| format_bash_with_gutter(c))
+ .collect::<Vec<_>>()
+ .join("\n")
))
);
return Ok(());
@@ -280,20 +294,23 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {
progress_message(cformat!("Running alias <bold>{}</>", opts.name))
);
- // Build JSON context for stdin
- let context_json = serde_json::to_string(&context_map)
- .expect("HashMap<String, String> serialization should never fail");
-
- match run_command_streaming(&command, &wt_path, Some(&context_json)) {
- Ok(()) => Ok(()),
- Err(CommandError::SpawnFailed(err)) => {
- bail!("Failed to run alias '{}': {}", opts.name, err);
- }
- Err(CommandError::ExitCode(exit_code)) => Err(WorktrunkError::AlreadyDisplayed {
- exit_code: exit_code.unwrap_or(1),
+ for cmd in commands {
+ let command = expand_template(&cmd.template, &vars, true, &repo, &opts.name)?;
+ match run_command_streaming(&command, &wt_path, Some(&context_json)) {
+ Ok(()) => {}
+ Err(CommandError::SpawnFailed(err)) => {
+ bail!("Failed to run alias '{}': {}", opts.name, err);
+ }
+ Err(CommandError::ExitCode(exit_code)) => {
+ return Err(WorktrunkError::AlreadyDisplayed {
+ exit_code: exit_code.unwrap_or(1),
+ }
+ .into());
+ }
}
- .into()),
}
+
+ Ok(())
}
#[cfg(test)]
diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rs
index 365d223e0..8022f2a27 100644
--- a/src/commands/command_approval.rs
+++ b/src/commands/command_approval.rs
@@ -149,23 +149,27 @@ fn prompt_for_batch_approval(
/// Approve a project-config alias before execution.
///
/// Returns `Ok(true)` if approved (or already approved), `Ok(false)` if declined.
-pub fn approve_alias(
- template: &str,
+pub fn approve_alias_commands(
+ commands: &worktrunk::config::CommandConfig,
alias_name: &str,
project_id: &str,
yes: bool,
) -> anyhow::Result<bool> {
let approvals = Approvals::load().context("Failed to load approvals")?;
- let cmd = ApprovableCommand {
- phase: Phase::Alias,
- command: worktrunk::config::Command::new(
- Some(alias_name.to_string()),
- template.to_string(),
- ),
- };
+ let cmds: Vec<_> = commands
+ .commands()
+ .iter()
+ .map(|cmd| ApprovableCommand {
+ phase: Phase::Alias,
+ command: worktrunk::config::Command::new(
+ Some(cmd.name.clone().unwrap_or_else(|| alias_name.to_string())),
+ cmd.template.clone(),
+ ),
+ })
+ .collect();
- approve_command_batch(&[cmd], project_id, &approvals, yes, false)
+ approve_command_batch(&cmds, project_id, &approvals, yes, false)
}
/// Collect project commands for hooks and request batch approval.
diff --git a/src/completion.rs b/src/completion.rs
index 06e8f33d9..3b494e44b 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::{ProjectConfig, UserConfig};
+use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};
use worktrunk::git::{BranchCategory, HookType, Repository};
/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`
@@ -389,7 +389,7 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
}
cmd.mut_subcommand("step", |mut step| {
- for (name, template) in aliases {
+ for (name, cmd_config) in aliases {
// Skip aliases that shadow built-in step commands
if step
.get_subcommands()
@@ -397,7 +397,13 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
{
continue;
}
- let help = truncate_template(&template);
+ // Use the first command's template for the help text
+ let first_template = cmd_config
+ .commands()
+ .first()
+ .map(|c| c.template.as_str())
+ .unwrap_or("");
+ let help = truncate_template(first_template);
// clap::Command::new() requires Into<Str>, and Str only implements
// From<&'static str> (not From<String>). Leak is fine: completion is
// a short-lived subprocess that exits after printing candidates.
@@ -420,7 +426,7 @@ fn inject_alias_subcommands(cmd: Command) -> Command {
}
/// Load aliases from user and project config for completion.
-fn load_aliases_for_completion() -> BTreeMap<String, String> {
+fn load_aliases_for_completion() -> BTreeMap<String, CommandConfig> {
let mut aliases = BTreeMap::new();
if let Ok(repo) = Repository::current() {
@@ -430,7 +436,7 @@ fn load_aliases_for_completion() -> BTreeMap<String, String> {
{
aliases.extend(project_aliases);
}
- // User config aliases override
+ // User config aliases replace on collision (trusted)
if let Ok(user_config) = UserConfig::load() {
let project_id = repo.project_identifier().ok();
aliases.extend(user_config.aliases(project_id.as_deref()));
diff --git a/src/config/commands.rs b/src/config/commands.rs
index 4bceee00b..cc7a0a73d 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -57,6 +57,13 @@ pub struct CommandConfig {
}
impl CommandConfig {
+ /// Create a config with a single unnamed command.
+ pub fn single(template: impl Into<String>) -> Self {
+ Self {
+ commands: vec![Command::new(None, template.into())],
+ }
+ }
+
/// Returns the commands as a slice
pub fn commands(&self) -> &[Command] {
&self.commands
diff --git a/src/config/project.rs b/src/config/project.rs
index 21a2a14ac..72228ee58 100644
--- a/src/config/project.rs
+++ b/src/config/project.rs
@@ -9,6 +9,7 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use super::HooksConfig;
+use super::commands::CommandConfig;
/// Project-level configuration for `wt list` output.
///
@@ -113,8 +114,8 @@ pub struct ProjectConfig {
/// \[experimental\] Command aliases for `wt step <name>`.
///
- /// Each alias maps a name to a command template. All hook template variables
- /// are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).
+ /// Each alias maps a name to one or more command templates. All hook
+ /// template variables are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).
///
/// ```toml
/// [aliases]
@@ -122,7 +123,7 @@ pub struct ProjectConfig {
/// lint = "npm run lint"
/// ```
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub aliases: Option<BTreeMap<String, String>>,
+ pub aliases: Option<BTreeMap<String, CommandConfig>>,
}
impl ProjectConfig {
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index ec32c7fdb..64e0211d8 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -6,6 +6,7 @@
use std::collections::{BTreeMap, HashMap};
use crate::config::HooksConfig;
+use crate::config::commands::CommandConfig;
use crate::config::expansion::expand_template;
use super::UserConfig;
@@ -198,14 +199,20 @@ impl UserConfig {
/// Returns effective aliases for a specific project.
///
- /// Merges global user aliases with per-project user aliases (per-project overrides on collision).
- pub fn aliases(&self, project: Option<&str>) -> BTreeMap<String, String> {
+ /// Merges global user aliases with per-project user aliases using append
+ /// semantics: both run on name collision (global first, then per-project).
+ pub fn aliases(&self, project: Option<&str>) -> BTreeMap<String, CommandConfig> {
let mut result = self.configs.aliases.clone().unwrap_or_default();
if let Some(proj_aliases) = project
.and_then(|p| self.projects.get(p))
.and_then(|proj| proj.overrides.aliases.as_ref())
{
- result.extend(proj_aliases.iter().map(|(k, v)| (k.clone(), v.clone())));
+ for (k, v) in proj_aliases {
+ result
+ .entry(k.clone())
+ .and_modify(|existing| *existing = existing.merge_append(v))
+ .or_insert_with(|| v.clone());
+ }
}
result
}
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 457ac5af5..ca07c7810 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -10,6 +10,7 @@ use serde::{Deserialize, Serialize};
use super::merge::Merge;
use crate::config::HooksConfig;
+use crate::config::commands::CommandConfig;
/// What to stage before committing
#[derive(
@@ -469,8 +470,11 @@ pub struct OverridableConfig {
/// \[experimental\] Command aliases for `wt step <name>`.
///
- /// Each alias maps a name to a command template. All hook template variables
- /// are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).
+ /// Each alias maps a name to one or more command templates. All hook
+ /// template variables are available (e.g., `{{ branch }}`, `{{ worktree_path }}`).
+ ///
+ /// Per-project aliases append to global aliases on name collision (global
+ /// first, then per-project), matching hook merge semantics.
///
/// ```toml
/// [aliases]
@@ -478,7 +482,7 @@ pub struct OverridableConfig {
/// lint = "npm run lint"
/// ```
#[serde(default, skip_serializing_if = "Option::is_none")]
- pub aliases: Option<BTreeMap<String, String>>,
+ pub aliases: Option<BTreeMap<String, CommandConfig>>,
}
impl OverridableConfig {
@@ -512,23 +516,31 @@ impl Merge for OverridableConfig {
merge: merge_optional(self.merge.as_ref(), other.merge.as_ref()),
switch: merge_optional(self.switch.as_ref(), other.switch.as_ref()),
select: merge_optional(self.select.as_ref(), other.select.as_ref()),
- aliases: merge_alias_maps(&self.aliases, &other.aliases),
+ aliases: merge_alias_maps(&self.aliases, &other.aliases), // Append semantics
}
}
}
-/// Merge two optional alias maps. Other's entries override base on collision.
+/// Merge two optional alias maps using append semantics.
+///
+/// Both base and other aliases run on name collision (base first, then other),
+/// matching how `HooksConfig::merge_with` appends hooks.
fn merge_alias_maps(
- base: &Option<BTreeMap<String, String>>,
- other: &Option<BTreeMap<String, String>>,
-) -> Option<BTreeMap<String, String>> {
+ base: &Option<BTreeMap<String, CommandConfig>>,
+ other: &Option<BTreeMap<String, CommandConfig>>,
+) -> Option<BTreeMap<String, CommandConfig>> {
match (base, other) {
(None, None) => None,
(Some(b), None) => Some(b.clone()),
(None, Some(o)) => Some(o.clone()),
(Some(b), Some(o)) => {
let mut merged = b.clone();
- merged.extend(o.iter().map(|(k, v)| (k.clone(), v.clone())));
+ for (k, v) in o {
+ merged
+ .entry(k.clone())
+ .and_modify(|existing| *existing = existing.merge_append(v))
+ .or_insert_with(|| v.clone());
+ }
Some(merged)
}
}
@@ -601,25 +613,35 @@ mod tests {
#[test]
fn test_merge_alias_maps_base_only() {
- let base = BTreeMap::from([("a".into(), "1".into())]);
+ let base = BTreeMap::from([("a".into(), CommandConfig::single("1"))]);
let result = merge_alias_maps(&Some(base.clone()), &None);
assert_eq!(result, Some(base));
}
#[test]
fn test_merge_alias_maps_other_only() {
- let other = BTreeMap::from([("b".into(), "2".into())]);
+ let other = BTreeMap::from([("b".into(), CommandConfig::single("2"))]);
let result = merge_alias_maps(&None, &Some(other.clone()));
assert_eq!(result, Some(other));
}
#[test]
- fn test_merge_alias_maps_other_overrides_base() {
- let base = BTreeMap::from([("a".into(), "1".into()), ("shared".into(), "base".into())]);
- let other = BTreeMap::from([("b".into(), "2".into()), ("shared".into(), "other".into())]);
+ fn test_merge_alias_maps_appends_on_collision() {
+ let base = BTreeMap::from([
+ ("a".into(), CommandConfig::single("1")),
+ ("shared".into(), CommandConfig::single("base-cmd")),
+ ]);
+ let other = BTreeMap::from([
+ ("b".into(), CommandConfig::single("2")),
+ ("shared".into(), CommandConfig::single("other-cmd")),
+ ]);
let result = merge_alias_maps(&Some(base), &Some(other)).unwrap();
- assert_eq!(result["a"], "1");
- assert_eq!(result["b"], "2");
- assert_eq!(result["shared"], "other");
+ assert_eq!(result["a"].commands().len(), 1);
+ assert_eq!(result["b"].commands().len(), 1);
+ // Collision: both commands are preserved (base first, then other)
+ let shared = &result["shared"];
+ assert_eq!(shared.commands().len(), 2);
+ assert_eq!(shared.commands()[0].template, "base-cmd");
+ assert_eq!(shared.commands()[1].template, "other-cmd");
}
}
diff --git a/src/config/user/tests.rs b/src/config/user/tests.rs
index 391c4d4c8..92cf8e955 100644
--- a/src/config/user/tests.rs
+++ b/src/config/user/tests.rs
@@ -2393,6 +2393,42 @@ fn test_hooks_merge_post_create_both_sides() {
assert_eq!(commands[1].template, "cargo build");
}
+#[test]
+fn test_aliases_accessor_appends_on_collision() {
+ let toml_str = r#"
+[aliases]
+shared = "global-cmd"
+global-only = "only-global"
+
+[projects."test-project".aliases]
+shared = "project-cmd"
+project-only = "only-project"
+"#;
+ let config: UserConfig = toml::from_str(toml_str).unwrap();
+
+ let aliases = config.aliases(Some("test-project"));
+
+ // Non-colliding aliases are present
+ assert_eq!(aliases["global-only"].commands().len(), 1);
+ assert_eq!(aliases["global-only"].commands()[0].template, "only-global");
+ assert_eq!(aliases["project-only"].commands().len(), 1);
+ assert_eq!(
+ aliases["project-only"].commands()[0].template,
+ "only-project"
+ );
+
+ // Colliding alias: both commands run (global first, then per-project)
+ let shared = &aliases["shared"];
+ assert_eq!(shared.commands().len(), 2);
+ assert_eq!(shared.commands()[0].template, "global-cmd");
+ assert_eq!(shared.commands()[1].template, "project-cmd");
+
+ // Without project: only global aliases
+ let global_only = config.aliases(None);
+ assert_eq!(global_only["shared"].commands().len(), 1);
+ assert_eq!(global_only["shared"].commands()[0].template, "global-cmd");
+}
+
/// Test that reload_projects_from handles permission errors
/// when the config file exists but cannot be read.
#[cfg(unix)]
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index 8a7f1216a..8ee37bc52 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -199,7 +199,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  #
  # #### Setting overrides [experimental]
  #
-  # Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks append — both global and per-project hooks run. Aliases merge — per-project aliases override global aliases on name collision.
+  # Override global user config for a specific project. Scalar values (like `worktree-path`) replace the global value. Hooks and aliases append — both global and per-project versions run (global first).
  #
  # [projects."github.com/user/repo"]
  # worktree-path = ".worktrees/{{ branch | sanitize }}"
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 3157e3389..02aa2707a 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -244,7 +244,7 @@ Entries are keyed by project identifier (e.g., github.com/user/repo).
Setting overrides [experimental]
-Override global user config for a specific project. Scalar values (like worktree-path) replace the global value. Hooks append — both global and per-project hooks run. Aliases merge — per-project aliases override global aliases on name collision.
+Override global user config for a specific project. Scalar values (like worktree-path) replace the global value. Hooks and aliases append — both global and per-project versions run (global first).
  [projects."github.com/user/repo"]
  worktree-path = ".worktrees/{{ branch | sanitize }}"