Skip to content

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

Changes to 6 files

Maximilian Roos333db17ade29
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index d57a8c317..0025c25e1 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -10,7 +10,7 @@ use super::context::CommandEnv;
use super::hooks::{HookFailureStrategy, HookPipeline};
use super::project_config::collect_commands_for_hooks;
use super::repository_ext::RepositoryCliExt;
-use super::worktree::{RemoveResult, handle_push};
+use super::worktree::{MergeOperations, RemoveResult, handle_push};
/// Context for collecting merge commands
struct MergeCommandCollector<'a> {
@@ -159,9 +159,11 @@ pub fn handle_merge(
Some(&target_branch),
false,
"Merged to",
- Some(committed),
- Some(squashed),
- Some(rebased),
+ Some(MergeOperations {
+ committed: Some(committed),
+ squashed: Some(squashed),
+ rebased: Some(rebased),
+ }),
)?;
// Get primary worktree path before cleanup (while we can still run git commands)
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 2aa0564bf..eb10aecc3 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -107,6 +107,14 @@ use super::command_executor::CommandContext;
use super::hooks::{HookFailureStrategy, HookPipeline};
use super::repository_ext::RepositoryCliExt;
+/// Flags indicating which merge operations occurred
+#[derive(Debug, Clone, Copy)]
+pub struct MergeOperations {
+ pub committed: Option<bool>,
+ pub squashed: Option<bool>,
+ pub rebased: Option<bool>,
+}
+
/// Result of a worktree switch operation
pub enum SwitchResult {
/// Switched to existing worktree at the given path
@@ -167,8 +175,8 @@ pub fn handle_switch(
// Switching back: swap current and previous
// history_before contains (A, B), we're switching from A to B
// After switch, record (B, A) so we can switch back to A
- if let Some((current, _previous)) = history_before {
- (resolved_branch.clone(), Some(current))
+ if let Some(history) = history_before {
+ (resolved_branch.clone(), Some(history.current))
} else {
// No history - shouldn't happen since "-" requires history
// But handle gracefully: just record where we're going
@@ -176,7 +184,7 @@ pub fn handle_switch(
}
} else {
// Normal switch: record new location as current, old current as previous
- let previous = history_before.map(|(current, _)| current);
+ let previous = history_before.map(|h| h.current);
(resolved_branch.clone(), previous)
};
@@ -436,9 +444,8 @@ impl<'a> CommandContext<'a> {
/// Push changes to target branch
///
-/// The `committed`, `squashed`, and `rebased` parameters are optional flags indicating
-/// whether those operations occurred in the merge workflow. Pass `None` for standalone
-/// push operations where these concepts don't apply.
+/// The `operations` parameter indicates which merge operations occurred (commit, squash, rebase).
+/// Pass `None` for standalone push operations where these concepts don't apply.
///
/// During the push stage we temporarily `git stash` non-overlapping changes in the
/// target worktree (if present) so that concurrent edits there do not block the
@@ -448,9 +455,7 @@ pub fn handle_push(
target: Option<&str>,
allow_merge_commits: bool,
verb: &str,
- committed: Option<bool>,
- squashed: Option<bool>,
- rebased: Option<bool>,
+ operations: Option<MergeOperations>,
) -> Result<(), GitError> {
let repo = Repository::current();
@@ -540,14 +545,14 @@ pub fn handle_push(
// Build parenthetical showing which operations didn't happen and flags used
let mut notes = Vec::new();
- // Skipped operations - only include if we're in merge workflow context (Some values)
- if committed.is_some() || squashed.is_some() || rebased.is_some() {
+ // Skipped operations - only include if we're in merge workflow context
+ if let Some(ops) = operations {
let mut skipped_ops = Vec::new();
- if !committed.unwrap_or(false) && !squashed.unwrap_or(false) {
+ if !ops.committed.unwrap_or(false) && !ops.squashed.unwrap_or(false) {
// Neither commit nor squash happened - combine them
skipped_ops.push("commit/squash");
}
- if !rebased.unwrap_or(false) {
+ if !ops.rebased.unwrap_or(false) {
skipped_ops.push("rebase");
}
if !skipped_ops.is_empty() {
@@ -633,12 +638,12 @@ pub fn handle_push(
))?;
} else {
// No commits to push - for merge workflow context, acknowledge operations that didn't happen
- let note = if committed.is_some() || squashed.is_some() || rebased.is_some() {
+ let note = if let Some(ops) = operations {
let mut notes = Vec::new();
- if !committed.unwrap_or(false) && !squashed.unwrap_or(false) {
+ if !ops.committed.unwrap_or(false) && !ops.squashed.unwrap_or(false) {
notes.push("no new commits");
}
- if !rebased.unwrap_or(false) {
+ if !ops.rebased.unwrap_or(false) {
notes.push("no rebase needed");
}
if notes.is_empty() {
diff --git a/src/git/mod.rs b/src/git/mod.rs
index dc3352525..8393c0a2d 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -33,6 +33,15 @@ pub enum HookType {
PostMerge,
}
+/// Switch history for ping-pong behavior between branches
+#[derive(Debug, Clone, PartialEq)]
+pub struct SwitchHistory {
+ /// The branch we switched to
+ pub current: String,
+ /// The branch we came from (for "-" to switch back)
+ pub previous: Option<String>,
+}
+
/// Worktree information
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Worktree {
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 5bcb1bc25..7f4ff901e 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -4,7 +4,9 @@ use std::process::{Command, Stdio};
use std::sync::OnceLock;
// Import types and functions from parent module (mod.rs)
-use super::{DefaultBranchName, DiffStats, GitError, LineDiff, Worktree, WorktreeList};
+use super::{
+ DefaultBranchName, DiffStats, GitError, LineDiff, SwitchHistory, Worktree, WorktreeList,
+};
/// Extension trait for Result types to simplify GitError conversions
///
@@ -243,9 +245,9 @@ impl Repository {
/// Get the previous branch from worktrunk.history.
///
- /// Returns (current, previous) if history is recorded.
- /// For single-value history (legacy), returns (value, None).
- pub fn get_switch_history(&self) -> Option<(String, Option<String>)> {
+ /// Returns history if recorded, where `current` is the branch we switched to
+ /// and `previous` is where we came from (for ping-pong "-" behavior).
+ pub fn get_switch_history(&self) -> Option<SwitchHistory> {
self.run_command(&["config", "--get", "worktrunk.history"])
.ok()
.and_then(|output| {
@@ -254,7 +256,10 @@ impl Repository {
return None;
}
let parts: Vec<&str> = trimmed.splitn(2, ',').collect();
- Some((parts[0].to_string(), parts.get(1).map(|s| s.to_string())))
+ Some(SwitchHistory {
+ current: parts[0].to_string(),
+ previous: parts.get(1).map(|s| s.to_string()),
+ })
})
}
@@ -279,7 +284,7 @@ impl Repository {
// Read from worktrunk.history (recorded by wt switch operations)
// History stores (current, previous), we want previous
self.get_switch_history()
- .and_then(|(_, prev)| prev)
+ .and_then(|h| h.previous)
.ok_or_else(|| {
GitError::message(
"No previous branch found in history. Use 'wt list' to see available worktrees.",
diff --git a/src/llm.rs b/src/llm.rs
index 70df398fb..8d7e6c209 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -6,6 +6,12 @@ use worktrunk::git::{GitError, Repository};
use minijinja::Environment;
+/// Context data for building LLM prompts
+struct PromptContext<'a> {
+ branch: &'a str,
+ repo_name: &'a str,
+}
+
/// Default template for commit message prompts
const DEFAULT_TEMPLATE: &str = r#"Format
- First line: <50 chars, present tense, describes WHAT and WHY (not HOW).
@@ -106,9 +112,8 @@ fn execute_llm_command(
fn build_commit_prompt(
config: &CommitGenerationConfig,
diff: &str,
- branch: &str,
recent_commits: Option<&Vec<String>>,
- repo_name: &str,
+ context: &PromptContext<'_>,
) -> Result<String, Box<dyn std::error::Error>> {
// Get template source
let template = match (&config.template, &config.template_file) {
@@ -140,9 +145,9 @@ fn build_commit_prompt(
let rendered = tmpl.render(minijinja::context! {
git_diff => diff,
- branch => branch,
+ branch => context.branch,
recent_commits => recent_commits.unwrap_or(&vec![]),
- repo => repo_name,
+ repo => context.repo_name,
})?;
Ok(rendered)
@@ -153,8 +158,7 @@ fn build_squash_prompt(
config: &CommitGenerationConfig,
target_branch: &str,
commits: &[String],
- current_branch: &str,
- repo_name: &str,
+ context: &PromptContext<'_>,
) -> Result<String, Box<dyn std::error::Error>> {
// Get template source
let template = match (&config.squash_template, &config.squash_template_file) {
@@ -192,8 +196,8 @@ fn build_squash_prompt(
let rendered = tmpl.render(minijinja::context! {
target_branch => target_branch,
commits => commits_reversed,
- branch => current_branch,
- repo => repo_name,
+ branch => context.branch,
+ repo => context.repo_name,
})?;
Ok(rendered)
@@ -281,13 +285,11 @@ fn try_generate_commit_message(
});
// Build prompt from template
- let prompt = build_commit_prompt(
- config,
- &diff_output,
- &current_branch,
- recent_commits.as_ref(),
+ let context = PromptContext {
+ branch: &current_branch,
repo_name,
- )?;
+ };
+ let prompt = build_commit_prompt(config, &diff_output, recent_commits.as_ref(), &context)?;
execute_llm_command(command, args, &prompt)
}
@@ -303,13 +305,12 @@ pub fn generate_squash_message(
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
- let prompt = build_squash_prompt(
- commit_generation_config,
- target_branch,
- subjects,
- current_branch,
+ let context = PromptContext {
+ branch: current_branch,
repo_name,
- )?;
+ };
+ let prompt =
+ build_squash_prompt(commit_generation_config, target_branch, subjects, &context)?;
return execute_llm_command(command, &commit_generation_config.args, &prompt);
}
@@ -330,7 +331,11 @@ mod tests {
#[test]
fn test_build_commit_prompt_with_default_template() {
let config = CommitGenerationConfig::default();
- let result = build_commit_prompt(&config, "diff content", "main", None, "myrepo");
+ let context = PromptContext {
+ branch: "main",
+ repo_name: "myrepo",
+ };
+ let result = build_commit_prompt(&config, "diff content", None, &context);
assert!(result.is_ok());
let prompt = result.unwrap();
assert!(prompt.contains("diff content"));
@@ -342,7 +347,11 @@ mod tests {
fn test_build_commit_prompt_with_recent_commits() {
let config = CommitGenerationConfig::default();
let commits = vec!["feat: add feature".to_string(), "fix: bug".to_string()];
- let result = build_commit_prompt(&config, "diff", "main", Some(&commits), "repo");
+ let context = PromptContext {
+ branch: "main",
+ repo_name: "repo",
+ };
+ let result = build_commit_prompt(&config, "diff", Some(&commits), &context);
assert!(result.is_ok());
let prompt = result.unwrap();
assert!(prompt.contains("feat: add feature"));
@@ -354,7 +363,11 @@ mod tests {
fn test_build_commit_prompt_empty_recent_commits() {
let config = CommitGenerationConfig::default();
let commits = vec![];
- let result = build_commit_prompt(&config, "diff", "main", Some(&commits), "repo");
+ let context = PromptContext {
+ branch: "main",
+ repo_name: "repo",
+ };
+ let result = build_commit_prompt(&config, "diff", Some(&commits), &context);
assert!(result.is_ok());
// Should not render the recent commits section if empty
let prompt = result.unwrap();
@@ -371,7 +384,11 @@ mod tests {
squash_template: None,
squash_template_file: None,
};
- let result = build_commit_prompt(&config, "my diff", "feature", None, "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_commit_prompt(&config, "my diff", None, &context);
assert!(result.is_ok());
assert_eq!(result.unwrap(), "Branch: feature\nDiff: my diff");
}
@@ -386,7 +403,11 @@ mod tests {
squash_template: None,
squash_template_file: None,
};
- let result = build_commit_prompt(&config, "diff", "main", None, "repo");
+ let context = PromptContext {
+ branch: "main",
+ repo_name: "repo",
+ };
+ let result = build_commit_prompt(&config, "diff", None, &context);
assert!(result.is_err());
}
@@ -400,7 +421,11 @@ mod tests {
squash_template: None,
squash_template_file: None,
};
- let result = build_commit_prompt(&config, "diff", "main", None, "repo");
+ let context = PromptContext {
+ branch: "main",
+ repo_name: "repo",
+ };
+ let result = build_commit_prompt(&config, "diff", None, &context);
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "Template is empty");
}
@@ -419,7 +444,11 @@ mod tests {
squash_template_file: None,
};
let commits = vec!["commit1".to_string(), "commit2".to_string()];
- let result = build_commit_prompt(&config, "my diff", "feature", Some(&commits), "myrepo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "myrepo",
+ };
+ let result = build_commit_prompt(&config, "my diff", Some(&commits), &context);
assert!(result.is_ok());
let prompt = result.unwrap();
assert_eq!(
@@ -432,7 +461,11 @@ mod tests {
fn test_build_squash_prompt_with_default_template() {
let config = CommitGenerationConfig::default();
let commits = vec!["feat: A".to_string(), "fix: B".to_string()];
- let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_squash_prompt(&config, "main", &commits, &context);
assert!(result.is_ok());
let prompt = result.unwrap();
// Commits should be reversed (chronological order: B first, then A)
@@ -455,7 +488,11 @@ mod tests {
squash_template_file: None,
};
let commits = vec!["A".to_string(), "B".to_string()];
- let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_squash_prompt(&config, "main", &commits, &context);
assert!(result.is_ok());
// Commits are reversed, so chronological order is B, A
assert_eq!(result.unwrap(), "Target: main\nB\nA\n");
@@ -465,7 +502,11 @@ mod tests {
fn test_build_squash_prompt_empty_commits() {
let config = CommitGenerationConfig::default();
let commits = vec![];
- let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_squash_prompt(&config, "main", &commits, &context);
assert!(result.is_ok());
}
@@ -479,7 +520,11 @@ mod tests {
squash_template: Some("{% for x in commits %}{{ x }".to_string()),
squash_template_file: None,
};
- let result = build_squash_prompt(&config, "main", &[], "feature", "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_squash_prompt(&config, "main", &[], &context);
assert!(result.is_err());
}
@@ -493,7 +538,11 @@ mod tests {
squash_template: Some(" \n ".to_string()),
squash_template_file: None,
};
- let result = build_squash_prompt(&config, "main", &[], "feature", "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_squash_prompt(&config, "main", &[], &context);
assert!(result.is_err());
assert_eq!(result.unwrap_err().to_string(), "Squash template is empty");
}
@@ -512,7 +561,11 @@ mod tests {
squash_template_file: None,
};
let commits = vec!["A".to_string(), "B".to_string()];
- let result = build_squash_prompt(&config, "main", &commits, "feature", "myrepo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "myrepo",
+ };
+ let result = build_squash_prompt(&config, "main", &commits, &context);
assert!(result.is_ok());
let prompt = result.unwrap();
assert_eq!(
@@ -552,13 +605,11 @@ Diff follows:
"fix: bug".to_string(),
"docs: update".to_string(),
];
- let result = build_commit_prompt(
- &config,
- "my diff content",
- "feature-x",
- Some(&commits),
- "myapp",
- );
+ let context = PromptContext {
+ branch: "feature-x",
+ repo_name: "myapp",
+ };
+ let result = build_commit_prompt(&config, "my diff content", Some(&commits), &context);
assert!(result.is_ok());
let prompt = result.unwrap();
@@ -599,7 +650,11 @@ No recent commits
squash_template: None,
squash_template_file: None,
};
- let result = build_commit_prompt(&config, "diff", "main", None, "test");
+ let context = PromptContext {
+ branch: "main",
+ repo_name: "test",
+ };
+ let result = build_commit_prompt(&config, "diff", None, &context);
assert!(result.is_ok());
let prompt = result.unwrap();
@@ -637,7 +692,11 @@ Single commit: {{ commits[0] }}
"commit B".to_string(),
"commit C".to_string(),
];
- let result = build_squash_prompt(&config, "main", &commits, "feature", "repo");
+ let context = PromptContext {
+ branch: "feature",
+ repo_name: "repo",
+ };
+ let result = build_squash_prompt(&config, "main", &commits, &context);
assert!(result.is_ok());
let prompt = result.unwrap();
@@ -650,7 +709,7 @@ Single commit: {{ commits[0] }}
// Test with single commit
let single_commit = vec!["solo commit".to_string()];
- let result = build_squash_prompt(&config, "main", &single_commit, "feature", "repo");
+ let result = build_squash_prompt(&config, "main", &single_commit, &context);
assert!(result.is_ok());
let prompt = result.unwrap();
diff --git a/src/main.rs b/src/main.rs
index 8d0d505a9..96913e0d4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -171,14 +171,7 @@ fn main() {
StandaloneCommand::Push {
target,
allow_merge_commits,
- } => handle_push(
- target.as_deref(),
- allow_merge_commits,
- "Pushed to",
- None,
- None,
- None,
- ),
+ } => handle_push(target.as_deref(), allow_merge_commits, "Pushed to", None),
StandaloneCommand::Rebase { target } => handle_rebase(target.as_deref()).map(|_| ()),
StandaloneCommand::AskApprovals { force, all } => {
handle_standalone_ask_approvals(force, all)