Skip to content

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

fix(config): report a failed migration diff instead of rendering none (#4126)

Worktrunk Bot41af9ba8cc3e
diff --git a/src/commands/config/update.rs b/src/commands/config/update.rs
index 0dc575156..07e3e93b1 100644
--- a/src/commands/config/update.rs
+++ b/src/commands/config/update.rs
@@ -12,7 +12,8 @@ use anyhow::{Context, bail};
use color_print::cformat;
use worktrunk::config::{
ConfigFileKind, DeprecationInfo, DeprecationKind, compute_migrated_content, config_path,
- copy_approved_commands_to_approvals_file, format_deprecation_warnings, format_migration_diff,
+ copy_approved_commands_to_approvals_file, format_deprecation_warnings,
+ format_migration_diff_block,
};
use worktrunk::git::{Repository, resolve_input_path};
use worktrunk::path::{format_path_for_display, paths_match};
@@ -244,10 +245,11 @@ fn format_update_preview(candidate: &UpdateCandidate) -> String {
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "config".to_string());
- if let Some(diff) = format_migration_diff(&candidate.original, &candidate.migrated, &label) {
- let _ = writeln!(out, "{}", info_message("Proposed diff:"));
- let _ = writeln!(out, "{diff}");
- }
+ out.push_str(&format_migration_diff_block(
+ &candidate.original,
+ &candidate.migrated,
+ &label,
+ ));
out
}
diff --git a/src/config/deprecation.rs b/src/config/deprecation.rs
index 8b09eb160..654c4ec93 100644
--- a/src/config/deprecation.rs
+++ b/src/config/deprecation.rs
@@ -1662,36 +1662,101 @@ pub fn compute_migrated_content(content: &str) -> String {
}
}
+/// Render the `Proposed diff:` block for a migration, or a warning line when
+/// git cannot produce the patch.
+///
+/// The three outcomes of `format_migration_diff` stay distinct here: an
+/// identical pair renders nothing, a differing pair renders the patch, and a
+/// git failure renders a warning rather than disappearing. Both consumers
+/// (`wt config show` and `wt config update`) go through this so neither can
+/// present a failed diff as "no changes"; the migration itself is computed in
+/// memory and is unaffected, so a broken renderer degrades the preview rather
+/// than failing the command.
+///
+/// Returns a string ending in a newline, or empty when there is nothing to show.
+pub fn format_migration_diff_block(original: &str, migrated: &str, label: &str) -> String {
+ use std::fmt::Write;
+ let mut out = String::new();
+ match format_migration_diff(original, migrated, label) {
+ Ok(Some(diff)) => {
+ let _ = writeln!(out, "{}", info_message("Proposed diff:"));
+ let _ = writeln!(out, "{diff}");
+ }
+ Ok(None) => {}
+ Err(e) => {
+ let _ = writeln!(
+ out,
+ "{}",
+ warning_message("Could not render the proposed diff")
+ );
+ // `{e:#}` rather than `to_string()`: the git-failure arm bails with
+ // the whole payload, but a spawn or tempfile failure carries its
+ // cause one `.context` layer down, and plain Display drops it.
+ let _ = writeln!(out, "{}", format_with_gutter(&format!("{e:#}"), None));
+ }
+ }
+ out
+}
+
/// Render a colored unified diff between `original` and `migrated`, with
/// `label` shown as the file name in the diff header (e.g. `config.toml`).
///
/// Uses a private tempdir containing two files named `<label>/current` and
/// `<label>/migrated`; `git diff --no-index` is invoked from inside that
/// tempdir so the diff header shows clean relative paths. The tempdir is
-/// dropped on return. Returns `None` when the contents match.
-pub fn format_migration_diff(original: &str, migrated: &str, label: &str) -> Option<String> {
- let dir = tempfile::tempdir().expect("failed to create tempdir for migration diff");
+/// dropped on return. Returns `Ok(None)` when the contents match.
+///
+/// `--no-ext-diff` keeps the patch worktrunk's own: a user's `diff.external`
+/// program would otherwise be handed these two temp files and could emit
+/// something that isn't a patch, block on a GUI, or die and take the preview
+/// with it.
+///
+/// `git diff --no-index` exits 0 when the files match and 1 when they differ,
+/// so those two are the answer and anything else is a failure. Branching on
+/// stdout alone conflated "no changes" with "git refused to run" — the shape
+/// this guards against (#4118).
+fn format_migration_diff(
+ original: &str,
+ migrated: &str,
+ label: &str,
+) -> anyhow::Result<Option<String>> {
+ let dir = tempfile::tempdir().context("failed to create tempdir for migration diff")?;
let subdir = dir.path().join(label);
- std::fs::create_dir(&subdir).expect("failed to create subdir in fresh tempdir");
- let current = subdir.join("current");
- let migrated_path = subdir.join("migrated");
- std::fs::write(&current, original).expect("failed to write current config to tempfile");
- std::fs::write(&migrated_path, migrated).expect("failed to write migrated config to tempfile");
+ std::fs::create_dir(&subdir).context("failed to create subdir in fresh tempdir")?;
+ std::fs::write(subdir.join("current"), original)
+ .context("failed to write current config to tempfile")?;
+ std::fs::write(subdir.join("migrated"), migrated)
+ .context("failed to write migrated config to tempfile")?;
let output = Cmd::new("git")
- .args(["diff", "--no-index", "--color=always", "-U3", "--"])
+ .args([
+ "diff",
+ "--no-index",
+ "--no-ext-diff",
+ "--color=always",
+ "-U3",
+ "--",
+ ])
.arg(format!("{label}/current"))
.arg(format!("{label}/migrated"))
.current_dir(dir.path())
.run()
- .expect("git diff --no-index failed");
+ .context("failed to run git diff --no-index")?;
- // git diff --no-index exits 1 when files differ, which is expected.
- let diff_output = String::from_utf8_lossy(&output.stdout);
- if diff_output.is_empty() {
- return None;
+ match output.status.code() {
+ Some(0) => Ok(None),
+ Some(1) => Ok(Some(format_with_gutter(
+ String::from_utf8_lossy(&output.stdout).trim_end(),
+ None,
+ ))),
+ // `ExitStatus`'s own rendering covers a signal-killed child too, so
+ // there is no separate arm for one.
+ _ => anyhow::bail!(
+ "git diff --no-index, {}\n{}",
+ output.status,
+ String::from_utf8_lossy(&output.stderr).trim_end()
+ ),
}
- Some(format_with_gutter(diff_output.trim_end(), None))
}
/// Format deprecation warning lines (without apply hints or diff).
@@ -1861,10 +1926,11 @@ pub fn format_deprecation_details(info: &DeprecationInfo, original_content: &str
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "config".to_string());
- if let Some(diff) = format_migration_diff(original_content, &migrated, &label) {
- let _ = writeln!(out, "{}", info_message("Proposed diff:"));
- let _ = writeln!(out, "{diff}");
- }
+ out.push_str(&format_migration_diff_block(
+ original_content,
+ &migrated,
+ &label,
+ ));
out
}
@@ -3938,6 +4004,36 @@ approved-commands = ["npm install"]
assert_eq!(result, content, "Invalid TOML should be returned unchanged");
}
+ /// The three outcomes the block renderer has to keep apart: identical
+ /// content, changed content, and (covered by the integration tests that
+ /// break `git diff`) a failure. Before #4118 a failure rendered as the
+ /// first of these.
+ #[test]
+ fn test_migration_diff_block_separates_identical_from_changed() {
+ // This test spawns the real `git diff`, and no fixture constructor runs
+ // here to latch the floor for it — without this the child reads the
+ // developer's own global config, where a single unparsable `diff.*`
+ // value turns the first assertion into the failure arm.
+ crate::shell_exec::enable_hermetic_test_env();
+
+ let original = "worktree-path = \"../{{ repo }}.{{ branch }}\"\n";
+ assert_eq!(
+ format_migration_diff_block(original, original, "config.toml"),
+ "",
+ "identical content renders nothing"
+ );
+
+ let block = format_migration_diff_block(
+ original,
+ "worktree-path = \"../{{ repo }}.{{ branch | sanitize }}\"\n",
+ "config.toml",
+ );
+ assert!(
+ block.contains("Proposed diff:") && block.contains("sanitize"),
+ "changed content renders the patch, got:\n{block}"
+ );
+ }
+
#[test]
fn test_format_deprecation_details_approved_commands() {
let content = r#"
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 5fa1dfc18..2148baf4f 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -166,7 +166,7 @@ pub use deprecation::compute_migrated_content;
pub use deprecation::copy_approved_commands_to_approvals_file;
pub use deprecation::format_deprecation_details;
pub use deprecation::format_deprecation_warnings;
-pub use deprecation::format_migration_diff;
+pub use deprecation::format_migration_diff_block;
pub use deprecation::migrate_content;
pub use deprecation::normalize_template_vars;
pub use deprecation::suppress_warnings;
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index 02352acf2..589b6db2b 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -7177,3 +7177,57 @@ fn test_project_config_path_env_var_half_anchored_errors(repo: TestRepo) {
);
}
}
+
+/// A deprecated config whose migration diff `wt config show` renders.
+const DEPRECATED_CONFIG_FOR_DIFF: &str = r#"worktree-path = "../{{ main_worktree }}.{{ branch }}"
+"#;
+
+/// Worktrunk renders its own migration patch, so a user's `diff.external`
+/// program must not be consulted — a broken or interactive one would otherwise
+/// replace or suppress the proposed diff.
+#[rstest]
+fn test_config_show_migration_diff_ignores_external_diff(repo: TestRepo) {
+ fs::write(repo.test_config_path(), DEPRECATED_CONFIG_FOR_DIFF).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["config", "show"])
+ // Appended to the hermetic test git config (keys 0 and 1).
+ .env("GIT_CONFIG_COUNT", "3")
+ .env("GIT_CONFIG_KEY_2", "diff.external")
+ .env("GIT_CONFIG_VALUE_2", "wt-nonexistent-external-diff")
+ .output()
+ .unwrap();
+
+ let raw = String::from_utf8_lossy(&output.stdout);
+ let stdout = raw.ansi_strip();
+ assert!(
+ stdout.contains("Proposed diff:") && stdout.contains("{{ repo }}"),
+ "expected the migration patch, got:\n{stdout}"
+ );
+}
+
+/// A `git diff --no-index` that fails outright must not read as "no changes":
+/// the preview says so instead of silently dropping the patch.
+#[rstest]
+fn test_config_show_reports_failed_migration_diff(repo: TestRepo) {
+ fs::write(repo.test_config_path(), DEPRECATED_CONFIG_FOR_DIFF).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["config", "show"])
+ // An unparsable `diff.*` value fails git after option parsing, which
+ // `--no-ext-diff` cannot prevent.
+ .env("GIT_CONFIG_COUNT", "3")
+ .env("GIT_CONFIG_KEY_2", "diff.algorithm")
+ .env("GIT_CONFIG_VALUE_2", "wt-nonexistent-diff-algorithm")
+ .output()
+ .unwrap();
+
+ let raw = String::from_utf8_lossy(&output.stdout);
+ let stdout = raw.ansi_strip();
+ assert!(
+ stdout.contains("Could not render the proposed diff"),
+ "expected the failure to be reported, got:\n{stdout}"
+ );
+}