Skip to content

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

Move project config and status loading to Repository

Maximilian Roosede4b6f9c932
diff --git a/src/commands/commit.rs b/src/commands/commit.rs
index eb0eb03f0..991bd4fbb 100644
--- a/src/commands/commit.rs
+++ b/src/commands/commit.rs
@@ -5,7 +5,7 @@ use worktrunk::styling::{AnstyleStyle, CYAN, GREEN, HINT, WARNING, format_with_g
use super::command_executor::CommandContext;
use super::hooks::{HookFailureStrategy, HookPipeline};
-use super::project_config::load_project_config;
+use super::project_config::ProjectConfigRepoExt;
/// Options for committing current changes.
pub struct CommitOptions<'a> {
@@ -153,7 +153,7 @@ pub fn commit_staged_changes(
/// Commit uncommitted changes with the shared commit pipeline.
pub fn commit_changes(options: CommitOptions<'_>) -> Result<(), GitError> {
if !options.no_verify
- && let Some(project_config) = load_project_config(options.ctx.repo)?
+ && let Some(project_config) = options.ctx.repo.load_project_config()?
{
run_pre_commit_commands(
&project_config,
diff --git a/src/commands/list/model.rs b/src/commands/list/model.rs
index 9eeb998f2..f188edea8 100644
--- a/src/commands/list/model.rs
+++ b/src/commands/list/model.rs
@@ -299,7 +299,7 @@ impl BranchInfo {
};
// Read user-defined status from git config (branch-keyed only, no worktree)
- let user_status = read_branch_keyed_status(repo, branch);
+ let user_status = repo.branch_keyed_status(branch);
// Create display fields with status
// For branches without worktrees, status is just user status or "·"
@@ -325,33 +325,6 @@ impl BranchInfo {
}
}
-/// Read user-defined status from branch-keyed config only (`worktrunk.status.<branch>`)
-/// Used for branch-only entries that don't have a worktree
-fn read_branch_keyed_status(repo: &Repository, branch: &str) -> Option<String> {
- let config_key = format!("worktrunk.status.{}", branch);
- repo.run_command(&["config", "--get", &config_key])
- .ok()
- .map(|output| output.trim().to_string())
- .filter(|s| !s.is_empty())
-}
-
-/// Read user-defined status from git config
-/// Tries worktree-specific config first (`worktrunk.status`), then falls back to branch-keyed (`worktrunk.status.<branch>`)
-/// Used for worktree entries
-fn read_user_status(repo: &Repository, branch: Option<&str>) -> Option<String> {
- // Try worktree-specific config first (requires extensions.worktreeConfig)
- if let Ok(output) = repo.run_command(&["config", "--worktree", "--get", "worktrunk.status"]) {
- let status = output.trim().to_string();
- if !status.is_empty() {
- return Some(status);
- }
- }
-
- // Fall back to branch-keyed config (works everywhere)
- let branch = branch?;
- read_branch_keyed_status(repo, branch)
-}
-
/// Main branch divergence state
///
/// Represents relationship to the main/primary branch.
@@ -945,7 +918,7 @@ impl WorktreeInfo {
}
// Read user-defined status from git config (worktree-specific or branch-keyed)
- let user_status = read_user_status(&wt_repo, wt.branch.as_deref());
+ let user_status = wt_repo.user_status(wt.branch.as_deref());
// Create display fields with rendered status
let status_display = if !symbols.is_empty() || user_status.is_some() {
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 9380f62ec..a123ac0ce 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -8,7 +8,7 @@ use super::command_executor::CommandContext;
use super::commit::{CommitOptions, commit_changes};
use super::context::CommandEnv;
use super::hooks::{HookFailureStrategy, HookPipeline};
-use super::project_config::{collect_commands_for_hooks, load_project_config};
+use super::project_config::{ProjectConfigRepoExt, collect_commands_for_hooks};
use super::worktree::{RemoveResult, handle_push};
/// Context for collecting merge commands
@@ -29,7 +29,7 @@ impl<'a> MergeCommandCollector<'a> {
/// Returns original (unexpanded) commands for approval matching
fn collect(self) -> Result<CollectedCommands, GitError> {
let mut all_commands = Vec::new();
- let project_config = match load_project_config(self.repo)? {
+ let project_config = match self.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok((all_commands, self.repo.project_identifier()?)),
};
@@ -149,7 +149,7 @@ pub fn handle_merge(
// Run pre-merge checks unless --no-verify was specified
// Do this after commit/squash/rebase to validate the final state that will be pushed
- if !no_verify && let Some(project_config) = load_project_config(repo)? {
+ if !no_verify && let Some(project_config) = repo.load_project_config()? {
let ctx = env.context(force);
run_pre_merge_commands(&project_config, &ctx, &target_branch)?;
}
@@ -283,7 +283,7 @@ pub fn execute_post_merge_commands(
target_branch: &str,
) -> Result<(), GitError> {
// Load project config from the main worktree path directly
- let project_config = match load_project_config(ctx.repo)? {
+ let project_config = match ctx.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
};
diff --git a/src/commands/project_config.rs b/src/commands/project_config.rs
index 698b965a0..6483d7e7b 100644
--- a/src/commands/project_config.rs
+++ b/src/commands/project_config.rs
@@ -6,30 +6,41 @@ fn load_project_config_at(repo_root: &Path) -> Result<Option<ProjectConfig>, Git
ProjectConfig::load(repo_root).git_context("Failed to load project config")
}
-/// Load the project configuration if it exists.
-pub fn load_project_config(repo: &Repository) -> Result<Option<ProjectConfig>, GitError> {
- let repo_root = repo.worktree_root()?;
- load_project_config_at(&repo_root)
+/// Extension methods for accessing project config data via Repository instances.
+pub trait ProjectConfigRepoExt {
+ /// Load the project configuration if it exists.
+ fn load_project_config(&self) -> Result<Option<ProjectConfig>, GitError>;
+
+ /// Load the project configuration, emitting a helpful hint if missing.
+ fn require_project_config(&self) -> Result<ProjectConfig, GitError>;
}
-/// Load the project configuration, emitting a helpful hint if missing.
-pub fn require_project_config(repo: &Repository) -> Result<ProjectConfig, GitError> {
- let repo_root = repo.worktree_root()?;
- let config_path = repo_root.join(".config").join("wt.toml");
-
- match load_project_config_at(&repo_root)? {
- Some(cfg) => Ok(cfg),
- None => {
- use worktrunk::styling::{ERROR, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, eprintln};
-
- eprintln!("{ERROR_EMOJI} {ERROR}No project configuration found{ERROR:#}",);
- eprintln!(
- "{HINT_EMOJI} {HINT}Create a config file at: {HINT_BOLD}{}{HINT_BOLD:#}{HINT:#}",
- config_path.display()
- );
- Err(GitError::CommandFailed(
- "No project configuration found".to_string(),
- ))
+impl ProjectConfigRepoExt for Repository {
+ fn load_project_config(&self) -> Result<Option<ProjectConfig>, GitError> {
+ let repo_root = self.worktree_root()?;
+ load_project_config_at(&repo_root)
+ }
+
+ fn require_project_config(&self) -> Result<ProjectConfig, GitError> {
+ let repo_root = self.worktree_root()?;
+ let config_path = repo_root.join(".config").join("wt.toml");
+
+ match load_project_config_at(&repo_root)? {
+ Some(cfg) => Ok(cfg),
+ None => {
+ use worktrunk::styling::{
+ ERROR, ERROR_EMOJI, HINT, HINT_BOLD, HINT_EMOJI, eprintln,
+ };
+
+ eprintln!("{ERROR_EMOJI} {ERROR}No project configuration found{ERROR:#}");
+ eprintln!(
+ "{HINT_EMOJI} {HINT}Create a config file at: {HINT_BOLD}{}{HINT_BOLD:#}{HINT:#}",
+ config_path.display()
+ );
+ Err(GitError::CommandFailed(
+ "No project configuration found".to_string(),
+ ))
+ }
}
}
}
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 43fd5d361..596ddef87 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -1,10 +1,8 @@
use skim::prelude::*;
use std::borrow::Cow;
use std::fs;
-use std::io::Write;
use std::path::PathBuf;
-use std::process::{Command, Stdio};
-use std::sync::{Arc, OnceLock};
+use std::sync::Arc;
use worktrunk::config::WorktrunkConfig;
use worktrunk::git::{GitError, GitResultExt, Repository};
@@ -75,112 +73,6 @@ impl Drop for PreviewState {
}
}
-/// Cached pager configuration to avoid repeated detection
-static PAGER_CONFIG: OnceLock<Option<String>> = OnceLock::new();
-
-/// Get cached pager configuration, detecting on first call
-fn get_pager_config() -> &'static Option<String> {
- PAGER_CONFIG.get_or_init(detect_pager)
-}
-
-/// Detect configured diff renderer (colorizer) for preview output
-///
-/// Respects user's git pager configuration, but treats the tool as a
-/// non-interactive renderer (not a pager) in the preview context.
-///
-/// Priority order:
-/// 1. GIT_PAGER environment variable (git's own preference)
-/// 2. git config pager.diff or core.pager
-/// 3. PAGER environment variable (system default)
-/// 4. None (fallback to plain colored output)
-///
-/// Returns the renderer command string to be executed via shell
-fn detect_pager() -> Option<String> {
- let repo = Repository::current();
-
- // Helper to validate pager value
- let validate = |s: &str| -> Option<String> {
- let trimmed = s.trim();
- (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
- };
-
- // Check sources in priority order
- std::env::var("GIT_PAGER")
- .ok()
- .and_then(|s| validate(&s))
- .or_else(|| {
- repo.run_command(&["config", "--get", "pager.diff"])
- .ok()
- .and_then(|s| validate(&s))
- })
- .or_else(|| {
- repo.run_command(&["config", "--get", "core.pager"])
- .ok()
- .and_then(|s| validate(&s))
- })
- .or_else(|| std::env::var("PAGER").ok().and_then(|s| validate(&s)))
-}
-
-/// Invoke a pager/renderer command with git output
-///
-/// Returns Some(output) on success, None on any failure (spawn, wait, or non-zero exit)
-fn invoke_renderer(pager_cmd: &str, git_output: &str) -> Option<String> {
- log::debug!("Invoking renderer: {}", pager_cmd);
-
- let mut cmd = Command::new("sh");
- cmd.arg("-c")
- .arg(pager_cmd)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::null())
- .env("PAGER", "cat")
- .env("DELTA_PAGER", "cat")
- .env("BAT_PAGER", "");
-
- let mut child = cmd.spawn().ok()?;
-
- if let Some(mut stdin) = child.stdin.take() {
- let _ = stdin.write_all(git_output.as_bytes());
- drop(stdin);
- }
-
- let output = child.wait_with_output().ok()?;
- if output.status.success() {
- log::debug!("Renderer succeeded, output len={}", output.stdout.len());
- String::from_utf8(output.stdout).ok()
- } else {
- log::debug!("Renderer failed with status={:?}", output.status);
- None
- }
-}
-
-/// Run git diff through configured renderer (colorizer), or fall back to --color=always
-///
-/// The renderer is run in non-interactive mode (via environment variables) suitable
-/// for embedding in a TUI preview pane. Interactive paging features are disabled.
-fn run_diff_with_pager(repo: &Repository, args: &[&str]) -> Result<String, GitError> {
- // First get git output with color
- let mut git_args = args.to_vec();
- git_args.push("--color=always");
- let git_output = repo.run_command(&git_args)?;
-
- // SECURITY NOTE: Using sh -c to invoke renderer inherits git's security model.
- // Git itself uses sh -c for pagers (for shell features like pipes, aliases, etc.)
- // Users who can control GIT_PAGER/PAGER can already execute arbitrary commands
- // via normal git operations, so this doesn't introduce new attack surface.
- // The renderer command comes from trusted sources (user's own env vars and git config).
-
- let result = match get_pager_config().as_ref() {
- Some(pager_cmd) => invoke_renderer(pager_cmd, &git_output).unwrap_or(git_output),
- None => {
- log::debug!("Using git output directly");
- git_output
- }
- };
-
- Ok(result)
-}
-
/// Wrapper to implement SkimItem for ListItem
struct WorktreeSkimItem {
display_text: String,
@@ -226,7 +118,7 @@ impl WorktreeSkimItem {
output.push_str("\n\n");
// Show full diff with renderer
- if let Ok(diff) = run_diff_with_pager(&repo, args) {
+ if let Ok(diff) = repo.run_diff_with_pager(args) {
output.push_str(&diff);
}
} else {
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 96326cb8b..40a069f00 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -10,9 +10,7 @@ use super::commit::{
};
use super::context::CommandEnv;
use super::merge::{execute_post_merge_commands, run_pre_merge_commands};
-use super::project_config::{
- collect_commands_for_hooks, load_project_config, require_project_config,
-};
+use super::project_config::{ProjectConfigRepoExt, collect_commands_for_hooks};
use super::worktree::{execute_post_create_commands, execute_post_start_commands_sequential};
/// Handle `wt beta run-hook` command
@@ -23,7 +21,7 @@ pub fn handle_standalone_run_hook(hook_type: HookType, force: bool) -> Result<()
let ctx = env.context(force);
// Load project config (show helpful error if missing)
- let project_config = require_project_config(repo)?;
+ let project_config = repo.require_project_config()?;
// TODO: Add support for custom variable overrides (e.g., --var key=value)
// This would allow testing hooks with different contexts without being in that context
@@ -124,7 +122,7 @@ pub fn handle_squash(
}
// Run pre-commit hook unless explicitly skipped
- if !skip_pre_commit && let Some(project_config) = load_project_config(repo)? {
+ if !skip_pre_commit && let Some(project_config) = repo.load_project_config()? {
run_pre_commit_commands(&project_config, &ctx, Some(&target_branch), auto_trust)?;
}
@@ -319,7 +317,7 @@ pub fn handle_standalone_ask_approvals(force: bool, show_all: bool) -> Result<()
let config = WorktrunkConfig::load().git_context("Failed to load config")?;
// Load project config (show helpful error if missing)
- let project_config = require_project_config(&repo)?;
+ let project_config = repo.require_project_config()?;
// Collect all commands from the project config
let all_hooks = [
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index c3e9e1fbd..6f2dbcca5 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -108,7 +108,7 @@ use worktrunk::styling::{
use super::command_executor::CommandContext;
use super::hooks::{HookFailureStrategy, HookPipeline};
-use super::project_config::load_project_config;
+use super::project_config::ProjectConfigRepoExt;
/// Result of a worktree switch operation
pub enum SwitchResult {
@@ -576,7 +576,7 @@ impl TargetWorktreeStash {
/// Execute post-create commands sequentially (blocking)
pub fn execute_post_create_commands(ctx: &CommandContext) -> Result<(), GitError> {
- let project_config = match load_project_config(ctx.repo)? {
+ let project_config = match ctx.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
};
@@ -598,7 +598,7 @@ pub fn execute_post_create_commands(ctx: &CommandContext) -> Result<(), GitError
/// Spawn post-start commands in parallel as background processes (non-blocking)
pub fn spawn_post_start_commands(ctx: &CommandContext) -> Result<(), GitError> {
- let project_config = match load_project_config(ctx.repo)? {
+ let project_config = match ctx.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
};
@@ -619,7 +619,7 @@ pub fn spawn_post_start_commands(ctx: &CommandContext) -> Result<(), GitError> {
/// Execute post-start commands sequentially (blocking) - for testing
pub fn execute_post_start_commands_sequential(ctx: &CommandContext) -> Result<(), GitError> {
- let project_config = match load_project_config(ctx.repo)? {
+ let project_config = match ctx.repo.load_project_config()? {
Some(cfg) => cfg,
None => return Ok(()),
};
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index ebe044223..25912575b 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1,5 +1,6 @@
+use std::io::Write;
use std::path::PathBuf;
-use std::process::Command;
+use std::process::{Command, Stdio};
use std::sync::OnceLock;
// Import types and functions from parent module (mod.rs)
@@ -194,6 +195,28 @@ impl Repository {
}
}
+ /// Read a user-defined status from `worktrunk.status.<branch>` in git config.
+ pub fn branch_keyed_status(&self, branch: &str) -> Option<String> {
+ let config_key = format!("worktrunk.status.{}", branch);
+ self.run_command(&["config", "--get", &config_key])
+ .ok()
+ .map(|output| output.trim().to_string())
+ .filter(|s| !s.is_empty())
+ }
+
+ /// Read user-defined status, preferring worktree config then falling back to branch-keyed.
+ pub fn user_status(&self, branch: Option<&str>) -> Option<String> {
+ if let Ok(output) = self.run_command(&["config", "--worktree", "--get", "worktrunk.status"])
+ {
+ let status = output.trim().to_string();
+ if !status.is_empty() {
+ return Some(status);
+ }
+ }
+
+ branch.and_then(|branch| self.branch_keyed_status(branch))
+ }
+
/// Resolve a worktree name, expanding "@" to the current branch and "-" to the previous branch.
///
/// # Arguments
@@ -850,6 +873,82 @@ impl Repository {
}
Ok(success)
}
+
+ /// Run git diff through a renderer (pager) if configured, otherwise return colored diff output.
+ pub fn run_diff_with_pager(&self, args: &[&str]) -> Result<String, GitError> {
+ let mut git_args = args.to_vec();
+ git_args.push("--color=always");
+ let git_output = self.run_command(&git_args)?;
+
+ let result = match pager_config().as_ref() {
+ Some(pager_cmd) => invoke_renderer(pager_cmd, &git_output).unwrap_or(git_output),
+ None => {
+ log::debug!("Using git output directly");
+ git_output
+ }
+ };
+
+ Ok(result)
+ }
+}
+
+fn pager_config() -> &'static Option<String> {
+ static PAGER_CONFIG: OnceLock<Option<String>> = OnceLock::new();
+ PAGER_CONFIG.get_or_init(detect_pager)
+}
+
+fn detect_pager() -> Option<String> {
+ let repo = Repository::current();
+
+ let validate = |s: &str| -> Option<String> {
+ let trimmed = s.trim();
+ (!trimmed.is_empty() && trimmed != "cat").then(|| trimmed.to_string())
+ };
+
+ std::env::var("GIT_PAGER")
+ .ok()
+ .and_then(|s| validate(&s))
+ .or_else(|| {
+ repo.run_command(&["config", "--get", "pager.diff"])
+ .ok()
+ .and_then(|s| validate(&s))
+ })
+ .or_else(|| {
+ repo.run_command(&["config", "--get", "core.pager"])
+ .ok()
+ .and_then(|s| validate(&s))
+ })
+ .or_else(|| std::env::var("PAGER").ok().and_then(|s| validate(&s)))
+}
+
+fn invoke_renderer(pager_cmd: &str, git_output: &str) -> Option<String> {
+ log::debug!("Invoking renderer: {}", pager_cmd);
+
+ let mut cmd = Command::new("sh");
+ cmd.arg("-c")
+ .arg(pager_cmd)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::null())
+ .env("PAGER", "cat")
+ .env("DELTA_PAGER", "cat")
+ .env("BAT_PAGER", "");
+
+ let mut child = cmd.spawn().ok()?;
+
+ if let Some(mut stdin) = child.stdin.take() {
+ let _ = stdin.write_all(git_output.as_bytes());
+ drop(stdin);
+ }
+
+ let output = child.wait_with_output().ok()?;
+ if output.status.success() {
+ log::debug!("Renderer succeeded, output len={}", output.stdout.len());
+ String::from_utf8(output.stdout).ok()
+ } else {
+ log::debug!("Renderer failed with status={:?}", output.status);
+ None
+ }
}
#[cfg(test)]