Skip to content

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

Add wt step {commit,squash} --dry-run, hide --show-prompt (#2557)

Maximilian Roose5d0c138eae8
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.md
index d0eeb3d06..208e19417 100644
--- a/.claude/skills/writing-user-outputs/SKILL.md
+++ b/.claude/skills/writing-user-outputs/SKILL.md
@@ -104,6 +104,23 @@ Examples:
- `wt config shell init` → shell code to stdout (for `eval`)
- `wt switch` → status messages only (nothing to pipe)
+## When to page output
+
+Route long, human-oriented stdout through `crate::help_pager::show_help_in_pager`. The helper TTY-detects internally, so piping (`wt … | grep`) keeps working.
+
+Page when output is human-oriented (headings, gutters, structure) and plausibly exceeds one screen. Don't page pipe-first data (tables, JSON, shell code), short output, or output already paged by a delegated tool (`git diff`).
+
+Examples that page: `--help`, `wt config show`, `wt hook show`, `wt step {commit,squash} --dry-run`. Examples that don't: `wt list`, `wt step diff`, `wt step eval`, `--show-prompt` (pipe-first by design).
+
+Build the whole output into a `String` first (don't stream), then:
+
+```rust
+if let Err(e) = crate::help_pager::show_help_in_pager(&out, true) {
+ log::debug!("Pager failed, falling back to stdout: {}", e);
+ println!("{}", out);
+}
+```
+
## Security
The split-trust design enforces two trust levels:
diff --git a/docs/content/step.md b/docs/content/step.md
index aa942a216..4713e8dc8 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -116,11 +116,13 @@ Configure the default in user config:
stage = "tracked"
```
-#### `--show-prompt`
+#### `--dry-run`
-Output the rendered LLM prompt to stdout without running the command. Useful for inspecting prompt templates or piping to other tools:
+Render the prompt, print the LLM command, generate the message, and exit without staging, running hooks, or committing:
-{{ terminal(cmd="# Inspect the rendered prompt|||wt step commit --show-prompt | less||||||# Pipe to a different LLM|||wt step commit --show-prompt | llm -m gpt-5-nano") }}
+{{ terminal(cmd="wt step commit --dry-run") }}
+
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the commit is skipped.
### Command reference
@@ -144,10 +146,8 @@ Usage: <b><span class=c>wt step commit</span></b> <span class=c>[OPTIONS]</span>
- <b><span class=c>tracked</span></b>: Stage tracked changes only (like <b>git add -u</b>)
- <b><span class=c>none</span></b>: Stage nothing, commit only what&#39;s already in the index
- <b><span class=c>--show-prompt</span></b>
- Show prompt without running LLM
-
- Outputs the rendered prompt to stdout for debugging or manual piping.
+ <b><span class=c>--dry-run</span></b>
+ Preview prompt, command, and generated message without committing
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
Print help (see a summary with &#39;-h&#39;)
@@ -194,11 +194,13 @@ Configure the default in user config:
stage = "tracked"
```
-#### `--show-prompt`
+#### `--dry-run`
-Output the rendered LLM prompt to stdout without running the command. Useful for inspecting prompt templates or piping to other tools:
+Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
-{{ terminal(cmd="wt step squash --show-prompt | less") }}
+{{ terminal(cmd="wt step squash --dry-run") }}
+
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
### Command reference
@@ -227,10 +229,8 @@ Usage: <b><span class=c>wt step squash</span></b> <span class=c>[OPTIONS]</span>
- <b><span class=c>tracked</span></b>: Stage tracked changes only (like <b>git add -u</b>)
- <b><span class=c>none</span></b>: Stage nothing, commit only what&#39;s already in the index
- <b><span class=c>--show-prompt</span></b>
- Show prompt without running LLM
-
- Outputs the rendered prompt to stdout for debugging or manual piping.
+ <b><span class=c>--dry-run</span></b>
+ Preview prompt, command, and generated message without squashing
<b><span class=c>-h</span></b>, <b><span class=c>--help</span></b>
Print help (see a summary with &#39;-h&#39;)
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index 3a712419e..ef1e45a1c 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -109,18 +109,16 @@ Configure the default in user config:
stage = "tracked"
```
-#### `--show-prompt`
+#### `--dry-run`
-Output the rendered LLM prompt to stdout without running the command. Useful for inspecting prompt templates or piping to other tools:
+Render the prompt, print the LLM command, generate the message, and exit without staging, running hooks, or committing:
```bash
-# Inspect the rendered prompt
-$ wt step commit --show-prompt | less
-
-# Pipe to a different LLM
-$ wt step commit --show-prompt | llm -m gpt-5-nano
+$ wt step commit --dry-run
```
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the commit is skipped.
+
### Command reference
```
@@ -143,10 +141,8 @@ Options:
- tracked: Stage tracked changes only (like git add -u)
- none: Stage nothing, commit only what's already in the index
- --show-prompt
- Show prompt without running LLM
-
- Outputs the rendered prompt to stdout for debugging or manual piping.
+ --dry-run
+ Preview prompt, command, and generated message without committing
-h, --help
Print help (see a summary with '-h')
@@ -195,14 +191,16 @@ Configure the default in user config:
stage = "tracked"
```
-#### `--show-prompt`
+#### `--dry-run`
-Output the rendered LLM prompt to stdout without running the command. Useful for inspecting prompt templates or piping to other tools:
+Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
```bash
-$ wt step squash --show-prompt | less
+$ wt step squash --dry-run
```
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
+
### Command reference
```
@@ -230,10 +228,8 @@ Options:
- tracked: Stage tracked changes only (like git add -u)
- none: Stage nothing, commit only what's already in the index
- --show-prompt
- Show prompt without running LLM
-
- Outputs the rendered prompt to stdout for debugging or manual piping.
+ --dry-run
+ Preview prompt, command, and generated message without squashing
-h, --help
Print help (see a summary with '-h')
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 569c76f3f..6c019ec9f 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -18,10 +18,12 @@ pub struct CommitArgs {
#[arg(long)]
pub(crate) stage: Option<crate::commands::commit::StageMode>,
- /// Show prompt without running LLM
- ///
- /// Outputs the rendered prompt to stdout for debugging or manual piping.
- #[arg(long)]
+ /// Preview prompt, command, and generated message without committing
+ #[arg(long, conflicts_with = "show_prompt")]
+ pub(crate) dry_run: bool,
+
+ /// Render prompt to stdout without running LLM
+ #[arg(long, hide = true)]
pub(crate) show_prompt: bool,
}
@@ -45,10 +47,12 @@ pub struct SquashArgs {
#[arg(long)]
pub(crate) stage: Option<crate::commands::commit::StageMode>,
- /// Show prompt without running LLM
- ///
- /// Outputs the rendered prompt to stdout for debugging or manual piping.
- #[arg(long)]
+ /// Preview prompt, command, and generated message without squashing
+ #[arg(long, conflicts_with = "show_prompt")]
+ pub(crate) dry_run: bool,
+
+ /// Render prompt to stdout without running LLM
+ #[arg(long, hide = true)]
pub(crate) show_prompt: bool,
}
@@ -88,17 +92,15 @@ Configure the default in user config:
stage = "tracked"
```
-### `--show-prompt`
+### `--dry-run`
-Output the rendered LLM prompt to stdout without running the command. Useful for inspecting prompt templates or piping to other tools:
+Render the prompt, print the LLM command, generate the message, and exit without staging, running hooks, or committing:
```console
-# Inspect the rendered prompt
-$ wt step commit --show-prompt | less
-
-# Pipe to a different LLM
-$ wt step commit --show-prompt | llm -m gpt-5-nano
+$ wt step commit --dry-run
```
+
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the commit is skipped.
"#
)]
Commit(CommitArgs),
@@ -132,13 +134,15 @@ Configure the default in user config:
stage = "tracked"
```
-### `--show-prompt`
+### `--dry-run`
-Output the rendered LLM prompt to stdout without running the command. Useful for inspecting prompt templates or piping to other tools:
+Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
```console
-$ wt step squash --show-prompt | less
+$ wt step squash --dry-run
```
+
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
"#
)]
Squash(SquashArgs),
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index 50c62b070..bc66f1bb2 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -164,7 +164,7 @@ impl<'a> CommitGenerator<'a> {
}
self.emit_hint_if_needed();
- let commit_message = crate::llm::generate_commit_message(self.config)?;
+ let commit_message = crate::llm::generate_commit_message(self.config, None)?;
let formatted_message = self.format_message_for_display(&commit_message);
eprintln!("{}", format_with_gutter(&formatted_message, None));
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index 5e177548e..185ba2c99 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -57,7 +57,8 @@ pub(crate) use repository_ext::RemoveTarget;
pub(crate) use run_pipeline::run_pipeline;
pub(crate) use step_commands::{
PromoteResult, RebaseResult, SquashResult, handle_promote, handle_rebase, handle_squash,
- step_commit, step_copy_ignored, step_diff, step_prune, step_relocate, step_show_squash_prompt,
+ step_commit, step_copy_ignored, step_diff, step_dry_run_squash, step_prune, step_relocate,
+ step_show_squash_prompt,
};
pub(crate) use worktree::{
OperationMode, is_worktree_at_expected_path, resolve_worktree_arg, worktree_display_name,
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index b8cf5dfaf..5c33f947a 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -31,8 +31,8 @@ use worktrunk::path::format_path_for_display;
use worktrunk::progress::{Progress, format_bytes};
use worktrunk::shell_exec::Cmd;
use worktrunk::styling::{
- eprintln, format_with_gutter, hint_message, info_message, progress_message, success_message,
- verbosity, warning_message,
+ eprintln, format_bash_with_gutter, format_heading, format_with_gutter, hint_message,
+ info_message, println, progress_message, success_message, verbosity, warning_message,
};
use super::command_approval::approve_or_skip;
@@ -54,16 +54,13 @@ pub fn step_commit(
verify: bool,
stage: Option<StageMode>,
show_prompt: bool,
+ dry_run: bool,
) -> anyhow::Result<()> {
- // Handle --show-prompt early: just build and output the prompt
- if show_prompt {
- let repo = worktrunk::git::Repository::current()?;
- let config = UserConfig::load().context("Failed to load config")?;
- let project_id = repo.project_identifier().ok();
- let commit_config = config.commit_generation(project_id.as_deref());
- let prompt = crate::llm::build_commit_prompt(&commit_config)?;
- println!("{}", prompt);
- return Ok(());
+ // --show-prompt and --dry-run skip hooks and the commit itself; --dry-run still
+ // mirrors --stage against a temp index so the previewed prompt matches what a real
+ // run would send the LLM.
+ if show_prompt || dry_run {
+ return preview_commit(stage, dry_run);
}
// Load config once, run LLM setup prompt, then reuse config
@@ -102,6 +99,117 @@ pub fn step_commit(
announcer.flush()
}
+/// Handle `wt step commit` in `--show-prompt` or `--dry-run` mode.
+///
+/// Both modes skip hooks and the commit itself. `--show-prompt` outputs only the
+/// rendered prompt against the existing index (cheap, pipeable). `--dry-run` mirrors
+/// `--stage` against a temp index — so the previewed prompt matches what a real run
+/// would send — then calls the LLM and prints the command and message in three labeled
+/// sections. The user's real index is never modified.
+fn preview_commit(stage: Option<StageMode>, dry_run: bool) -> anyhow::Result<()> {
+ let env = CommandEnv::for_action(UserConfig::load().context("Failed to load config")?)?;
+ let commit_config = env.resolved().commit_generation.clone();
+
+ // For --dry-run, stage to a copy of the index so the preview reflects what a real
+ // run would send. --show-prompt skips this — it's the cheap "what's already staged"
+ // path. StageMode::None has nothing to stage, so we use the existing index as-is.
+ let temp_index = if dry_run {
+ let add_args: Option<&[&str]> = match stage.unwrap_or(env.resolved().commit.stage()) {
+ StageMode::All => Some(&["add", "-A"]),
+ StageMode::Tracked => Some(&["add", "-u"]),
+ StageMode::None => None,
+ };
+ add_args
+ .map(|args| stage_to_temp_index(&env.repo, args))
+ .transpose()?
+ } else {
+ None
+ };
+ let index_override = temp_index.as_ref().map(|t| t.path());
+
+ let prompt = crate::llm::build_commit_prompt(&commit_config, index_override)?;
+ if !dry_run {
+ println!("{}", prompt);
+ return Ok(());
+ }
+ let message = crate::llm::generate_commit_message(&commit_config, index_override)?;
+ print_dry_run(&prompt, &commit_config, &message)
+}
+
+/// Copy the current worktree's index to a temp file and run `git <add_args>` against it.
+///
+/// Returns the [`tempfile::NamedTempFile`] so the caller controls its lifetime — when
+/// dropped, the temp file is removed without ever touching the user's real index.
+fn stage_to_temp_index(
+ repo: &Repository,
+ add_args: &[&str],
+) -> anyhow::Result<tempfile::NamedTempFile> {
+ let wt = repo.current_worktree();
+ let real_index = wt.git_dir()?.join("index");
+ let temp = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;
+ fs::copy(&real_index, temp.path()).context("Failed to copy index file")?;
+
+ let output = Cmd::new("git")
+ .args(add_args.iter().copied())
+ .current_dir(wt.root()?)
+ .env("GIT_INDEX_FILE", temp.path())
+ .run()
+ .context("Failed to stage changes into temp index")?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("git {} failed: {}", add_args.join(" "), stderr.trim());
+ }
+ Ok(temp)
+}
+
+/// Print the three dry-run sections: rendered prompt, LLM command, generated message.
+///
+/// The COMMAND and MESSAGE sections use the same gutter treatment as the regular commit
+/// flow — `format_bash_with_gutter` for the shell invocation, and the bold-first-line
+/// commit message format wrapped in `format_with_gutter`. The PROMPT is left ungutter'd
+/// to keep `--dry-run`'s output visually aligned with `--show-prompt`.
+///
+/// Output is routed through the pager when stdout is a TTY (see writing-user-outputs →
+/// "When to page output"). The helper falls back to direct stdout when piped.
+fn print_dry_run(
+ prompt: &str,
+ commit_config: &worktrunk::config::CommitGenerationConfig,
+ message: &str,
+) -> anyhow::Result<()> {
+ use std::fmt::Write as _;
+ let mut out = String::new();
+ writeln!(out, "{}", format_heading("PROMPT", None))?;
+ writeln!(out, "{}", prompt)?;
+ writeln!(out)?;
+ writeln!(out, "{}", format_heading("COMMAND", None))?;
+ match commit_config
+ .command
+ .as_deref()
+ .filter(|s| !s.trim().is_empty())
+ {
+ Some(cmd) => writeln!(
+ out,
+ "{}",
+ format_bash_with_gutter(&crate::llm::render_llm_invocation(cmd)?)
+ )?,
+ None => writeln!(
+ out,
+ "{}",
+ format_with_gutter("(LLM not configured — using built-in fallback)", None)
+ )?,
+ }
+ writeln!(out)?;
+ writeln!(out, "{}", format_heading("MESSAGE", None))?;
+ let formatted = CommitGenerator::new(commit_config).format_message_for_display(message);
+ writeln!(out, "{}", format_with_gutter(&formatted, None))?;
+
+ if let Err(e) = crate::help_pager::show_help_in_pager(&out, true) {
+ log::debug!("Pager failed, falling back to stdout: {}", e);
+ println!("{}", out);
+ }
+ Ok(())
+}
+
/// Result of a squash operation
#[derive(Debug, Clone)]
pub enum SquashResult {
@@ -374,28 +482,38 @@ pub fn handle_squash(
///
/// Builds and outputs the squash prompt without running the LLM or squashing.
pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {
+ preview_squash(target, false)
+}
+
+/// Handle `wt step squash --dry-run`
+///
+/// Renders the squash prompt, prints the LLM command, generates the message, and prints
+/// it without resetting, running hooks, or committing.
+pub fn step_dry_run_squash(target: Option<&str>) -> anyhow::Result<()> {
+ preview_squash(target, true)
+}
+
+/// Shared implementation for `--show-prompt` and `--dry-run` on squash. `--show-prompt`
+/// (`dry_run = false`) outputs only the rendered prompt; `--dry-run` additionally calls
+/// the LLM and prints the command and the generated message.
+fn preview_squash(target: Option<&str>, dry_run: bool) -> anyhow::Result<()> {
let repo = Repository::current()?;
let config = UserConfig::load().context("Failed to load config")?;
let project_id = repo.project_identifier().ok();
- let effective_config = config.commit_generation(project_id.as_deref());
+ let commit_config = config.commit_generation(project_id.as_deref());
- // Get and validate target ref (any commit-ish for merge-base calculation)
let integration_target = repo.require_target_ref(target)?;
- // Get current branch
let wt = repo.current_worktree();
let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());
- // Get merge base with target branch (required for generating squash message)
let merge_base = repo
.merge_base("HEAD", &integration_target)?
.context("Cannot generate squash message: no common ancestor with target branch")?;
- // Get commit subjects for the squash message
let range = format!("{}..HEAD", merge_base);
let subjects = repo.commit_subjects(&range)?;
- // Get repo name from directory
let repo_root = wt.root()?;
let repo_name = repo_root
.file_name()
@@ -408,10 +526,21 @@ pub fn step_show_squash_prompt(target: Option<&str>) -> anyhow::Result<()> {
&subjects,
&current_branch,
repo_name,
- &effective_config,
+ &commit_config,
)?;
- println!("{}", prompt);
- Ok(())
+ if !dry_run {
+ println!("{}", prompt);
+ return Ok(());
+ }
+ let message = crate::llm::generate_squash_message(
+ &integration_target,
+ &merge_base,
+ &subjects,
+ &current_branch,
+ repo_name,
+ &commit_config,
+ )?;
+ print_dry_run(&prompt, &commit_config, &message)
}
/// Result of a rebase operation
diff --git a/src/llm.rs b/src/llm.rs
index f0163a6d2..bb7cde4be 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -19,6 +19,31 @@ const SHELL_METACHARACTERS: &[char] = &[
'\\',
];
+/// Render the shell invocation worktrunk would use to run `command`.
+///
+/// Mirrors the wrapping done by [`execute_llm_command`]: every LLM command is passed as
+/// a single argument to the platform shell, so the displayed form is always
+/// `<shell> <shell-args> <quoted-command>` (e.g. `sh -c 'claude -p'`).
+///
+/// Uses the shell's basename rather than the full path so the displayed command stays
+/// short and doesn't leak the user's install path (`C:\Program Files\Git\bin\bash.exe`
+/// becomes `bash.exe`).
+pub(crate) fn render_llm_invocation(command: &str) -> anyhow::Result<String> {
+ let shell = ShellConfig::get()?;
+ let mut rendered = shell
+ .executable
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_else(|| shell.executable.to_string_lossy().into_owned());
+ for arg in &shell.args {
+ rendered.push(' ');
+ rendered.push_str(arg);
+ }
+ rendered.push(' ');
+ rendered.push_str(&escape(Cow::Borrowed(command)));
+ Ok(rendered)
+}
+
/// Format a reproduction command, only wrapping with `sh -c` if needed.
///
/// Simple commands like `llm -m haiku` are shown as-is.
@@ -475,30 +500,39 @@ fn build_prompt(
Ok(rendered)
}
+/// `index_override` is forwarded to git operations that read the staging area, so
+/// `--dry-run` can preview against a temp index without touching the user's real one.
pub(crate) fn generate_commit_message(
commit_generation_config: &CommitGenerationConfig,
+ index_override: Option<&Path>,
) -> anyhow::Result<String> {
// Check if commit generation is configured (non-empty command)
if commit_generation_config.is_configured() {
let command = commit_generation_config.command.as_ref().unwrap();
// Commit generation is explicitly configured - fail if it doesn't work
- return try_generate_commit_message(command, commit_generation_config).map_err(|e| {
- worktrunk::git::GitError::LlmCommandFailed {
- command: command.clone(),
- error: e.to_string(),
- reproduction_command: Some(format_reproduction_command(
- "wt step commit --show-prompt",
- command,
- )),
- }
- .into()
- });
+ return try_generate_commit_message(command, commit_generation_config, index_override)
+ .map_err(|e| {
+ worktrunk::git::GitError::LlmCommandFailed {
+ command: command.clone(),
+ error: e.to_string(),
+ reproduction_command: Some(format_reproduction_command(
+ "wt step commit --show-prompt",
+ command,
+ )),
+ }
+ .into()
+ });
}
// Fallback: generate a descriptive commit message based on changed files
let repo = Repository::current()?;
- // Use -z for NUL-separated output to handle filenames with spaces/newlines
- let file_list = repo.run_command(&["diff", "--staged", "--name-only", "-z"])?;
+ let mut name_only = Cmd::new("git")
+ .args(["diff", "--staged", "--name-only", "-z"])
+ .current_dir(repo.discovery_path());
+ if let Some(path) = index_override {
+ name_only = name_only.env("GIT_INDEX_FILE", path);
+ }
+ let file_list = run_git_capture(name_only, "diff --staged --name-only")?;
let staged_files = file_list
.split('\0')
.map(|s| s.trim())
@@ -528,31 +562,66 @@ pub(crate) fn generate_commit_message(
fn try_generate_commit_message(
command: &str,
config: &CommitGenerationConfig,
+ index_override: Option<&Path>,
) -> anyhow::Result<String> {
- let prompt = build_commit_prompt(config)?;
+ let prompt = build_commit_prompt(config, index_override)?;
execute_llm_command(command, &prompt)
}
+/// Run a git `Cmd` and bail on non-zero exit, mirroring [`Repository::run_command`].
+///
+/// Used by call sites that need to set `GIT_INDEX_FILE` (`--dry-run`) and so can't go
+/// through `Repository::run_command`. Without this check, a failing `git diff` would
+/// silently feed an empty diff to the LLM.
+fn run_git_capture(cmd: Cmd, what: &str) -> anyhow::Result<String> {
+ let output = cmd
+ .run()
+ .with_context(|| format!("Failed to execute git {what}"))?;
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ anyhow::bail!("git {what} failed: {}", stderr.trim());
+ }
+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+}
+
/// Build the commit prompt from staged changes.
///
/// Gathers the staged diff, branch name, repo name, and recent commits, then renders
-/// the prompt template. Used by both normal commit generation and `--show-prompt`.
-pub(crate) fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<String> {
+/// the prompt template. Used by normal commit generation, `--show-prompt`, and
+/// `--dry-run`.
+///
+/// `index_override` points git at an alternate index via `GIT_INDEX_FILE` — used by
+/// `--dry-run` to preview what `git add` per the user's `--stage` flag would produce
+/// without modifying the real index.
+pub(crate) fn build_commit_prompt(
+ config: &CommitGenerationConfig,
+ index_override: Option<&Path>,
+) -> anyhow::Result<String> {
let repo = Repository::current()?;
+ let cwd = repo.discovery_path().to_path_buf();
- // Get staged diff and diffstat
// Use -c flags to ensure consistent format regardless of user's git config
// (diff.noprefix, diff.mnemonicPrefix, etc. could break our parsing)
- let diff_output = repo.run_command(&[
- "-c",
- "diff.noprefix=false",
- "-c",
- "diff.mnemonicPrefix=false",
- "--no-pager",
- "diff",
- "--staged",
- ])?;
- let diff_stat = repo.run_command(&["--no-pager", "diff", "--staged", "--stat"])?;
+ let mut diff_cmd = Cmd::new("git")
+ .args([
+ "-c",
+ "diff.noprefix=false",
+ "-c",
+ "diff.mnemonicPrefix=false",
+ "--no-pager",
+ "diff",
+ "--staged",
+ ])
+ .current_dir(&cwd);
+ let mut diff_stat_cmd = Cmd::new("git")
+ .args(["--no-pager", "diff", "--staged", "--stat"])
+ .current_dir(&cwd);
+ if let Some(index) = index_override {
+ diff_cmd = diff_cmd.env("GIT_INDEX_FILE", index);
+ diff_stat_cmd = diff_stat_cmd.env("GIT_INDEX_FILE", index);
+ }
+ let diff_output = run_git_capture(diff_cmd, "diff --staged")?;
+ let diff_stat = run_git_capture(diff_stat_cmd, "diff --staged --stat")?;
// Prepare diff (may filter if too large)
let prepared = prepare_diff(diff_output, diff_stat);
@@ -733,6 +802,35 @@ mod tests {
use super::*;
use insta::assert_snapshot;
+ /// `render_llm_invocation` should wrap the command through the platform shell with
+ /// the shell's basename (no full install path) and shell-escape the command argument
+ /// so paths/quotes survive the round-trip.
+ #[test]
+ fn test_render_llm_invocation_basics() {
+ let rendered = render_llm_invocation("llm -m haiku").unwrap();
+ // Linux: "sh -c 'llm -m haiku'" — Windows: "bash.exe -c 'llm -m haiku'"
+ assert!(
+ rendered.ends_with(" -c 'llm -m haiku'"),
+ "expected '<shell> -c <quoted-command>', got: {rendered}"
+ );
+ // Basename only — no install-path leakage.
+ assert!(
+ !rendered.contains('/') && !rendered.contains('\\'),
+ "shell rendered with directory components: {rendered}"
+ );
+ }
+
+ /// Single-quotes in the user's command must be escaped so the displayed string is a
+ /// faithful, copy-pasteable shell invocation.
+ #[test]
+ fn test_render_llm_invocation_escapes_quotes() {
+ let rendered = render_llm_invocation("echo 'hi'").unwrap();
+ assert!(
+ rendered.contains(r#"'echo '\''hi'\'''"#),
+ "single quotes not escaped: {rendered}"
+ );
+ }
+
/// Helper to create a commit context (no squash-specific fields)
fn commit_context<'a>(
git_diff: &'a str,
diff --git a/src/main.rs b/src/main.rs
index 810c9f71a..3d9739deb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -208,13 +208,22 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
match action {
StepCommand::Commit(args) => {
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
- step_commit(args.branch, yes, verify, args.stage, args.show_prompt)
+ step_commit(
+ args.branch,
+ yes,
+ verify,
+ args.stage,
+ args.show_prompt,
+ args.dry_run,
+ )
}
StepCommand::Squash(args) => {
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
- // Handle --show-prompt early: just build and output the prompt
+ // --show-prompt and --dry-run skip the squash and exit after preview output.
if args.show_prompt {
commands::step_show_squash_prompt(args.target.as_deref())
+ } else if args.dry_run {
+ commands::step_dry_run_squash(args.target.as_deref())
} else {
// Approval is handled inside handle_squash (like step_commit).
let repo = Repository::current()?;
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index e7a51f9c4..8ca48a5c6 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -903,6 +903,13 @@ fn setup_snapshot_settings_for_paths_with_home(
add_remove_stats_byte_filter(&mut settings);
+ // Normalize the platform shell basename so cross-platform snapshots match.
+ // `wt step {commit,squash} --dry-run` renders the LLM shell invocation,
+ // which is `sh` on Unix and `bash.exe` on Windows (Git Bash). No `\b`: the
+ // syntax-highlighted output puts an ANSI code (`...m`) immediately before
+ // `bash`, and `m` is a word char so `\bbash` wouldn't see a word boundary.
+ settings.add_filter(r"bash\.exe", "sh");
+
// Filter out Git hint messages that vary across Git versions
// These hints appear during rebase conflicts and can differ between versions
// Pattern matches lines with gutter formatting + "hint:" + message + newline
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index fb9ecaa4d..b84058a59 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2362,6 +2362,213 @@ fn test_step_squash_show_prompt(repo_with_multi_commit_feature: TestRepo) {
));
}
+// =============================================================================
+// --dry-run tests
+// =============================================================================
+
+#[rstest]
+fn test_step_commit_dry_run(repo: TestRepo) {
+ // Stage a change so the prompt has a diff to describe
+ fs::write(repo.root_path().join("new_file.txt"), "new content").expect("Failed to write file");
+ repo.git_command()
+ .args(["add", "new_file.txt"])
+ .run()
+ .expect("git add failed");
+
+ // Stub the LLM with a command that consumes stdin and prints a fixed message
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'feat: add new_file'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ // PROMPT/COMMAND/MESSAGE sections render to stdout; nothing is committed.
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["commit", "--dry-run"],
+ None
+ ));
+
+ // Confirm no commit was created — HEAD must still be the fixture's initial commit.
+ let log = repo
+ .git_command()
+ .args(["log", "--oneline"])
+ .run()
+ .expect("git log failed");
+ let log_text = String::from_utf8(log.stdout).unwrap();
+ assert_eq!(
+ log_text.lines().count(),
+ 1,
+ "--dry-run must not create a commit; got log:\n{log_text}"
+ );
+}
+
+/// `--dry-run` should mirror `--stage` against a temp index so the prompt reflects what a
+/// real run would send the LLM — including untracked files that aren't yet in the index.
+#[rstest]
+fn test_step_commit_dry_run_stages_untracked(repo: TestRepo) {
+ // Untracked, never `git add`'d. Default --stage=all would pick this up at commit time.
+ fs::write(repo.root_path().join("untracked.txt"), "untracked content")
+ .expect("Failed to write file");
+
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'feat: add untracked'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ let output = make_snapshot_cmd(&repo, "step", &["commit", "--dry-run"], None)
+ .output()
+ .expect("wt step commit --dry-run failed");
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ assert!(
+ stdout.contains("untracked.txt"),
+ "--dry-run with default --stage=all should include untracked files in the prompt; \
+ got stdout:\n{stdout}"
+ );
+
+ // The user's real index must not have absorbed the untracked file.
+ let status = repo
+ .git_command()
+ .args(["status", "--porcelain"])
+ .run()
+ .expect("git status failed");
+ let status_text = String::from_utf8(status.stdout).unwrap();
+ assert!(
+ status_text.contains("?? untracked.txt"),
+ "untracked.txt should remain untracked after --dry-run; got status:\n{status_text}"
+ );
+}
+
+/// `--stage=none` overrides the default — `--dry-run` should respect the override and
+/// preview against only what's already in the index, ignoring untracked changes.
+#[rstest]
+fn test_step_commit_dry_run_stage_none(repo: TestRepo) {
+ fs::write(repo.root_path().join("untracked.txt"), "untracked content")
+ .expect("Failed to write file");
+
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'fallback'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ let output = make_snapshot_cmd(
+ &repo,
+ "step",
+ &["commit", "--dry-run", "--stage=none"],
+ None,
+ )
+ .output()
+ .expect("wt step commit --dry-run --stage=none failed");
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ assert!(
+ !stdout.contains("untracked.txt"),
+ "--stage=none should skip untracked files in the dry-run prompt; got stdout:\n{stdout}"
+ );
+}
+
+/// `--stage=tracked` should mirror `git add -u` against the temp index — modifications
+/// to tracked files appear in the prompt, but untracked files do not.
+#[rstest]
+fn test_step_commit_dry_run_stage_tracked(repo: TestRepo) {
+ // Create and commit a tracked file first
+ fs::write(repo.root_path().join("tracked.txt"), "original").expect("Failed to write");
+ repo.git_command()
+ .args(["add", "tracked.txt"])
+ .run()
+ .expect("git add failed");
+ repo.git_command()
+ .args(["commit", "-m", "add tracked"])
+ .run()
+ .expect("git commit failed");
+
+ // Modify the tracked file (unstaged) and create a new untracked file
+ fs::write(repo.root_path().join("tracked.txt"), "modified").expect("Failed to write");
+ fs::write(repo.root_path().join("untracked.txt"), "new").expect("Failed to write");
+
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'feat: tweak'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ let output = make_snapshot_cmd(
+ &repo,
+ "step",
+ &["commit", "--dry-run", "--stage=tracked"],
+ None,
+ )
+ .output()
+ .expect("wt step commit --dry-run --stage=tracked failed");
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ assert!(
+ stdout.contains("tracked.txt") && stdout.contains("modified"),
+ "--stage=tracked should include modified tracked files; got stdout:\n{stdout}"
+ );
+ assert!(
+ !stdout.contains("untracked.txt"),
+ "--stage=tracked should skip untracked files; got stdout:\n{stdout}"
+ );
+}
+
+/// `--dry-run` without an LLM configured falls back to the deterministic message
+/// generator and prints `(LLM not configured — using built-in fallback)` for COMMAND.
+#[rstest]
+fn test_step_commit_dry_run_no_llm_configured(repo: TestRepo) {
+ fs::write(repo.root_path().join("new.txt"), "x").expect("Failed to write");
+ repo.git_command()
+ .args(["add", "new.txt"])
+ .run()
+ .expect("git add failed");
+ // Empty config: no [commit.generation] section.
+ fs::write(repo.test_config_path(), "").unwrap();
+
+ let output = make_snapshot_cmd(&repo, "step", &["commit", "--dry-run"], None)
+ .output()
+ .expect("wt step commit --dry-run failed");
+ let stdout = String::from_utf8(output.stdout).unwrap();
+ assert!(
+ stdout.contains("LLM not configured"),
+ "fallback notice should appear in the COMMAND section; got stdout:\n{stdout}"
+ );
+ assert!(
+ stdout.contains("Changes to new.txt"),
+ "fallback message generator should describe the staged file; got stdout:\n{stdout}"
+ );
+}
+
+#[rstest]
+fn test_step_squash_dry_run(repo_with_multi_commit_feature: TestRepo) {
+ let repo = repo_with_multi_commit_feature;
+ let feature_wt = repo.worktree_path("feature");
+
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'feat: combined feature work'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["squash", "--dry-run"],
+ Some(feature_wt)
+ ));
+
+ // The feature branch must still have its multiple commits — squash didn't run.
+ let log = std::process::Command::new("git")
+ .args(["-C", feature_wt.to_str().unwrap(), "log", "--oneline"])
+ .output()
+ .expect("git log failed");
+ let log_text = String::from_utf8(log.stdout).unwrap();
+ assert!(
+ log_text.lines().count() > 1,
+ "--dry-run must not squash; got log:\n{log_text}"
+ );
+}
+
// =============================================================================
// step rebase tests
// =============================================================================
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_dry_run.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_dry_run.snap
new file mode 100644
index 000000000..64d816dda
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_dry_run.snap
@@ -0,0 +1,97 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - commit
+ - "--dry-run"
+ 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_COMMON_DIR: ""
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
+ GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
+ GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ 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_OPENCODE_INSTALLED: "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 -----
+PROMPT
+<task>Write a commit message for the staged changes below.</task>
+
+<format>
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
+- Output only the commit message, no quotes or code blocks
+</format>
+
+<style>
+- Imperative mood: "Add feature" not "Added feature"
+- Match recent commit style (conventional commits if used)
+- Describe the change, not the intent or benefit
+</style>
+
+<diffstat>
+ new_file.txt | 1 +
+ 1 file changed, 1 insertion(+)
+
+</diffstat>
+
+<diff>
+diff --git a/new_file.txt b/new_file.txt
+new file mode 100644
+index 0000000..47d2739
+--- /dev/null
++++ b/new_file.txt
+@@ -0,0 +1 @@
++new content
+\ No newline at end of file
+
+</diff>
+
+<context>
+Branch: main
+<recent_commits>
+- Initial commit
+</recent_commits>
+</context>
+
+COMMAND
+  sh -c 'cat >/dev/null && echo '\''feat: add new_file'\'''
+
+MESSAGE
+  feat: add new_file
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap b/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap
new file mode 100644
index 000000000..9d6a3521d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_squash_dry_run.snap
@@ -0,0 +1,104 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - squash
+ - "--dry-run"
+ 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_COMMON_DIR: ""
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
+ GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
+ GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ 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_OPENCODE_INSTALLED: "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 -----
+PROMPT
+<task>Write a commit message for the combined effect of these commits.</task>
+
+<format>
+- Subject line under 50 chars
+- For material changes, add a blank line then a body paragraph explaining the change
+- Output only the commit message, no quotes or code blocks
+</format>
+
+<style>
+- Imperative mood: "Add feature" not "Added feature"
+- Match the style of commits being squashed (conventional commits if used)
+- Describe the change, not the intent or benefit
+</style>
+
+<commits branch="feature" target="main">
+- feat: add file 1
+- feat: add file 2
+</commits>
+
+<diffstat>
+ file1.txt | 1 +
+ file2.txt | 1 +
+ 2 files changed, 2 insertions(+)
+
+</diffstat>
+
+<diff>
+diff --git a/file1.txt b/file1.txt
+new file mode 100644
+index 0000000..a523607
+--- /dev/null
++++ b/file1.txt
+@@ -0,0 +1 @@
++content 1
+\ No newline at end of file
+diff --git a/file2.txt b/file2.txt
+new file mode 100644
+index 0000000..9f8f8ac
+--- /dev/null
++++ b/file2.txt
+@@ -0,0 +1 @@
++content 2
+\ No newline at end of file
+
+</diff>
+
+COMMAND
+  sh -c 'cat >/dev/null && echo '\''feat: combined feature work'\'''
+
+MESSAGE
+  feat: combined feature work
+
+----- stderr -----