Skip to content

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

refactor(config): stop supplying the deprecated template variables, migrating them on load (#4080)

Worktrunk Botb1e0871bef26
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index b77df4b86..e6cf653bf 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -278,12 +278,8 @@ pub fn build_hook_context(
map.insert("branch".into(), branch.into());
}
map.insert("worktree_name".into(), worktree_name.into());
- map.insert("repo_path".into(), repo_path.clone());
- map.insert("worktree_path".into(), worktree.clone());
- // Deprecated aliases (kept for backward compatibility)
- map.insert("main_worktree".into(), repo_name.into());
- map.insert("repo_root".into(), repo_path);
- map.insert("worktree".into(), worktree);
+ map.insert("repo_path".into(), repo_path);
+ map.insert("worktree_path".into(), worktree);
if let Some(parsed_remote) = ctx.repo.primary_remote_parsed_url() {
map.insert("owner".into(), parsed_remote.owner().to_string());
@@ -299,17 +295,13 @@ pub fn build_hook_context(
}
// Primary worktree path (where established files live)
- if scope.wants("primary_worktree_path") || scope.wants("main_worktree_path") {
+ if scope.wants("primary_worktree_path") {
let _span = Span::new("var_primary_worktree");
if let Ok(Some(path)) = ctx.repo.primary_worktree() {
- let path_str = to_posix_path(&path.to_string_lossy());
- if scope.wants("primary_worktree_path") {
- map.insert("primary_worktree_path".into(), path_str.clone());
- }
- // Deprecated alias
- if scope.wants("main_worktree_path") {
- map.insert("main_worktree_path".into(), path_str);
- }
+ map.insert(
+ "primary_worktree_path".into(),
+ to_posix_path(&path.to_string_lossy()),
+ );
}
}
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index a77c7bbc7..50e5836c8 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -1639,7 +1639,7 @@ pub fn handle_show_theme() {
eprintln!(
"{}",
format_bash_with_gutter(
- "eval \"$(wt config shell init bash)\"\necho 'This is a long command that will wrap to the next line when the terminal is narrow enough to require wrapping.'\necho 'hello\nworld'\ncargo build --release &&\ncargo test\ncp {{ repo_root }}/target {{ worktree }}/target"
+ "eval \"$(wt config shell init bash)\"\necho 'This is a long command that will wrap to the next line when the terminal is narrow enough to require wrapping.'\necho 'hello\nworld'\ncargo build --release &&\ncargo test\ncp {{ repo_path }}/target {{ worktree_path }}/target"
)
);
diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rs
index 6feedcff8..00636f8fc 100644
--- a/src/commands/worktree/resolve.rs
+++ b/src/commands/worktree/resolve.rs
@@ -117,10 +117,12 @@ pub fn worktree_display_name(
/// Uses an absolute path (`repo_path`/../) to avoid ambiguity with relative resolution.
const BARE_REPO_WORKTREE_PATH: &str = "{{ repo_path }}/../{{ branch | sanitize }}";
-/// Check whether a template string references `{{ repo }}` or `{{ main_worktree }}`.
+/// Check whether a template string references `{{ repo }}`.
+///
+/// The template comes from the loaded config, so the deprecation layer has
+/// already renamed the retired `main_worktree` to `repo` before it gets here.
fn template_references_repo_name(template: &str) -> bool {
worktrunk::config::template_references_var(template, "repo")
- || worktrunk::config::template_references_var(template, "main_worktree")
}
/// Offer to set a project-level `worktree-path` for bare repos with hidden directory names.
@@ -281,11 +283,6 @@ mod tests {
true,
),
("repo with filter", "{{ repo | sanitize }}", true),
- (
- "deprecated main_worktree alias",
- "{{ main_worktree }}.{{ branch }}",
- true,
- ),
(
"repo_path is a distinct variable",
"{{ repo_path }}/../{{ branch | sanitize }}",
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 9a0b09066..8b09eb160 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -97,16 +97,33 @@ pub fn warnings_suppressed() -> bool {
static WARNED_UNKNOWN_PATHS: LazyLock<Mutex<HashSet<PathBuf>>> =
LazyLock::new(|| Mutex::new(HashSet::new()));
-/// Mapping from deprecated variable name to its replacement
-const DEPRECATED_VARS: &[(&str, &str)] = &[
+/// Retired template variables, mapped to their replacement. No renderer
+/// supplies the old name any more, so the rewrite is
+/// [`DeprecationRule::Structural`]: it applies on every load, before serde
+/// parses, and is what keeps an unmigrated template rendering what it always
+/// did. The warning still fires and still points at `wt config update`, which
+/// writes the rename into the user's file.
+///
+/// Every row is a mechanical identifier swap — the replacement resolves to the
+/// same value the old name did — which is what makes rewriting the in-memory
+/// config on every load safe. `commits` is squash-template-only, and each
+/// `commit_details` element renders as its subject when printed bare, so a
+/// migrated `{% for c in commit_details %}{{ c }}` reads identically to the old
+/// `{% for c in commits %}{{ c }}` (see #2984 and `CommitDetailValue`).
+///
+/// The rewrite happens at load, not on request, because an old name that
+/// reached a renderer would fail differently depending on where it sat. A
+/// hook, alias, or `worktree-path` template would fail its `SemiStrict`
+/// expansion with an undefined-variable error — loud, and fixable from the
+/// message. A squash template would render nothing at all: `build_prompt`
+/// renders under minijinja's default `UndefinedBehavior::Lenient`, which
+/// iterates an undefined value as an empty sequence, so the prompt would lose
+/// its commit list silently — the outcome #2984 opens by calling out.
+const RETIRED_VARS: &[(&str, &str)] = &[
("repo_root", "repo_path"),
("worktree", "worktree_path"),
("main_worktree", "repo"),
("main_worktree_path", "primary_worktree_path"),
- // Squash-template-only. The rename is a safe mechanical rewrite because each
- // `commit_details` element renders as its subject when printed bare, so a
- // migrated `{% for c in commit_details %}{{ c }}` reads identically to the
- // old `{% for c in commits %}{{ c }}` (see #2984 and `CommitDetailValue`).
("commits", "commit_details"),
];
@@ -165,17 +182,17 @@ pub fn normalize_template_vars(template: &str) -> Cow<'_, str> {
.unwrap_or(Cow::Borrowed(template))
}
-/// The deprecated `(old, new)` pairs used as variables in `template`, in
-/// [`DEPRECATED_VARS`] order. Empty when none appear (or the template doesn't
+/// The retired `(old, new)` pairs used as variables in `template`, in
+/// [`RETIRED_VARS`] order. Empty when none appear (or the template doesn't
/// parse). An identifier appearing only as an attribute name
/// (`{{ foo.repo_root }}`) or an assignment target doesn't count — only
/// genuine variable uses, which is exactly what the rewrite replaces.
+///
+/// Detection and migration share this one predicate: the rule rewrites what
+/// this reports, so the two cannot drift.
fn deprecated_vars_in_template(template: &str) -> Vec<(&'static str, &'static str)> {
- // Quick check: if none of the deprecated vars appear, skip parsing
- if !DEPRECATED_VARS
- .iter()
- .any(|(old, _)| template.contains(old))
- {
+ // Quick check: if none of the retired vars appear, skip parsing
+ if !RETIRED_VARS.iter().any(|(old, _)| template.contains(old)) {
return Vec::new();
}
@@ -184,7 +201,7 @@ fn deprecated_vars_in_template(template: &str) -> Vec<(&'static str, &'static st
return Vec::new();
};
let used_vars = parsed.undeclared_variables(false);
- DEPRECATED_VARS
+ RETIRED_VARS
.iter()
.copied()
.filter(|(old, _)| used_vars.contains(*old))
@@ -365,10 +382,10 @@ fn is_template_identifier_char(ch: char) -> bool {
ch == '_' || ch.is_ascii_alphanumeric()
}
-/// Replace deprecated template vars in every string value of the document,
-/// mutating the `toml_edit` tree in place; returns one
+/// Replace every [`RETIRED_VARS`] template variable in every string value of
+/// the document, mutating the `toml_edit` tree in place; returns one
/// [`DeprecationKind::TemplateVar`] per `(old, new)` pair replaced, in
-/// [`DEPRECATED_VARS`] order.
+/// [`RETIRED_VARS`] order.
///
/// Operating on the parsed tree (rather than a raw `str::replace` against the
/// file text) is correct when the TOML source uses escapes: the decoded value
@@ -426,7 +443,7 @@ fn migrate_template_vars_doc(doc: &mut toml_edit::DocumentMut) -> Deprecations {
let mut replaced = Replaced::new();
walk_table(doc.as_table_mut(), &mut replaced);
- DEPRECATED_VARS
+ RETIRED_VARS
.iter()
.filter(|pair| replaced.contains(*pair))
.map(|&(old, new)| DeprecationKind::TemplateVar { old, new })
@@ -524,11 +541,13 @@ type SilentMigrateFn = fn(&mut toml_edit::DocumentMut) -> bool;
enum DeprecationRule {
/// Warns, and is rewritten on every config load before serde parses.
Structural(MigrateFn),
- /// Warns, but the deprecated form still works at runtime (deprecated
- /// template variables resolve via [`normalize_template_vars`];
- /// `approved-commands` is still a valid serde field), so the load path
+ /// Warns, but the deprecated form still works at runtime
+ /// (`approved-commands` is still a valid serde field), so the load path
/// leaves it alone. Rewritten only via [`compute_migrated_content`]
- /// (`wt config show` / `wt config update`).
+ /// (`wt config show` / `wt config update`). A template variable nothing
+ /// supplies any more belongs in [`RETIRED_VARS`], which is rewritten
+ /// structurally instead — an unmigrated name would otherwise reach a
+ /// renderer that has nothing to resolve it to.
UpdateOnly(MigrateFn),
/// Silently-migrated rename: rewritten on every load like `Structural`,
/// but with no warning by construction.
@@ -563,9 +582,10 @@ enum RulePass {
/// A [`DeprecationRule::Structural`] rule must not depend on an `UpdateOnly`
/// rewrite preceding it: the load path skips `UpdateOnly` rules while
/// detection applies them, so such a dependency would make the load-path
-/// rewrite diverge from what was warned. The current `UpdateOnly` rules
-/// rewrite key spaces no other rule reads (template strings and
-/// `approved-commands`).
+/// rewrite diverge from what was warned. No rule here has such a dependency —
+/// the template-variable row reads and writes a key space
+/// (`{{ … }}` identifiers inside string values) that no other rule touches,
+/// and `approved-commands` is read by no other rule.
///
/// A rule that moves a section's table wholesale into a new location must
/// remove the keys its destination has no field for, reporting each via
@@ -581,9 +601,12 @@ enum RulePass {
/// section). A silently-migrated rename is just a [`DeprecationRule::Silent`]
/// row.
const DEPRECATION_RULES: &[DeprecationRule] = &[
- // Template variables: {{ repo_root }} → {{ repo_path }} etc., inside any
- // string value.
- DeprecationRule::UpdateOnly(migrate_template_vars_doc),
+ // Retired template variables: {{ repo_root }} → {{ repo_path }},
+ // {{ commits }} → {{ commit_details }}, etc., inside any string value.
+ // Structural because no renderer supplies any of these names any more —
+ // the load-path rewrite is what keeps an unmigrated template rendering
+ // what it always did.
+ DeprecationRule::Structural(migrate_template_vars_doc),
// [commit-generation] → [commit.generation], top-level and per-project.
DeprecationRule::Structural(migrate_commit_generation_doc),
// approved-commands under [projects."..."] → approvals.toml. The rule only
@@ -2225,6 +2248,39 @@ post-start = "ln -sf {{ repo_root }}/node_modules {{ worktree }}/node_modules"
);
}
+ /// Every retired variable is rewritten on load, not just by
+ /// `wt config update`: nothing supplies the old names at render time, so a
+ /// template that reached a renderer un-rewritten would fail its expansion
+ /// (`worktree-path`) or render nothing (`squash-template`). Detection
+ /// reports the same pairs either way.
+ #[test]
+ fn test_retired_vars_migrate_on_load_and_on_update() {
+ let content = r#"worktree-path = "../{{ repo_root }}.{{ branch }}"
+
+[commit.generation]
+squash-template = "{% for c in commits %}{{ c }}\n{% endfor %}"
+"#;
+ assert_eq!(
+ find_deprecated_vars(content),
+ vec![("repo_root", "repo_path"), ("commits", "commit_details")]
+ );
+
+ for (label, migrated) in [
+ ("load", migrate_content(content)),
+ ("update", compute_migrated_content(content)),
+ ] {
+ assert!(
+ migrated.contains("{{ repo_path }}")
+ && migrated.contains("for c in commit_details"),
+ "{label} must rewrite both retired vars: {migrated}"
+ );
+ assert!(
+ !migrated.contains("repo_root") && !migrated.contains("in commits"),
+ "{label} must leave no retired var behind: {migrated}"
+ );
+ }
+ }
+
#[test]
fn test_find_deprecated_vars_with_filter() {
let content = r#"
@@ -3455,6 +3511,16 @@ hostname = "forge.example"
"switch = \"x\"\n\n[select]\nheight = \"50%\"\n",
// empty approved-commands is not deprecated
"[projects.\"github.com/u/r\"]\napproved-commands = []\n",
+ // Live variables whose names merely contain a retired one. The
+ // rewrite matches whole identifiers, and it now runs on every
+ // load, so a substring match here would mangle a current variable
+ // in every user's config on every command — `worktree` inside
+ // `worktree_path`, `main_worktree` inside `main_worktree_path`
+ // (itself retired, to a different name), `commits` inside
+ // `recent_commits`
+ "[commit.generation]\nsquash-template = \"{{ recent_commits | length }}\"\n",
+ "worktree-path = \"{{ worktree_path }}\"\n",
+ "post-start = \"ln -sf {{ primary_worktree_path }}/node_modules .\"\n",
];
for content in untouched {
assert!(
@@ -3492,7 +3558,14 @@ hostname = "forge.example"
// list.task-timeout-ms, section and inline forms
"[projects.\"github.com/u/r\".list]\ntask-timeout-ms = 500\n",
"[projects.\"github.com/u/r\"]\nlist = { task-timeout-ms = 500 }\n",
+ // Retired template variables, rewritten on load as well as by
+ // update. `main_worktree_path` is the near-miss of the row above
+ // it in the table and must reach its own replacement.
"worktree-path = \"../{{ repo_root }}.{{ branch }}\"\n",
+ "worktree-path = \"../{{ main_worktree }}.{{ branch }}\"\n",
+ "post-start = \"ln -sf {{ main_worktree_path }}/node_modules .\"\n",
+ "post-start = \"cp {{ worktree }}/.env .\"\n",
+ "[commit.generation]\nsquash-template = \"{{ commits | length }}\"\n",
"[projects.\"github.com/u/r\"]\napproved-commands = [\"npm test\"]\n",
];
for content in rewritten {
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 0843909e8..898634e1c 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -85,20 +85,6 @@ pub fn base_vars() -> Vec<&'static str> {
/// indexing, iteration, and `length` behave like a sequence.
pub const ALIAS_ARGS_KEY: &str = "args";
-/// Deprecated template variable aliases (still valid for backward compatibility).
-///
-/// These map to current variables and are available in every scope:
-/// - `main_worktree` → `repo`
-/// - `repo_root` → `repo_path`
-/// - `worktree` → `worktree_path`
-/// - `main_worktree_path` → `primary_worktree_path`
-pub const DEPRECATED_TEMPLATE_VARS: &[&str] = &[
- "main_worktree",
- "repo_root",
- "worktree",
- "main_worktree_path",
-];
-
/// Variables available in `wt list` custom-column templates (plus `vars.*`).
///
/// Deliberately narrower than [`base_vars`]: column values are computed per
@@ -275,9 +261,13 @@ const HOOK_INFRASTRUCTURE_VARS: &[&str] = &["hook_type", "hook_name"];
/// All template variables available in a given scope.
///
-/// The returned list is [`base_vars`] + scope-specific extras + deprecated
-/// aliases. Used by [`validate_template`] to build the placeholder context
-/// and by error messages to list what the user could have typed.
+/// The returned list is [`base_vars`] + scope-specific extras. Used by
+/// [`validate_template`] to build the placeholder context and by error
+/// messages to list what the user could have typed. Retired names
+/// (`repo_root`, `worktree`, …) are absent: the deprecation layer renames them
+/// before serde parses the config, so a template reaching here carries only
+/// current names, and one typed on the command line gets the undefined-variable
+/// error with this list attached.
pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {
let mut vars: Vec<&'static str> = base_vars();
match scope {
@@ -293,7 +283,6 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {
vars.push(ALIAS_ARGS_KEY);
}
}
- vars.extend(DEPRECATED_TEMPLATE_VARS);
vars
}
@@ -2976,8 +2965,10 @@ mod tests {
.is_ok()
);
- // Deprecated vars still valid in every scope
- assert!(validate_template("{{ main_worktree }}", hook, &test.repo, "test").is_ok());
+ // Retired names resolve nowhere: the deprecation layer renames them
+ // before serde parses, so one reaching validation was typed on the
+ // command line and gets the undefined-variable error.
+ assert!(validate_template("{{ main_worktree }}", hook, &test.repo, "test").is_err());
// `args` validates in both Hook and Alias scopes.
assert!(validate_template("echo {{ args }}", hook, &test.repo, "test").is_ok());
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 5f7d215da..5fa1dfc18 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -178,12 +178,11 @@ pub use deprecation::{
};
pub use deprecation::{DeprecationKind, Deprecations};
pub use expansion::{
- ACTIVE_VARS, ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, EXEC_BASE_VARS, REPO_VARS,
- TemplateContext, TemplateExpandError, ValidationScope, VarScope, VarsMode,
- alias_context_filter, base_vars, expand_template, format_alias_variables,
- format_base_variables, format_hook_variables, redact_credentials, referenced_vars_for_config,
- referenced_vars_for_templates, sanitize_branch_name, sanitize_db, short_hash,
- template_environment, template_references_var, validate_list_column_template,
+ ACTIVE_VARS, ALIAS_ARGS_KEY, EXEC_BASE_VARS, REPO_VARS, TemplateContext, TemplateExpandError,
+ ValidationScope, VarScope, VarsMode, alias_context_filter, base_vars, expand_template,
+ format_alias_variables, format_base_variables, format_hook_variables, redact_credentials,
+ referenced_vars_for_config, referenced_vars_for_templates, sanitize_branch_name, sanitize_db,
+ short_hash, template_environment, template_references_var, validate_list_column_template,
validate_template, validate_template_syntax, vars_available_in, vars_map_to_value,
};
pub use hooks::HooksConfig;
@@ -249,7 +248,7 @@ mod tests {
fn test_format_worktree_path() {
let test = test_repo();
let config = UserConfig {
- worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),
+ worktree_path: Some("{{ repo }}.{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -264,7 +263,7 @@ mod tests {
fn test_format_worktree_path_custom_template() {
let test = test_repo();
let config = UserConfig {
- worktree_path: Some("{{ main_worktree }}-{{ branch }}".to_string()),
+ worktree_path: Some("{{ repo }}-{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -279,7 +278,7 @@ mod tests {
fn test_format_worktree_path_only_branch() {
let test = test_repo();
let config = UserConfig {
- worktree_path: Some(".worktrees/{{ main_worktree }}/{{ branch }}".to_string()),
+ worktree_path: Some(".worktrees/{{ repo }}/{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -295,7 +294,7 @@ mod tests {
let test = test_repo();
// Use {{ branch | sanitize }} to replace slashes with dashes
let config = UserConfig {
- worktree_path: Some("{{ main_worktree }}.{{ branch | sanitize }}".to_string()),
+ worktree_path: Some("{{ repo }}.{{ branch | sanitize }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -310,9 +309,7 @@ mod tests {
fn test_format_worktree_path_with_multiple_slashes() {
let test = test_repo();
let config = UserConfig {
- worktree_path: Some(
- ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
- ),
+ worktree_path: Some(".worktrees/{{ repo }}/{{ branch | sanitize }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -328,9 +325,7 @@ mod tests {
let test = test_repo();
// Windows-style path separators should also be sanitized
let config = UserConfig {
- worktree_path: Some(
- ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}".to_string(),
- ),
+ worktree_path: Some(".worktrees/{{ repo }}/{{ branch | sanitize }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -346,7 +341,7 @@ mod tests {
let test = test_repo();
// {{ branch }} without filter gives raw branch name
let config = UserConfig {
- worktree_path: Some("{{ main_worktree }}.{{ branch }}".to_string()),
+ worktree_path: Some("{{ repo }}.{{ branch }}".to_string()),
..Default::default()
};
assert_eq!(
@@ -520,10 +515,10 @@ task2 = "echo 'Task 2 running' > task2.txt"
let test = test_repo();
let mut vars = HashMap::new();
- vars.insert("main_worktree", "myrepo");
+ vars.insert("repo", "myrepo");
vars.insert("branch", "feature-x");
let result = expand_template(
- "../{{ main_worktree }}.{{ branch }}",
+ "../{{ repo }}.{{ branch }}",
&vars,
ShellEscapeMode::Posix,
&test.repo,
@@ -542,10 +537,10 @@ task2 = "echo 'Task 2 running' > task2.txt"
// Use {{ branch | sanitize }} filter for filesystem-safe paths
// shell_escape=false to test filter in isolation (shell escaping tested separately)
let mut vars = HashMap::new();
- vars.insert("main_worktree", "myrepo");
+ vars.insert("repo", "myrepo");
vars.insert("branch", "feature/foo");
let result = expand_template(
- "{{ main_worktree }}/{{ branch | sanitize }}",
+ "{{ repo }}/{{ branch | sanitize }}",
&vars,
ShellEscapeMode::Literal,
&test.repo,
@@ -555,10 +550,10 @@ task2 = "echo 'Task 2 running' > task2.txt"
assert_eq!(result, "myrepo/feature-foo");
let mut vars = HashMap::new();
- vars.insert("main_worktree", "myrepo");
+ vars.insert("repo", "myrepo");
vars.insert("branch", r"feat\bar");
let result = expand_template(
- ".worktrees/{{ main_worktree }}/{{ branch | sanitize }}",
+ ".worktrees/{{ repo }}/{{ branch | sanitize }}",
&vars,
ShellEscapeMode::Literal,
&test.repo,
@@ -573,11 +568,11 @@ task2 = "echo 'Task 2 running' > task2.txt"
use std::collections::HashMap;
let mut vars = HashMap::new();
- vars.insert("worktree", "/path/to/worktree");
- vars.insert("repo_root", "/path/to/repo");
+ vars.insert("worktree_path", "/path/to/worktree");
+ vars.insert("repo_path", "/path/to/repo");
let result = expand_template(
- "{{ repo_root }}/target -> {{ worktree }}/target",
+ "{{ repo_path }}/target -> {{ worktree_path }}/target",
&vars,
ShellEscapeMode::Posix,
&test_repo().repo,
@@ -674,7 +669,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
#[test]
fn test_user_hooks_config_parsing() {
let toml_str = r#"
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ repo }}.{{ branch }}"
[post-start]
log = "echo '{{ repo }}' >> ~/.log"
@@ -705,7 +700,7 @@ lint = "cargo clippy"
#[test]
fn test_user_hooks_config_single_command() {
let toml_str = r#"
-worktree-path = "../{{ main_worktree }}.{{ branch }}"
+worktree-path = "../{{ repo }}.{{ branch }}"
post-start = "npm install"
"#;
let config: UserConfig = toml::from_str(toml_str).unwrap();
diff --git a/src/config/user/accessors.rs b/src/config/user/accessors.rs
index bbb828b67..c83f6e354 100644
--- a/src/config/user/accessors.rs
+++ b/src/config/user/accessors.rs
@@ -255,7 +255,6 @@ impl UserConfig {
// Use native path format (not POSIX) since this is used for filesystem operations
let repo_path = repo.repo_path()?.to_string_lossy().to_string();
let mut vars = HashMap::new();
- vars.insert("main_worktree", main_worktree);
vars.insert("repo", main_worktree);
vars.insert("branch", branch);
vars.insert("repo_path", repo_path.as_str());
diff --git a/src/config/user/sections.rs b/src/config/user/sections.rs
index 93561287e..5a615e4e0 100644
--- a/src/config/user/sections.rs
+++ b/src/config/user/sections.rs
@@ -68,7 +68,7 @@ pub struct CommitGenerationConfig {
pub template: Option<String>,
/// Inline template for squash commit message prompt
- /// Available variables: {{ commits }}, {{ target_branch }}, {{ branch }}, {{ repo }}
+ /// Available variables: {{ commit_details }}, {{ target_branch }}, {{ branch }}, {{ repo }}
#[serde(default, rename = "squash-template")]
pub squash_template: Option<String>,
diff --git a/src/llm.rs b/src/llm.rs
index 1d27cc4ed..cda6d3f4f 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -16,10 +16,12 @@ use minijinja::value::{Enumerator, Object, Value};
///
/// It renders as its bare subject (`{{ detail }}` yields the subject line) so a
/// template that iterates the list and prints the loop variable directly
-/// behaves exactly like the deprecated `commits` list of subject strings. That
-/// equivalence is what lets `wt config update` migrate a `commits` template to
-/// `commit_details` as a plain identifier rename — no shape-changing hand edits
-/// (see #2984). The `.subject` and `.body` properties remain available for
+/// behaves exactly like the retired `commits` list of subject strings. That
+/// equivalence is what lets the deprecation layer rewrite a `commits` template
+/// to `commit_details` as a plain identifier rename — on every load, and in the
+/// file itself via `wt config update` — with no shape-changing hand edits (see
+/// #2984 and `RETIRED_VARS`). The `.subject` and `.body` properties remain
+/// available for
/// templates that want the structured form, and because minijinja coerces an
/// object to a string via its `render`, string filters (`{{ c | upper }}`)
/// operate on the subject too.
@@ -584,9 +586,11 @@ enum TemplateType {
/// subject when printed bare and exposes `.subject` / `.body` properties.
/// Capped at [`MAX_SQUASH_COMMITS`]; the older tail is represented by one
/// synthetic "(N earlier commits omitted)" entry.
-/// - `commits`: Commit subjects being squashed (deprecated — see #2984;
-/// `wt config update` rewrites it to `commit_details`)
/// - `target_branch`: Target branch for merge
+///
+/// The retired `commits` variable is not supplied: the deprecation layer
+/// rewrites it to `commit_details` before serde parses the config, so an
+/// unmigrated template still renders its commit list (see `RETIRED_VARS`).
fn build_prompt(
config: &CommitGenerationConfig,
template_type: TemplateType,
@@ -621,15 +625,14 @@ fn build_prompt(
// Reverse commits so they're in chronological order (oldest first).
//
- // `commits` (a list of bare subject strings) is deprecated in favor of
- // `commit_details` (see #2984). The deprecation warning and the
- // `wt config update` rewrite both go through the standard config
- // deprecation framework (`DEPRECATED_VARS`), so nothing is detected or
- // warned here — `commits` is simply still rendered for templates that
- // haven't migrated yet. The rename is safe because each `commit_details`
- // element renders as its subject (see `CommitDetailValue`), so a migrated
- // `{% for c in commit_details %}{{ c }}` reads identically to the old
- // `{% for c in commits %}{{ c }}`.
+ // `commit_details` is the only commit list supplied. The retired `commits`
+ // variable (a list of bare subject strings) is handled entirely by the
+ // config deprecation layer (`RETIRED_VARS`), which rewrites it to
+ // `commit_details` on every load and warns, so an unmigrated template
+ // arrives here already renamed — nothing is detected or warned here. The
+ // rename is safe because each `commit_details` element renders as its
+ // subject (see `CommitDetailValue`), so `{% for c in commit_details %}{{ c
+ // }}` reads identically to the old `{% for c in commits %}{{ c }}`.
//
// The list is capped at `MAX_SQUASH_COMMITS` — the one prompt input the
// diff budget doesn't bound. Details arrive newest-first, so the newest
@@ -648,10 +651,6 @@ fn build_prompt(
.iter()
.chain(kept_details.iter().rev())
.collect();
- let commits_chronological: Vec<&String> = details_chronological
- .iter()
- .map(|detail| &detail.subject)
- .collect();
let commit_details_chronological: Vec<Value> = details_chronological
.iter()
.map(|detail| {
@@ -680,7 +679,6 @@ fn build_prompt(
branch => context.branch,
recent_commits => context.recent_commits.unwrap_or(&empty_commits),
repo => context.repo_name,
- commits => &commits_chronological,
commit_details => &commit_details_chronological,
target_branch => context.target_branch.unwrap_or(""),
})?)
@@ -705,7 +703,6 @@ fn build_prompt(
branch => context.branch,
recent_commits => context.recent_commits.unwrap_or(&empty_commits),
repo => context.repo_name,
- commits => commits_chronological,
commit_details => commit_details_chronological,
target_branch => context.target_branch.unwrap_or(""),
user_guidance => user_guidance,
@@ -1131,8 +1128,9 @@ mod tests {
/// A `commit_details` element renders as its bare subject and exposes
/// `.subject` / `.body`. This is the equivalence that lets the
- /// `commits` → `commit_details` rename be a mechanical identifier rewrite
- /// (see #2984 and `CommitDetailValue`).
+ /// `commits` → `commit_details` rename be a mechanical identifier rewrite,
+ /// which is what the config deprecation layer applies on every load now
+ /// that nothing supplies `commits` (see #2984 and `CommitDetailValue`).
#[test]
fn test_commit_detail_value_render_and_properties() {
assert_eq!(render_with_detail("{{ c }}", "Add a", "body a"), "Add a");
@@ -1630,7 +1628,7 @@ mod tests {
command: None,
template: None,
squash_template: Some(
- "Target: {{ target_branch }}\n{% for c in commits %}{{ c }}\n{% endfor %}"
+ "Target: {{ target_branch }}\n{% for c in commit_details %}{{ c }}\n{% endfor %}"
.to_string(),
),
template_append: None,
@@ -1699,7 +1697,7 @@ mod tests {
let config = CommitGenerationConfig {
command: None,
template: None,
- squash_template: Some("{% for x in commits %}{{ x }".to_string()),
+ squash_template: Some("{% for x in commit_details %}{{ x }".to_string()),
template_append: None,
};
let commit_details = vec![];
@@ -1729,7 +1727,7 @@ mod tests {
command: None,
template: None,
squash_template: Some(
- "Repo: {{ repo }}\nBranch: {{ branch }}\nTarget: {{ target_branch }}\nDiff: {{ git_diff }}\n{% for c in commits %}{{ c }}\n{% endfor %}{% for r in recent_commits %}style: {{ r }}\n{% endfor %}"
+ "Repo: {{ repo }}\nBranch: {{ branch }}\nTarget: {{ target_branch }}\nDiff: {{ git_diff }}\n{% for c in commit_details %}{{ c }}\n{% endfor %}{% for r in recent_commits %}style: {{ r }}\n{% endfor %}"
.to_string(),
),
template_append: None,
@@ -1827,14 +1825,14 @@ Diff follows:
command: None,
template: None,
squash_template: Some(
- r#"Squashing {{ commits | length }} commit(s) from {{ branch }} to {{ target_branch }}
-{% if commits | length > 1 -%}
+ r#"Squashing {{ commit_details | length }} commit(s) from {{ branch }} to {{ target_branch }}
+{% if commit_details | length > 1 -%}
Multiple commits detected:
-{%- for c in commits %}
+{%- for c in commit_details %}
{{ loop.index }}/{{ loop.length }}: {{ c }}
{%- endfor %}
{%- else -%}
-Single commit: {{ commits[0] }}
+Single commit: {{ commit_details[0] }}
{%- endif %}"#
.to_string(),
),
@@ -1886,7 +1884,7 @@ Single commit: {{ commits[0] }}
let config = CommitGenerationConfig {
command: None,
template: Some(
- "Branch: {{ branch }}\nTarget: {{ target_branch }}\nCommit subjects: {{ commits | length }}\nCommit details: {{ commit_details | length }}"
+ "Branch: {{ branch }}\nTarget: {{ target_branch }}\nCommit details: {{ commit_details | length }}"
.to_string(),
),
squash_template: None,
@@ -1897,10 +1895,7 @@ Single commit: {{ commits[0] }}
assert!(result.is_ok());
let prompt = result.unwrap();
// Squash-specific variables are empty for regular commits
- assert_eq!(
- prompt,
- "Branch: feature\nTarget: \nCommit subjects: 0\nCommit details: 0"
- );
+ assert_eq!(prompt, "Branch: feature\nTarget: \nCommit details: 0");
}
// Tests for diff filtering
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index b3dd4e2b3..ef9535f3f 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -247,7 +247,7 @@ fn test_saving_config_mutation_preserves_toml_comments() {
let initial_content = r#"# User preferences for worktrunk
# These comments should be preserved after saving
-worktree-path = "../{{ main_worktree }}.{{ branch }}" # inline comment should also be preserved
+worktree-path = "../{{ repo }}.{{ branch }}" # inline comment should also be preserved
# LLM commit generation settings
[commit.generation]
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index b1c4f7790..32d67c34d 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -2072,9 +2072,12 @@ fn test_deprecated_project_config_silent_in_linked_worktree(
.iter()
.find(|hook| hook["source"] == "project" && hook["type"] == "pre-start")
.expect("linked-worktree project hook should be listed");
+ // The linked-worktree gate silences the warning, not the migration: the
+ // retired name is rewritten before serde parses, here as everywhere, since
+ // nothing would resolve it at render time.
assert_eq!(
project_hook["template"],
- "echo linked-project-hook {{ main_worktree }}"
+ "echo linked-project-hook {{ repo }}"
);
assert!(
!(stderr.contains("Project config")
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index ce70ddbc4..51cc37d9e 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -3035,11 +3035,14 @@ squash-template = """
));
}
-/// A custom squash template that references the deprecated `commits` variable
-/// still renders, and the standard config-deprecation framework warns that it
-/// is replaced by `commit_details` and points at `wt config update` to apply
-/// the rewrite (see #2984). The rename is mechanical because each
-/// `commit_details` element renders as its subject when printed bare.
+/// A custom squash template that references the retired `commits` variable
+/// still renders, even though the prompt renderer no longer supplies that name:
+/// the config-deprecation layer rewrites it to `commit_details` on load, warns
+/// that it is replaced, and points at `wt config update` to write the rename
+/// into the file (see #2984 and `RETIRED_VARS`). The rename is mechanical
+/// because each `commit_details` element renders as its subject when printed
+/// bare — which is why the rendered count below is the real commit count and
+/// not the zero an undefined variable would produce.
#[rstest]
fn test_step_squash_show_prompt_deprecated_commits_warns(mut repo: TestRepo) {
let feature_wt = repo.add_worktree("feature");
diff --git a/tests/integration_tests/post_start_commands.rs b/tests/integration_tests/post_start_commands.rs
index 262d5fa2d..9daf586d4 100644
--- a/tests/integration_tests/post_start_commands.rs
+++ b/tests/integration_tests/post_start_commands.rs
@@ -604,12 +604,12 @@ approved-commands = ["cat > context.json"]
"Branch should be sanitized (feature-json)"
);
assert!(
- json.get("worktree").is_some(),
- "JSON should contain 'worktree' field"
+ json.get("worktree_path").is_some(),
+ "JSON should contain 'worktree_path' field"
);
assert!(
- json.get("repo_root").is_some(),
- "JSON should contain 'repo_root' field"
+ json.get("repo_path").is_some(),
+ "JSON should contain 'repo_path' field"
);
assert_eq!(
json["hook_type"].as_str(),
diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rs
index 8c514745d..5a7e5a2c1 100644
--- a/tests/integration_tests/readme_sync.rs
+++ b/tests/integration_tests/readme_sync.rs
@@ -2943,8 +2943,7 @@ fn test_template_variables_table_matches_constants() {
use std::collections::{BTreeMap, BTreeSet};
use strum::IntoEnumIterator;
use worktrunk::config::{
- ACTIVE_VARS, ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, EXEC_BASE_VARS, REPO_VARS,
- ValidationScope, vars_available_in,
+ ACTIVE_VARS, ALIAS_ARGS_KEY, EXEC_BASE_VARS, REPO_VARS, ValidationScope, vars_available_in,
};
use worktrunk::git::HookType;
@@ -3023,7 +3022,6 @@ fn test_template_variables_table_matches_constants() {
.iter()
.chain(REPO_VARS.iter())
.chain(EXEC_BASE_VARS.iter())
- .chain(DEPRECATED_TEMPLATE_VARS.iter())
.collect();
let infra_and_args: BTreeSet<&str> = ["hook_type", "hook_name", ALIAS_ARGS_KEY].into();
let mut operation: BTreeSet<String> = BTreeSet::new();
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snap b/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snap
index 2bed64283..cd6d98284 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__config_show_theme__show_theme.snap
@@ -66,7 +66,7 @@ exit_code: 0
  world'
  cargo build --release &&
  cargo test
-  cp {{ repo_root }}/target {{ worktree }}/target
+  cp {{ repo_path }}/target {{ worktree_path }}/target
○ Prompt formatting:
❯ Proceed? [y/N]
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 603683113..72302e5a3 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -1286,7 +1286,7 @@ broken = "echo {{ does_not_exist }} > should_not_exist.txt"
assert_snapshot!(log_content, @"
✗ Failed to expand user:broken: undefined value @ line 1
  echo {{ does_not_exist }} > should_not_exist.txt
- ↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, target, target_worktree_path, upstream, worktree, worktree_name, worktree_path
+ ↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path
");
// The step never ran.
@@ -3123,37 +3123,6 @@ fn test_var_shorthand_does_not_leak_into_hook_show() {
);
}
-#[rstest]
-fn test_var_flag_deprecated_alias_works(repo: TestRepo) {
- // Test that deprecated variable aliases (main_worktree, repo_root, worktree) can be overridden
- repo.write_test_config(
- r#"[pre-start]
-test = "echo '{{ main_worktree }}' > alias_output.txt"
-"#,
- );
-
- let output = repo
- .wt_command()
- .args([
- "hook",
- "pre-start",
- "--yes",
- "--var",
- "main_worktree=/custom/path",
- ])
- .output()
- .expect("Failed to run wt hook");
-
- assert!(output.status.success());
-
- let output_file = repo.root_path().join("alias_output.txt");
- let contents = std::fs::read_to_string(&output_file).expect("Should have created output file");
- assert!(
- contents.contains("/custom/path"),
- "Deprecated alias should be overridden, got: {contents}"
- );
-}
-
// ============================================================================
// Hook Order Preservation Tests (Issue #737)
// ============================================================================
diff --git a/tests/snapshots/integration__integration_tests__config_show__deprecated_template_variables_verbose_shows_content.snap b/tests/snapshots/integration__integration_tests__config_show__deprecated_template_variables_verbose_shows_content.snap
index dc9cd6f27..da85bafe6 100644
--- a/tests/snapshots/integration__integration_tests__config_show__deprecated_template_variables_verbose_shows_content.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__deprecated_template_variables_verbose_shows_content.snap
@@ -69,15 +69,15 @@ exit_code: 0
▲ User config: template variable main_worktree is deprecated in favor of repo
↳ To see details, run wt config show; to apply updates, run wt config update
○ worktree-path source
-  ../{{ main_worktree }}.{{ branch }}
+  ../{{ repo }}.{{ branch }}
○ worktree-path result
  ../repo.feature-a
○ worktree-path source
-  ../{{ main_worktree }}.{{ branch }}
+  ../{{ repo }}.{{ branch }}
○ worktree-path result
  ../repo.feature-b
○ worktree-path source
-  ../{{ main_worktree }}.{{ branch }}
+  ../{{ repo }}.{{ branch }}
○ worktree-path result
  ../repo.feature-c
diff --git a/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap b/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap
index d650d184b..ec583c35c 100644
--- a/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap
+++ b/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap
@@ -62,4 +62,4 @@ exit_code: 1
----- stderr -----
✗ Failed to expand eval: undefined value @ line 1
  {{ undefined_var }}
-↳ Available variables: branch, commit, cwd, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, upstream, worktree, worktree_name, worktree_path
+↳ Available variables: branch, commit, cwd, default_branch, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, upstream, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap
index a1932eaaa..befb5351c 100644
--- a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap
+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap
@@ -67,4 +67,4 @@ exit_code: 1
◎ Running in repo.detached-test (detached)...
✗ Failed to expand for-each argument: undefined value @ line 1
  Branch: {{ branch }}
-↳ Available variables: commit, cwd, default_branch, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, worktree, worktree_name, worktree_path
+↳ Available variables: commit, cwd, default_branch, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap
index 52f870c69..6d7238ee8 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap
@@ -63,4 +63,4 @@ exit_code: 1
----- stderr -----
✗ Failed to expand project pre-start hook: undefined value @ line 1
  echo 'Upstream: {{ upstream }}' > upstream.txt
-↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, target, target_worktree_path, worktree, worktree_name, worktree_path
+↳ Available variables: args, base, base_worktree_path, branch, commit, cwd, default_branch, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, worktree_name, worktree_path
diff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
index cd569a3b2..ceb07f140 100644
--- a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap
@@ -63,5 +63,5 @@ exit_code: 0
▲ Skipping feature due to template error:
✗ Failed to expand worktree-path: undefined value @ line 1
  {{ nonexistent_variable }}
-↳ Available variables: branch, main_worktree, repo, repo_path
+↳ Available variables: branch, repo, repo_path
○ No relocations performed; 1 skipped due to template error
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
index bc5ca0f58..00036ba5f 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap
@@ -49,4 +49,4 @@ exit_code: 1
  echo FIRST_RAN > first_marker.txt
✗ Failed to expand user:broken: undefined value @ line 1
  echo {{ does_not_exist }}
-↳ Available variables: args, branch, commit, cwd, default_branch, hook_name, hook_type, main_worktree, main_worktree_path, primary_worktree_path, remote, remote_url, repo, repo_path, repo_root, short_commit, target, target_worktree_path, upstream, worktree, worktree_name, worktree_path
+↳ Available variables: args, branch, commit, cwd, default_branch, hook_name, hook_type, primary_worktree_path, remote, remote_url, repo, repo_path, short_commit, target, target_worktree_path, upstream, worktree_name, worktree_path