Skip to content

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

Add --show-prompt flag to step commit and squash commands (#187)

Maximilian Roosea184717470b
diff --git a/src/cli.rs b/src/cli.rs
index c11ecc453..7b3270f92 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -887,6 +887,12 @@ pub enum StepCommand {
/// What to stage before committing [default: all]
#[arg(long)]
stage: Option<crate::commands::commit::StageMode>,
+
+ /// Show prompt without running LLM
+ ///
+ /// Outputs the rendered prompt to stdout for debugging or manual piping.
+ #[arg(long)]
+ show_prompt: bool,
},
/// Squash commits down to target
@@ -910,6 +916,12 @@ pub enum StepCommand {
/// What to stage before committing [default: all]
#[arg(long)]
stage: Option<crate::commands::commit::StageMode>,
+
+ /// Show prompt without running LLM
+ ///
+ /// Outputs the rendered prompt to stdout for debugging or manual piping.
+ #[arg(long)]
+ show_prompt: bool,
},
/// Push changes to local target branch
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index ca7d480d0..81215a941 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -34,7 +34,7 @@ pub use merge::{execute_pre_remove_commands, handle_merge};
pub use select::handle_select;
pub use standalone::{
RebaseResult, SquashResult, add_approvals, clear_approvals, handle_hook_show, handle_rebase,
- handle_squash, run_hook, step_commit,
+ handle_squash, run_hook, step_commit, step_show_squash_prompt,
};
pub use worktree::{
compute_worktree_path, handle_remove, handle_remove_by_path, handle_remove_current,
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 96bf0cd86..6d4697f41 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -142,9 +142,18 @@ pub fn step_commit(
force: bool,
no_verify: bool,
stage_mode: super::commit::StageMode,
+ show_prompt: bool,
) -> anyhow::Result<()> {
use super::command_approval::approve_hooks;
+ // Handle --show-prompt early: just build and output the prompt
+ if show_prompt {
+ let config = WorktrunkConfig::load().context("Failed to load config")?;
+ let prompt = crate::llm::build_commit_prompt(&config.commit_generation)?;
+ crate::output::data(prompt)?;
+ return Ok(());
+ }
+
let env = CommandEnv::for_action("commit")?;
let ctx = env.context(force);
@@ -398,6 +407,47 @@ pub fn handle_squash(
Ok(SquashResult::Squashed)
}
+/// Handle `wt step squash --show-prompt`
+///
+/// Builds and outputs the squash prompt without running the LLM or squashing.
+pub fn step_show_squash_prompt(
+ target: Option<&str>,
+ config: &worktrunk::config::CommitGenerationConfig,
+) -> anyhow::Result<()> {
+ let repo = Repository::current();
+
+ // Get target branch (default to default branch if not provided)
+ let target_branch = repo.resolve_target_branch(target)?;
+
+ // Get current branch
+ let current_branch = repo.current_branch()?.unwrap_or_else(|| "HEAD".to_string());
+
+ // Get merge base with target branch
+ let merge_base = repo.merge_base("HEAD", &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 = repo.worktree_root()?;
+ let repo_name = repo_root
+ .file_name()
+ .and_then(|n| n.to_str())
+ .unwrap_or("repo");
+
+ let prompt = crate::llm::build_squash_prompt(
+ &target_branch,
+ &merge_base,
+ &subjects,
+ &current_branch,
+ repo_name,
+ config,
+ )?;
+ crate::output::data(prompt)?;
+ Ok(())
+}
+
/// Result of a rebase operation
pub enum RebaseResult {
/// Rebase occurred (either true rebase or fast-forward)
diff --git a/src/llm.rs b/src/llm.rs
index 69fd3d3c8..019f3badd 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -192,6 +192,24 @@ fn format_command_display(command: &str, args: &[String]) -> String {
}
}
+/// Get recent commit subjects for style reference.
+///
+/// If `start_ref` is provided, gets commits starting from that ref (exclusive).
+/// Otherwise gets commits from HEAD.
+fn get_recent_commits(repo: &Repository, start_ref: Option<&str>) -> Option<Vec<String>> {
+ let mut args = vec!["log", "--pretty=format:%s", "-n", "5", "--no-merges"];
+ if let Some(ref_name) = start_ref {
+ args.push(ref_name);
+ }
+ repo.run_command(&args).ok().and_then(|output| {
+ if output.trim().is_empty() {
+ None
+ } else {
+ Some(output.lines().map(String::from).collect())
+ }
+ })
+}
+
/// Default template for commit message prompts
///
/// Synced to dev/config.example.toml by `cargo test readme_sync`
@@ -458,6 +476,15 @@ fn try_generate_commit_message(
args: &[String],
config: &CommitGenerationConfig,
) -> anyhow::Result<String> {
+ let prompt = build_commit_prompt(config)?;
+ execute_llm_command(command, args, &prompt)
+}
+
+/// 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 fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<String> {
let repo = Repository::current();
// Get staged diff and diffstat
@@ -487,19 +514,8 @@ fn try_generate_commit_message(
.and_then(|n| n.to_str())
.unwrap_or("repo");
- // Get recent commit messages for style reference
- let recent_commits = repo
- .run_command(&["log", "--pretty=format:%s", "-n", "5", "--no-merges"])
- .ok()
- .and_then(|output| {
- if output.trim().is_empty() {
- None
- } else {
- Some(output.lines().map(String::from).collect::<Vec<_>>())
- }
- });
+ let recent_commits = get_recent_commits(&repo, None);
- // Build prompt from template
let context = TemplateContext {
git_diff: &prepared.diff,
git_diff_stat: &prepared.stat,
@@ -509,9 +525,7 @@ fn try_generate_commit_message(
commits: &[],
target_branch: None,
};
- let prompt = build_prompt(config, TemplateType::Commit, &context)?;
-
- execute_llm_command(command, args, &prompt)
+ build_prompt(config, TemplateType::Commit, &context)
}
pub fn generate_squash_message(
@@ -527,54 +541,14 @@ pub fn generate_squash_message(
let command = commit_generation_config.command.as_ref().unwrap();
let args = &commit_generation_config.args;
- // Get the combined diff and diffstat for all commits being squashed
- // Use -c flags to ensure consistent format regardless of user's git config
- let repo = Repository::current();
- let diff_output = repo.run_command(&[
- "-c",
- "diff.noprefix=false",
- "-c",
- "diff.mnemonicPrefix=false",
- "--no-pager",
- "diff",
+ let prompt = build_squash_prompt(
+ target_branch,
merge_base,
- "HEAD",
- ])?;
- let diff_stat = repo.run_command(&["--no-pager", "diff", merge_base, "HEAD", "--stat"])?;
-
- // Prepare diff (may filter if too large)
- let prepared = prepare_diff(diff_output, diff_stat);
-
- // Get recent commit messages for style reference (from before the commits being squashed)
- let recent_commits = repo
- .run_command(&[
- "log",
- "--pretty=format:%s",
- "-n",
- "5",
- "--no-merges",
- merge_base,
- ])
- .ok()
- .and_then(|output| {
- if output.trim().is_empty() {
- None
- } else {
- Some(output.lines().map(String::from).collect::<Vec<_>>())
- }
- });
-
- // Build prompt from template with all variables
- let context = TemplateContext {
- git_diff: &prepared.diff,
- git_diff_stat: &prepared.stat,
- branch: current_branch,
- recent_commits: recent_commits.as_ref(),
+ subjects,
+ current_branch,
repo_name,
- commits: subjects,
- target_branch: Some(target_branch),
- };
- let prompt = build_prompt(commit_generation_config, TemplateType::Squash, &context)?;
+ commit_generation_config,
+ )?;
return execute_llm_command(command, args, &prompt).map_err(|e| {
worktrunk::git::GitError::LlmCommandFailed {
@@ -595,6 +569,50 @@ pub fn generate_squash_message(
Ok(commit_message)
}
+/// Build the squash prompt from commits being squashed.
+///
+/// Gathers the combined diff, commit subjects, branch names, and recent commits, then
+/// renders the prompt template. Used by both normal squash generation and `--show-prompt`.
+pub fn build_squash_prompt(
+ target_branch: &str,
+ merge_base: &str,
+ subjects: &[String],
+ current_branch: &str,
+ repo_name: &str,
+ config: &CommitGenerationConfig,
+) -> anyhow::Result<String> {
+ let repo = Repository::current();
+
+ // Get the combined diff and diffstat for all commits being squashed
+ // Use -c flags to ensure consistent format regardless of user's git config
+ let diff_output = repo.run_command(&[
+ "-c",
+ "diff.noprefix=false",
+ "-c",
+ "diff.mnemonicPrefix=false",
+ "--no-pager",
+ "diff",
+ merge_base,
+ "HEAD",
+ ])?;
+ let diff_stat = repo.run_command(&["--no-pager", "diff", merge_base, "HEAD", "--stat"])?;
+
+ // Prepare diff (may filter if too large)
+ let prepared = prepare_diff(diff_output, diff_stat);
+
+ let recent_commits = get_recent_commits(&repo, Some(merge_base));
+ let context = TemplateContext {
+ git_diff: &prepared.diff,
+ git_diff_stat: &prepared.stat,
+ branch: current_branch,
+ recent_commits: recent_commits.as_ref(),
+ repo_name,
+ commits: subjects,
+ target_branch: Some(target_branch),
+ };
+ build_prompt(config, TemplateType::Squash, &context)
+}
+
/// Synthetic diff for testing commit generation
const SYNTHETIC_DIFF: &str = r#"diff --git a/src/main.rs b/src/main.rs
index abc1234..def5678 100644
diff --git a/src/main.rs b/src/main.rs
index 25d19413e..8237ae15c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1010,19 +1010,21 @@ fn main() {
force,
verify,
stage,
+ show_prompt,
} => WorktrunkConfig::load()
.context("Failed to load config")
.and_then(|config| {
let stage_final = stage
.or_else(|| config.commit.and_then(|c| c.stage))
.unwrap_or_default();
- step_commit(force, !verify, stage_final)
+ step_commit(force, !verify, stage_final, show_prompt)
}),
StepCommand::Squash {
target,
force,
verify,
stage,
+ show_prompt,
} => WorktrunkConfig::load()
.context("Failed to load config")
.and_then(|config| {
@@ -1030,6 +1032,14 @@ fn main() {
.or_else(|| config.commit.and_then(|c| c.stage))
.unwrap_or_default();
+ // Handle --show-prompt early: just build and output the prompt
+ if show_prompt {
+ return commands::step_show_squash_prompt(
+ target.as_deref(),
+ &config.commit_generation,
+ );
+ }
+
// "Approve at the Gate": approve pre-commit hooks upfront (unless --no-verify)
// Shadow verify: if user declines approval, skip hooks but continue squash
let verify = if verify {
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index e7e60e51f..9a6af2cb6 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2603,3 +2603,52 @@ fn test_merge_error_conflicting_changes_in_target(mut repo_with_alternate_primar
Some(&feature_wt),
);
}
+
+// =============================================================================
+// --show-prompt tests
+// =============================================================================
+
+#[rstest]
+fn test_step_commit_show_prompt(repo: TestRepo) {
+ // Create some staged changes so there's a diff to include in the prompt
+ fs::write(repo.root_path().join("new_file.txt"), "new content").expect("Failed to write file");
+ repo.git_command(&["add", "new_file.txt"]);
+
+ // The prompt should be written to stdout
+ snapshot_step_commit_with_env(
+ "step_commit_show_prompt",
+ &repo,
+ &["--show-prompt"],
+ None,
+ &[],
+ );
+}
+
+#[rstest]
+fn test_step_commit_show_prompt_no_staged_changes(repo: TestRepo) {
+ // No staged changes - should still output the prompt (with empty diff)
+ snapshot_step_commit_with_env(
+ "step_commit_show_prompt_no_staged",
+ &repo,
+ &["--show-prompt"],
+ None,
+ &[],
+ );
+}
+
+#[rstest]
+fn test_step_squash_show_prompt(repo_with_multi_commit_feature: TestRepo) {
+ let repo = repo_with_multi_commit_feature;
+
+ // Get the feature worktree path
+ let feature_wt = repo.worktree_path("feature");
+
+ // Should output the squash prompt with commits and diff
+ snapshot_step_squash_with_env(
+ "step_squash_show_prompt",
+ &repo,
+ &["--show-prompt"],
+ Some(feature_wt),
+ &[],
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap
new file mode 100644
index 000000000..71ce044fd
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt.snap
@@ -0,0 +1,58 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - commit
+ - "--show-prompt"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Write a commit message for the staged changes below.
+
+<format>
+- Subject under 50 chars, blank line, then optional body
+- 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>
+
+</diffstat>
+
+<diff>
+
+</diff>
+
+<context>
+Branch: main
+<recent_commits>
+- Initial commit
+</recent_commits>
+</context>
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged.snap
new file mode 100644
index 000000000..71ce044fd
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_show_prompt_no_staged.snap
@@ -0,0 +1,58 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - commit
+ - "--show-prompt"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Write a commit message for the staged changes below.
+
+<format>
+- Subject under 50 chars, blank line, then optional body
+- 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>
+
+</diffstat>
+
+<diff>
+
+</diff>
+
+<context>
+Branch: main
+<recent_commits>
+- Initial commit
+</recent_commits>
+</context>
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap b/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
new file mode 100644
index 000000000..fae7bc8b8
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__step_squash_show_prompt.snap
@@ -0,0 +1,75 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - step
+ - squash
+ - "--show-prompt"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+Combine these commits into a single commit message.
+
+<format>
+- Subject under 50 chars, blank line, then optional body
+- 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>
+
+----- stderr -----