Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Simplify CI to use pre-commit action and pre-merge hook (#135)
Maximilian Roos7d469550eb2b
diff --git a/.config/wt.toml b/.config/wt.tomlindex 2a60d3928..32bf864bc 100644--- a/.config/wt.toml+++ b/.config/wt.toml@@ -42,4 +42,5 @@ pre-commit = "pre-commit run --all-files"# a TOML table section, and everything after it would be inside that section[pre-merge]insta = "RUSTFLAGS='-D warnings' NEXTEST_STATUS_LEVEL=fail NEXTEST_SUCCESS_OUTPUT=never cargo insta test --dnd --check --features shell-integration-tests"+doctest = "cargo test --doc"doc = "RUSTDOCFLAGS='-Dwarnings' cargo doc --no-deps"diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yamlindex c1c8c7102..0095277ab 100644--- a/.github/workflows/ci.yaml+++ b/.github/workflows/ci.yaml@@ -61,42 +61,30 @@ jobs:echo "Using Git Bash for Windows tests"shell: pwsh- - name: π Compile- uses: clechasseur/rs-cargo@v4- with:- command: test- args: --no-run --locked --features shell-integration-tests-- - name: π Test- uses: clechasseur/rs-cargo@v4- timeout-minutes: 10- with:- command: insta- args: test --test-runner=nextest --features shell-integration-tests-- - name: π Doctest- uses: clechasseur/rs-cargo@v4- with:- command: test- args: --doc --locked-- - name: π Clippy- uses: clechasseur/rs-cargo@v4- with:- command: clippy- args: --all-targets --all-features -- -D warnings-- - name: β¨οΈ Fmt- uses: clechasseur/rs-cargo@v4+ - name: Setup Python for pre-commit+ uses: actions/setup-python@v5with:- command: fmt- args: --all --check+ python-version: '3.12'- - name: ποΈ Doc- uses: clechasseur/rs-cargo@v4- with:- command: doc- args: --no-deps+ - name: π Pre-commit hooks+ run: |+ pip install pre-commit+ pre-commit run --all-files+ env:+ # Skip lychee - the dedicated check-links job handles link checking+ SKIP: lychee++ # TODO: Restore after next release (published wt doesn't have --force flag yet)+ # # TODO: This installs from crates.io, not from the PR code. We should install from the+ # # local checkout instead, but baptiste0928/cargo-install doesn't support local paths.+ # # For now, pre-merge hooks run against the published version, not the PR changes.+ # - name: Install wt+ # uses: baptiste0928/cargo-install@v3+ # with:+ # crate: worktrunk+ #+ # - name: π§ͺ Pre-merge hooks+ # run: wt hook pre-merge --forcecheck-links:runs-on: ubuntu-latestdiff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex ec834ed2e..1b1a383de 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -25,7 +25,7 @@ repos:rev: v1.0.1hooks:- id: clippy- args: ["--all-targets", "--", "-D", "warnings"]+ args: ["--all-targets", "--all-features", "--", "-D", "warnings"]- repo: https://github.com/lycheeverse/lycheerev: lychee-v0.22.0hooks:diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex bc1716aa9..6dfdb0a39 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -17,7 +17,8 @@ pub struct PreparedCommand {pub struct CommandContext<'a> {pub repo: &'a Repository,pub config: &'a WorktrunkConfig,- pub branch: &'a str,+ /// Current branch name, if on a branch (None in detached HEAD state).+ pub branch: Option<&'a str>,pub worktree_path: &'a Path,pub repo_root: &'a Path,pub force: bool,@@ -27,7 +28,7 @@ impl<'a> CommandContext<'a> {pub fn new(repo: &'a Repository,config: &'a WorktrunkConfig,- branch: &'a str,+ branch: Option<&'a str>,worktree_path: &'a Path,repo_root: &'a Path,force: bool,@@ -41,6 +42,11 @@ impl<'a> CommandContext<'a> {force,}}++ /// Get branch name, using "HEAD" as fallback for detached HEAD state.+ pub fn branch_or_head(&self) -> &str {+ self.branch.unwrap_or("HEAD")+ }}/// Build hook context as a HashMap for JSON serialization and template expansion.@@ -66,7 +72,7 @@ pub fn build_hook_context(let mut map = HashMap::new();map.insert("repo".into(), repo_name.into());- map.insert("branch".into(), sanitize_branch_name(ctx.branch));+ map.insert("branch".into(), sanitize_branch_name(ctx.branch_or_head()));map.insert("worktree".into(), worktree.into());map.insert("worktree_name".into(), worktree_name.into());map.insert("repo_root".into(), repo_root.to_string_lossy().into());@@ -89,7 +95,9 @@ pub fn build_hook_context(if let Ok(url) = ctx.repo.run_command(&["remote", "get-url", &remote]) {map.insert("remote_url".into(), url.trim().into());}- if let Ok(Some(upstream)) = ctx.repo.upstream_branch(ctx.branch) {+ if let Some(branch) = ctx.branch+ && let Ok(Some(upstream)) = ctx.repo.upstream_branch(branch)+ {map.insert("upstream".into(), upstream);}}@@ -132,14 +140,16 @@ fn expand_commands(let mut result = Vec::new();for cmd in commands {- let expanded_str = expand_template(&cmd.template, repo_name, ctx.branch, &extras_ref)- .map_err(|e| {- anyhow::anyhow!(- "Failed to expand command template '{}': {}",- cmd.template,- e- )- })?;+ let expanded_str =+ expand_template(&cmd.template, repo_name, ctx.branch_or_head(), &extras_ref).map_err(+ |e| {+ anyhow::anyhow!(+ "Failed to expand command template '{}': {}",+ cmd.template,+ e+ )+ },+ )?;// Build per-command JSON with hook_type and hook_namelet mut cmd_context = base_context.clone();diff --git a/src/commands/context.rs b/src/commands/context.rsindex 331eb077f..3395750b5 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -17,7 +17,8 @@ use super::command_executor::CommandContext;/// broader contexts without forcing config loads or branch resolution.pub struct CommandEnv {pub repo: Repository,- pub branch: String,+ /// Current branch name, if on a branch (None in detached HEAD state).+ pub branch: Option<String>,pub config: WorktrunkConfig,pub worktree_path: PathBuf,pub repo_root: PathBuf,@@ -35,6 +36,29 @@ impl CommandEnv {let config = WorktrunkConfig::load().context("Failed to load config")?;let repo_root = repo.worktree_base()?;+ Ok(Self {+ repo,+ branch: Some(branch),+ config,+ worktree_path,+ repo_root,+ })+ }++ /// Load the command environment without requiring a branch.+ ///+ /// Use this for commands that can operate in detached HEAD state,+ /// such as running hooks (where `{{ branch }}` expands to "HEAD" if detached).+ pub fn for_action_branchless() -> anyhow::Result<Self> {+ let repo = Repository::current();+ let worktree_path = std::env::current_dir().context("Failed to get current directory")?;+ // Propagate git errors (broken repo, missing git) but allow None for detached HEAD+ let branch = repo+ .current_branch()+ .context("Failed to determine current branch")?;+ let config = WorktrunkConfig::load().context("Failed to load config")?;+ let repo_root = repo.worktree_base()?;+Ok(Self {repo,branch,@@ -49,10 +73,20 @@ impl CommandEnv {CommandContext::new(&self.repo,&self.config,- &self.branch,+ self.branch.as_deref(),&self.worktree_path,&self.repo_root,force,)}++ /// Get branch name, returning error if in detached HEAD state.+ pub fn require_branch(&self, action: &str) -> anyhow::Result<&str> {+ self.branch.as_deref().ok_or_else(|| {+ worktrunk::git::GitError::DetachedHead {+ action: Some(action.into()),+ }+ .into()+ })+ }}diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 34f7120f5..e91fc3e4d 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -67,7 +67,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {let wt_repo = Repository::at(&wt.path);// Build full hook context for this worktree- let ctx = CommandContext::new(&wt_repo, &config, branch, &wt.path, &repo_root, false);+ let ctx = CommandContext::new(&wt_repo, &config, Some(branch), &wt.path, &repo_root, false);let context_map = build_hook_context(&ctx, &[]);// Convert to &str references for expand_templatediff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex d906dc4e2..00217f6bd 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -228,7 +228,7 @@ impl<'a> HookPipeline<'a> {self.ctx.repo,self.ctx.worktree_path,&prepared.expanded,- self.ctx.branch,+ self.ctx.branch_or_head(),&operation,Some(&prepared.context_json),) {diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex d654b5ecf..5e13802d1 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -84,7 +84,8 @@ pub fn handle_merge(let env = CommandEnv::for_action("merge")?;let repo = &env.repo;let config = &env.config;- let current_branch = env.branch.clone();+ // Merge requires being on a branch (can't merge from detached HEAD)+ let current_branch = env.require_branch("merge")?.to_string();// Validate --no-commit: requires clean working treeif !commit && repo.is_dirty()? {@@ -242,7 +243,7 @@ pub fn handle_merge(let ctx = CommandContext::new(&destination_repo,config,- ¤t_branch,+ Some(¤t_branch),&destination_path,&destination_repo_root,force,diff --git a/src/commands/standalone.rs b/src/commands/standalone.rsindex f23a10ad2..9cf611c5e 100644--- a/src/commands/standalone.rs+++ b/src/commands/standalone.rs@@ -24,11 +24,13 @@ use super::repository_ext::RepositoryCliExt;////// When explicitly invoking hooks, ALL hooks run (both user and project)./// There's no skip flag - if you explicitly run hooks, all configured hooks run.+///+/// Works in detached HEAD state - `{{ branch }}` template variable will be "HEAD".pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) -> anyhow::Result<()> {use super::command_approval::approve_hooks_filtered;- // Derive context from current environment- let env = CommandEnv::for_action(&format!("run {hook_type} hook"))?;+ // Derive context from current environment (branch-optional for CI compatibility)+ let env = CommandEnv::for_action_branchless()?;let repo = &env.repo;let ctx = env.context(force);@@ -104,11 +106,11 @@ pub fn run_hook(hook_type: HookType, force: bool, name_filter: Option<&str>) ->// which already handle user hooks (approval already happened at gate)// Use current branch as target (matches approval prompt for wt hook)let project_cfg = project_config.unwrap_or_default();- run_pre_merge_commands(&project_cfg, &ctx, &env.branch, name_filter)+ run_pre_merge_commands(&project_cfg, &ctx, ctx.branch_or_head(), name_filter)}HookType::PostMerge => {// Use current branch as target (matches approval prompt for wt hook)- execute_post_merge_commands(&ctx, &env.branch, name_filter)+ execute_post_merge_commands(&ctx, ctx.branch_or_head(), name_filter)}HookType::PreRemove => execute_pre_remove_commands(&ctx, name_filter),}@@ -259,7 +261,8 @@ pub fn handle_squash(let env = CommandEnv::for_action("squash")?;let repo = &env.repo;- let current_branch = env.branch.clone();+ // Squash requires being on a branch (can't squash in detached HEAD)+ let current_branch = env.require_branch("squash")?.to_string();let ctx = env.context(force);let generator = CommitGenerator::new(&env.config.commit_generation);@@ -671,8 +674,9 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyho// Build context for template expansion (only used if --expanded)// Need to keep CommandEnv alive for the lifetime of ctx+ // Uses branchless mode - template expansion uses "HEAD" in detached HEAD statelet env = if expanded {- Some(CommandEnv::for_action("show hooks")?)+ Some(CommandEnv::for_action_branchless()?)} else {None};@@ -891,7 +895,7 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook}HookType::PreMerge | HookType::PostMerge => {// Pre-merge and post-merge use current branch as target- vec![("target", ctx.branch)]+ vec![("target", ctx.branch_or_head())]}_ => Vec::new(),};@@ -904,7 +908,7 @@ fn expand_command_template(template: &str, ctx: &CommandContext, hook_type: Hook.file_name().and_then(|n| n.to_str()).unwrap_or("unknown"),- ctx.branch,+ ctx.branch_or_head(),&template_ctx.iter().map(|(k, v)| (k.as_str(), v.as_str()))diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 1ad9379da..e639f6aa9 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -489,7 +489,7 @@ pub fn handle_switch(let ctx = CommandContext::new(&repo,config,- &resolved_branch,+ Some(&resolved_branch),&worktree_path,&repo_root,force,diff --git a/src/main.rs b/src/main.rsindex a7665130e..be997432c 100644--- a/src/main.rs+++ b/src/main.rs@@ -1072,7 +1072,7 @@ fn main() {let ctx = CommandContext::new(&repo,&config,- &branch,+ Some(&branch),&worktree_path,&repo_root,force,@@ -1114,7 +1114,7 @@ fn main() {let ctx = CommandContext::new(&repo,&config,- &resolved_branch,+ Some(&resolved_branch),path,&repo_root,force,@@ -1159,11 +1159,12 @@ fn main() {let worktree_path =std::env::current_dir().context("Failed to get current directory")?;let repo_root = repo.worktree_base()?;- let current_branch = repo.current_branch()?.unwrap_or_default();+ // Keep as Option so detached HEAD maps to None -> "HEAD" via branch_or_head()+ let current_branch = repo.current_branch()?;let ctx = CommandContext::new(&repo,&config,- ¤t_branch,+ current_branch.as_deref(),&worktree_path,&repo_root,force,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex a545fbbf1..e27f0a7f0 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -476,14 +476,13 @@ fn handle_removed_worktree_output(// Execute pre-remove hooks in the worktree being removed// Non-zero exit aborts removal (FailFast strategy)- // For detached HEAD, branch expands to empty string in templates+ // For detached HEAD, {{ branch }} expands to "HEAD" in templatesif verify && let Ok(config) = WorktrunkConfig::load() {let target_repo = Repository::at(worktree_path);- let hook_branch = branch_name.unwrap_or("");let ctx = CommandContext::new(&target_repo,&config,- hook_branch,+ branch_name,worktree_path,main_path,false, // force=false for CommandContext (not approval-related)diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex e0de9f7df..0e61c933c 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1173,12 +1173,12 @@ approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]String::from_utf8_lossy(&output.stderr));- // Verify {{ branch }} expanded to empty string+ // Verify {{ branch }} expanded to "HEAD" (fallback for detached HEAD state)let content =std::fs::read_to_string(&branch_file).expect("Hook should have created the branch file");assert_eq!(content.trim(),- "branch=",- "{{ branch }} should expand to empty string for detached HEAD worktrees"+ "branch=HEAD",+ "{{ branch }} should expand to 'HEAD' for detached HEAD worktrees");}