Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: simplify Repository API and eliminate magic cwd lookups (#519)
Maximilian Roos2e2777c4040f
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 85656a491..220d5c7c5 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -80,7 +80,7 @@ impl<'a> CommitGenerator<'a> {show_no_squash_note: bool,stage_mode: StageMode,) -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;// Fail early if nothing is staged (avoids confusing LLM prompt with empty diff)if !repo.has_staged_changes()? {diff --git a/src/commands/config.rs b/src/commands/config.rsindex 41ea46293..d0eca2be2 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -55,8 +55,8 @@ fn comment_out_config(content: &str) -> String {/// Handle the config create commandpub fn handle_config_create(project: bool) -> anyhow::Result<()> {if project {- let repo = Repository::current();- let config_path = repo.worktree_root()?.join(".config/wt.toml");+ let repo = Repository::current()?;+ let config_path = repo.current_worktree().root()?.join(".config/wt.toml");create_config_file(config_path,PROJECT_CONFIG_EXAMPLE,@@ -282,13 +282,10 @@ fn render_diagnostics(out: &mut String) -> anyhow::Result<()> {writeln!(out, "{}", format_heading("DIAGNOSTICS", None))?;// Check CI tool based on detected platform (with config override support)- let repo = Repository::current();+ let repo = Repository::current()?;let project_config = ProjectConfig::load(&repo, true).ok().flatten();let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());- let platform = repo- .worktree_root()- .ok()- .and_then(|root| get_platform_for_repo(root.to_str()?, platform_override));+ let platform = get_platform_for_repo(&repo, platform_override);match platform {Some(CiPlatform::GitHub) => {@@ -424,8 +421,7 @@ fn warn_unknown_keys(out: &mut String, unknown_keys: &[String]) -> anyhow::Resulfn render_project_config(out: &mut String) -> anyhow::Result<()> {// Try to get current repository root- let repo = Repository::current();- let repo_root = match repo.worktree_root() {+ let repo_root = match Repository::current().and_then(|repo| repo.current_worktree().root()) {Ok(root) => root,Err(_) => {writeln!(@@ -876,7 +872,7 @@ fn require_user_config_path() -> anyhow::Result<PathBuf> {/// Clear all log files from the wt-logs directoryfn clear_logs(repo: &Repository) -> anyhow::Result<usize> {- let log_dir = repo.wt_logs_dir()?;+ let log_dir = repo.wt_logs_dir();if !log_dir.exists() {return Ok(0);@@ -902,7 +898,7 @@ fn clear_logs(repo: &Repository) -> anyhow::Result<usize> {/// Render the LOG FILES section (heading + table or "(none)") into the output bufferfn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {- let log_dir = repo.wt_logs_dir()?;+ let log_dir = repo.wt_logs_dir();let log_dir_display = format_path_for_display(&log_dir);writeln!(@@ -970,7 +966,7 @@ fn render_log_files(out: &mut String, repo: &Repository) -> anyhow::Result<()> {pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> anyhow::Result<()> {use super::list::ci_status::PrStatus;- let repo = Repository::current();+ let repo = Repository::current()?;match key {"default-branch" => {@@ -1002,8 +998,6 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> anyNone => repo.require_current_branch("get ci-status for current branch")?,};- let repo_root = repo.worktree_root()?;-// Get the HEAD commit for this branchlet head = repo.run_command(&["rev-parse", &branch_name])@@ -1025,7 +1019,7 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any}let has_upstream = repo.upstream_branch(&branch_name).ok().flatten().is_some();- let ci_status = PrStatus::detect(&branch_name, &head, &repo_root, has_upstream)+ let ci_status = PrStatus::detect(&repo, &branch_name, &head, has_upstream).map_or(super::list::ci_status::CiStatus::NoCI, |s| s.ci_status);let status_str: &'static str = ci_status.into();crate::output::stdout(status_str)?;@@ -1052,7 +1046,7 @@ pub fn handle_state_get(key: &str, refresh: bool, branch: Option<String>) -> any/// Handle the state set commandpub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;match key {"default-branch" => {@@ -1097,7 +1091,7 @@ pub fn handle_state_set(key: &str, value: String, branch: Option<String>) -> any/// Handle the state clear commandpub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;match key {"default-branch" => {@@ -1215,7 +1209,7 @@ pub fn handle_state_clear(key: &str, branch: Option<String>, all: bool) -> anyho/// Handle the state clear all commandpub fn handle_state_clear_all() -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;let mut cleared_any = false;// Clear default branch cache@@ -1271,7 +1265,7 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {/// Handle the hints get command (list shown hints)pub fn handle_hints_get() -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;let hints = repo.list_shown_hints();if hints.is_empty() {@@ -1287,7 +1281,7 @@ pub fn handle_hints_get() -> anyhow::Result<()> {/// Handle the hints clear commandpub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;match name {Some(hint_name) => {@@ -1317,7 +1311,7 @@ pub fn handle_hints_clear(name: Option<String>) -> anyhow::Result<()> {pub fn handle_state_show(format: crate::cli::OutputFormat) -> anyhow::Result<()> {use crate::cli::OutputFormat;- let repo = Repository::current();+ let repo = Repository::current()?;match format {OutputFormat::Json => handle_state_show_json(&repo),@@ -1369,7 +1363,7 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {.collect();// Get log files- let log_dir = repo.wt_logs_dir()?;+ let log_dir = repo.wt_logs_dir();let logs: Vec<serde_json::Value> = if log_dir.exists() {let mut entries: Vec<_> = std::fs::read_dir(&log_dir)?.filter_map(|e| e.ok())diff --git a/src/commands/context.rs b/src/commands/context.rsindex dcb1cfaa1..10a2c4559 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -30,7 +30,7 @@ impl CommandEnv {/// `action` describes what command is running (e.g., "merge", "squash")./// Used in error messages when the environment can't be loaded.pub fn for_action(action: &str) -> anyhow::Result<Self> {- let repo = Repository::current();+ let repo = Repository::current()?;let worktree_path = std::env::current_dir().context("Failed to get current directory")?;let branch = repo.require_current_branch(action)?;let config = WorktrunkConfig::load().context("Failed to load config")?;@@ -52,11 +52,12 @@ impl CommandEnv {/// 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 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 HEADlet branch = repo- .current_branch()+ .current_worktree()+ .branch().context("Failed to determine current branch")?;let config = WorktrunkConfig::load().context("Failed to load config")?;let repo_root = repodiff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 9309c11dd..d978ae6ac 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -45,7 +45,7 @@ use crate::output;////// All template variables from hooks are available, and context JSON is piped to stdin.pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;// Filter out prunable worktrees (directory deleted) - can't run commands therelet worktrees: Vec<_> = repo.list_worktrees()?@@ -67,13 +67,10 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {let display_name = worktree_display_name(wt, &repo, &config);output::print(progress_message(format!("Running in {display_name}...")))?;- // Open repository at worktree path to get worktree-specific context (commit, etc.)- let wt_repo = Repository::at(&wt.path);-// Build full hook context for this worktree// Pass wt.branch directly (not the display string) so detached HEAD maps to None -> "HEAD"let ctx = CommandContext::new(- &wt_repo,+ &repo,&config,wt.branch.as_deref(),&wt.path,diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 0bc987123..1b60d8a0a 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -264,12 +264,16 @@ pub fn add_approvals(show_all: bool) -> anyhow::Result<()> {use super::command_approval::approve_command_batch;use worktrunk::config::WorktrunkConfig;- let repo = Repository::current();+ let repo = Repository::current()?;let project_id = repo.project_identifier()?;let config = WorktrunkConfig::load().context("Failed to load config")?;// Load project config (error if missing - this command requires it)- let config_path = repo.worktree_root()?.join(".config").join("wt.toml");+ let config_path = repo+ .current_worktree()+ .root()?+ .join(".config")+ .join("wt.toml");let project_config = repo.load_project_config()?.ok_or(GitError::ProjectConfigNotFound { config_path })?;@@ -340,7 +344,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {)))?;} else {// Clear approvals for current project (default)- let repo = Repository::current();+ let repo = Repository::current()?;let project_id = repo.project_identifier()?;// Check if project has any approvals@@ -375,7 +379,7 @@ pub fn clear_approvals(global: bool) -> anyhow::Result<()> {pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyhow::Result<()> {use crate::help_pager::show_help_in_pager;- let repo = Repository::current();+ let repo = Repository::current()?;let config = WorktrunkConfig::load().context("Failed to load user config")?;let project_config = repo.load_project_config()?;let project_id = repo.project_identifier().ok();@@ -493,7 +497,7 @@ fn render_project_hooks(filter: Option<HookType>,ctx: Option<&CommandContext>,) -> anyhow::Result<()> {- let repo_root = repo.worktree_root()?;+ let repo_root = repo.current_worktree().root()?;let config_path = repo_root.join(".config").join("wt.toml");writeln!(diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex 93a9381bf..9b3020370 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -2,7 +2,7 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned};use std::fs;use std::path::{Path, PathBuf};use std::process::Command;-use worktrunk::git::{Repository, parse_owner_repo, parse_remote_host, parse_remote_owner};+use worktrunk::git::{Repository, parse_owner_repo, parse_remote_owner};use worktrunk::path::sanitize_for_filename;use worktrunk::shell_exec::run;use worktrunk::utils::get_now;@@ -34,15 +34,10 @@ fn detect_platform_from_url(url: &str) -> Option<CiPlatform> {/// Get the CI platform for a repository.////// If `platform_override` is provided (from project config `[ci] platform`),-/// uses that value directly. Otherwise, detects platform from the origin+/// uses that value directly. Otherwise, detects platform from the primary/// remote URL.-///-/// # Arguments-///-/// * `repo_root` - Repository root path-/// * `platform_override` - Optional platform from `[ci] platform` in project configpub fn get_platform_for_repo(- repo_root: &str,+ repo: &Repository,platform_override: Option<&str>,) -> Option<CiPlatform> {// Config override takes precedence@@ -58,30 +53,10 @@ pub fn get_platform_for_repo(}// Fall back to URL detection- let url = get_remote_url_for_repo(repo_root)?;+ let url = repo.primary_remote_url()?;detect_platform_from_url(&url)}-/// Get the origin remote URL for a repository.-fn get_remote_url_for_repo(repo_root: &str) -> Option<String> {- let repo = Repository::at(repo_root);- repo.remote_url("origin")-}--/// Get the GitLab hostname for a repository by parsing its origin remote URL.-///-/// Returns the hostname if the remote URL contains "gitlab", None otherwise.-/// Used to check glab auth status against a specific host.-pub fn get_gitlab_host_for_repo(repo_root: &str) -> Option<String> {- let url = get_remote_url_for_repo(repo_root)?;- // Only return host if this looks like a GitLab URL- if detect_platform_from_url(&url) == Some(CiPlatform::GitLab) {- parse_remote_host(&url)- } else {- None- }-}-#[cfg(test)]mod tests {use super::*;@@ -672,20 +647,20 @@ const MAX_PRS_TO_FETCH: u8 = 20;////// Used for client-side filtering of PRs by source repository./// See [`parse_remote_owner`] for details on why this is necessary.-fn get_origin_owner(repo_root: &str) -> Option<String> {- let url = get_remote_url_for_repo(repo_root)?;+fn get_origin_owner(repo: &Repository) -> Option<String> {+ let url = repo.primary_remote_url()?;parse_remote_owner(&url)}-/// Get the owner and repo name from the origin remote.+/// Get the owner and repo name from the primary remote.////// Used for GitHub API calls that require `repos/{owner}/{repo}/...` paths.-fn get_owner_repo(repo_root: &str) -> Option<(String, String)> {- let url = get_remote_url_for_repo(repo_root)?;+fn get_owner_repo(repo: &Repository) -> Option<(String, String)> {+ let url = repo.primary_remote_url()?;parse_owner_repo(&url)}-/// Get the GitLab project ID for the current repository.+/// Get the GitLab project ID for a repository.////// Used for client-side filtering of MRs by source project./// This is the GitLab equivalent of [`get_origin_owner`] for GitHub.@@ -698,11 +673,13 @@ fn get_owner_repo(repo_root: &str) -> Option<(String, String)> {/// the repo is actually GitLab-hosted. If glab is installed but the repo/// is GitHub, this adds an unnecessary CLI call. A future optimization/// could check the remote URL first and skip for non-GitLab remotes.-fn get_gitlab_project_id(repo_root: &str) -> Option<u64> {+fn get_gitlab_project_id(repo: &Repository) -> Option<u64> {+ let repo_root = repo.current_worktree().root().ok()?;+// Use glab repo view to get the project info as JSONlet mut cmd = Command::new("glab");cmd.args(["repo", "view", "--output", "json"]);- cmd.current_dir(repo_root);+ cmd.current_dir(&repo_root);// Disable color/pager to avoid ANSI noise in JSON outputconfigure_non_interactive(&mut cmd);cmd.env("PAGER", "cat");@@ -798,11 +775,6 @@ impl CiToolsStatus {glab_authenticated,}}-- /// Returns true if at least one CI tool can fetch status- pub fn any_available(&self) -> bool {- self.gh_authenticated || self.glab_authenticated- }}/// Parse JSON output from CLI tools@@ -930,22 +902,20 @@ impl CachedCiStatus {}/// Get the cache directory path: `.git/wt-cache/ci-status/`- fn cache_dir(repo_root: &Path) -> Option<PathBuf> {- let repo = Repository::at(repo_root);- let git_common_dir = repo.git_common_dir().ok()?;- Some(git_common_dir.join("wt-cache").join("ci-status"))+ fn cache_dir(repo: &Repository) -> PathBuf {+ repo.git_common_dir().join("wt-cache").join("ci-status")}/// Get the cache file path for a branch.- fn cache_file(branch: &str, repo_root: &Path) -> Option<PathBuf> {- let dir = Self::cache_dir(repo_root)?;+ fn cache_file(repo: &Repository, branch: &str) -> PathBuf {+ let dir = Self::cache_dir(repo);let safe_branch = sanitize_for_filename(branch);- Some(dir.join(format!("{safe_branch}.json")))+ dir.join(format!("{safe_branch}.json"))}/// Read cached CI status from file.- fn read(branch: &str, repo_root: &Path) -> Option<Self> {- let path = Self::cache_file(branch, repo_root)?;+ fn read(repo: &Repository, branch: &str) -> Option<Self> {+ let path = Self::cache_file(repo, branch);let json = fs::read_to_string(&path).ok()?;serde_json::from_str(&json).ok()}@@ -954,11 +924,8 @@ impl CachedCiStatus {////// Uses atomic write (write to temp file, then rename) to avoid corruption/// and minimize lock contention on Windows.- fn write(&self, branch: &str, repo_root: &Path) {- let Some(path) = Self::cache_file(branch, repo_root) else {- log::debug!("Failed to get cache path for {}", branch);- return;- };+ fn write(&self, repo: &Repository, branch: &str) {+ let path = Self::cache_file(repo, branch);// Create cache directory if neededif let Some(parent) = path.parent()@@ -989,14 +956,7 @@ impl CachedCiStatus {/// List all cached CI statuses as (branch_name, cached_status) pairs.pub(crate) fn list_all(repo: &Repository) -> Vec<(String, Self)> {- let repo_root = match repo.worktree_root() {- Ok(path) => path,- Err(_) => return Vec::new(),- };-- let Some(cache_dir) = Self::cache_dir(&repo_root) else {- return Vec::new();- };+ let cache_dir = Self::cache_dir(repo);let entries = match fs::read_dir(&cache_dir) {Ok(entries) => entries,@@ -1023,14 +983,7 @@ impl CachedCiStatus {/// Clear all cached CI statuses, returns count cleared.pub(crate) fn clear_all(repo: &Repository) -> usize {- let repo_root = match repo.worktree_root() {- Ok(path) => path,- Err(_) => return 0,- };-- let Some(cache_dir) = Self::cache_dir(&repo_root) else {- return 0;- };+ let cache_dir = Self::cache_dir(repo);let entries = match fs::read_dir(&cache_dir) {Ok(entries) => entries,@@ -1144,25 +1097,26 @@ impl PrStatus {/// repos are properly detected.////// # Arguments- /// * `repo_path` - Repository root path from `Repository::worktree_root()`/// * `has_upstream` - Whether the branch has upstream tracking configured./// PR/MR detection always runs. Workflow/pipeline fallback only runs if true.pub fn detect(+ repo: &Repository,branch: &str,local_head: &str,- repo_path: &std::path::Path,has_upstream: bool,) -> Option<Self> {+ let repo_path = repo.current_worktree().root().ok()?;+// Check cache first to avoid hitting API rate limitslet now_secs = get_now();- if let Some(cached) = CachedCiStatus::read(branch, repo_path) {- if cached.is_valid(local_head, now_secs, repo_path) {+ if let Some(cached) = CachedCiStatus::read(repo, branch) {+ if cached.is_valid(local_head, now_secs, &repo_path) {log::debug!("Using cached CI status for {} (age={}s, ttl={}s, status={:?})",branch,now_secs - cached.checked_at,- CachedCiStatus::ttl_for_repo(repo_path),+ CachedCiStatus::ttl_for_repo(&repo_path),cached.status.as_ref().map(|s| &s.ci_status));return cached.status;@@ -1171,16 +1125,13 @@ impl PrStatus {"Cache expired for {} (age={}s, ttl={}s, head_match={})",branch,now_secs - cached.checked_at,- CachedCiStatus::ttl_for_repo(repo_path),+ CachedCiStatus::ttl_for_repo(&repo_path),cached.head == local_head);}// Cache miss or expired - fetch fresh status- // We run gh/glab commands from the repo directory to let them auto-detect the correct repo- // (including upstream repos for forks)- let repo_root = repo_path.to_string_lossy();- let status = Self::detect_uncached(branch, local_head, &repo_root, has_upstream);+ let status = Self::detect_uncached(repo, branch, local_head, has_upstream);// Cache the result (including None - means no CI found for this branch)let cached = CachedCiStatus {@@ -1188,7 +1139,7 @@ impl PrStatus {checked_at: now_secs,head: local_head.to_string(),};- cached.write(branch, repo_path);+ cached.write(repo, branch);status}@@ -1200,65 +1151,61 @@ impl PrStatus {/// to trying both platforms./// PR/MR detection always runs. Workflow/pipeline fallback only runs if `has_upstream`.fn detect_uncached(+ repo: &Repository,branch: &str,local_head: &str,- repo_root: &str,has_upstream: bool,) -> Option<Self> {use worktrunk::config::ProjectConfig;// Load project config for platform override- let repo = Repository::at(repo_root);- let project_config = ProjectConfig::load(&repo, false).ok().flatten();+ let project_config = ProjectConfig::load(repo, false).ok().flatten();let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());// Determine platform (config override or URL detection)- let platform = get_platform_for_repo(repo_root, platform_override);+ let platform = get_platform_for_repo(repo, platform_override);match platform {Some(CiPlatform::GitHub) => {- Self::detect_github_ci(branch, local_head, repo_root, has_upstream)+ Self::detect_github_ci(repo, branch, local_head, has_upstream)}Some(CiPlatform::GitLab) => {- Self::detect_gitlab_ci(branch, local_head, repo_root, has_upstream)+ Self::detect_gitlab_ci(repo, branch, local_head, has_upstream)}None => {// Unknown platform (e.g., GitHub Enterprise, self-hosted GitLab with custom domain)// Fall back to trying both platforms- log::debug!(- "Could not determine CI platform for {}, trying both",- repo_root- );- Self::detect_github_ci(branch, local_head, repo_root, has_upstream)- .or_else(|| Self::detect_gitlab_ci(branch, local_head, repo_root, has_upstream))+ log::debug!("Could not determine CI platform, trying both");+ Self::detect_github_ci(repo, branch, local_head, has_upstream)+ .or_else(|| Self::detect_gitlab_ci(repo, branch, local_head, has_upstream))}}}/// Detect GitHub CI status (PR first, then workflow if has_upstream)fn detect_github_ci(+ repo: &Repository,branch: &str,local_head: &str,- repo_root: &str,has_upstream: bool,) -> Option<Self> {- if let Some(status) = Self::detect_github(branch, local_head, repo_root) {+ if let Some(status) = Self::detect_github(repo, branch, local_head) {return Some(status);}if has_upstream {- return Self::detect_github_commit_checks(local_head, repo_root);+ return Self::detect_github_commit_checks(repo, local_head);}None}/// Detect GitLab CI status (MR first, then pipeline if has_upstream)fn detect_gitlab_ci(+ repo: &Repository,branch: &str,local_head: &str,- repo_root: &str,has_upstream: bool,) -> Option<Self> {- if let Some(status) = Self::detect_gitlab(branch, local_head, repo_root) {+ if let Some(status) = Self::detect_gitlab(repo, branch, local_head) {return Some(status);}if has_upstream {@@ -1284,8 +1231,11 @@ impl PrStatus {/// - Fork workflows (PRs from your fork to upstream)/// - Organization repos (PRs from org branches)/// - Multiple users with same branch name- fn detect_github(branch: &str, local_head: &str, repo_root: &str) -> Option<Self> {+ fn detect_github(repo: &Repository, branch: &str, local_head: &str) -> Option<Self> {use std::process::Stdio;++ let repo_root = repo.current_worktree().root().ok()?;+// Check if gh is available and authenticatedlet mut auth_cmd = Command::new("gh");auth_cmd.args(["auth", "status"]);@@ -1303,9 +1253,9 @@ impl PrStatus {}// Get origin owner for filtering (see parse_remote_owner docs for why)- let origin_owner = get_origin_owner(repo_root);+ let origin_owner = get_origin_owner(repo);if origin_owner.is_none() {- log::debug!("Could not determine origin owner for {}", repo_root);+ log::debug!("Could not determine origin owner for {}", branch);}// Use `gh pr list --head` instead of `gh pr view` to handle numeric branch names correctly.@@ -1329,7 +1279,7 @@ impl PrStatus {]);configure_non_interactive(&mut cmd);- cmd.current_dir(repo_root);+ cmd.current_dir(&repo_root);let output = match run(&mut cmd, None) {Ok(output) => output,@@ -1374,7 +1324,7 @@ impl PrStatus {// This is less accurate but better than nothinglog::debug!("No origin owner for {}, using first open PR for branch {}",- repo_root,+ repo_root.display(),branch);pr_list.first()@@ -1412,15 +1362,17 @@ impl PrStatus {/// 1. Get the current project ID via `glab repo view`/// 2. Fetch all open MRs with matching branch name (up to 20)/// 3. Filter client-side by comparing `source_project_id` to our project ID- fn detect_gitlab(branch: &str, local_head: &str, repo_root: &str) -> Option<Self> {+ fn detect_gitlab(repo: &Repository, branch: &str, local_head: &str) -> Option<Self> {if !tool_available("glab", &["--version"]) {return None;}+ let repo_root = repo.current_worktree().root().ok()?;+// Get current project ID for filtering- let project_id = get_gitlab_project_id(repo_root);+ let project_id = get_gitlab_project_id(repo);if project_id.is_none() {- log::debug!("Could not determine GitLab project ID for {}", repo_root);+ log::debug!("Could not determine GitLab project ID");}// Fetch MRs with matching source branch.@@ -1436,7 +1388,7 @@ impl PrStatus {"--output","json",]);- cmd.current_dir(repo_root);+ cmd.current_dir(&repo_root);let output = match run(&mut cmd, None) {Ok(output) => output,@@ -1481,7 +1433,7 @@ impl PrStatus {// If we can't determine project ID, fall back to first MRlog::debug!("No project ID for {}, using first MR for branch {}",- repo_root,+ repo_root.display(),branch);mr_list.first()@@ -1515,25 +1467,26 @@ impl PrStatus {/// This queries all check runs for the commit SHA, giving us the same data/// that `statusCheckRollup` provides for PRs. This correctly aggregates/// status across multiple workflows (e.g., `ci` and `publish-docs`).- fn detect_github_commit_checks(local_head: &str, repo_root: &str) -> Option<Self> {+ fn detect_github_commit_checks(repo: &Repository, local_head: &str) -> Option<Self> {// Note: We don't log auth failures here since detect_github already logged themif !tool_available("gh", &["auth", "status"]) {return None;}- let (owner, repo) = get_owner_repo(repo_root)?;+ let repo_root = repo.current_worktree().root().ok()?;+ let (owner, repo_name) = get_owner_repo(repo)?;// Use GitHub's check-runs API to get all checks for this commitlet mut cmd = Command::new("gh");cmd.args(["api",- &format!("repos/{owner}/{repo}/commits/{local_head}/check-runs"),+ &format!("repos/{owner}/{repo_name}/commits/{local_head}/check-runs"),"--jq",".check_runs | map({status, conclusion})",]);configure_non_interactive(&mut cmd);- cmd.current_dir(repo_root);+ cmd.current_dir(&repo_root);let output = match run(&mut cmd, None) {Ok(output) => output,diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex f6d580fc4..84422e657 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -263,9 +263,9 @@ impl TaskKind {/// Detect if a worktree is in the middle of a git operation (rebase/merge).pub(super) fn detect_git_operation(repo: &Repository) -> GitOperationState {- if repo.is_rebasing().unwrap_or(false) {+ if repo.current_worktree().is_rebasing().unwrap_or(false) {GitOperationState::Rebase- } else if repo.is_merging().unwrap_or(false) {+ } else if repo.current_worktree().is_merging().unwrap_or(false) {GitOperationState::Merge} else {GitOperationState::None@@ -413,8 +413,9 @@ fn apply_default(items: &mut [ListItem], status_contexts: &mut [StatusContext],items[idx].upstream = Some(UpstreamStatus::default());}TaskKind::CiStatus => {- // Some(None) means "loaded but no CI"- items[idx].pr_status = Some(None);+ // Leave as None (not fetched) on error. This allows the hint path+ // in mod.rs to run and show "install gh/glab" when CI tools fail.+ // Some(None) means "CI tool ran successfully but found no PR".}TaskKind::UrlStatus => {// URL is set at item creation, only default url_active@@ -700,7 +701,7 @@ pub fn collect(// Detect current worktree by checking if repo path is inside any worktree.// This avoids a git command - we just compare canonicalized paths.- let repo_path_canonical = canonicalize(repo.base_path()).ok();+ let repo_path_canonical = canonicalize(repo.discovery_path()).ok();let current_worktree_path = repo_path_canonical.as_ref().and_then(|repo_path| {worktrees.iter().find_map(|wt| {canonicalize(&wt.path)@@ -998,12 +999,11 @@ pub fn collect(// See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same issue)#[cfg(target_os = "macos")]{- let main_repo = Repository::at(&main_worktree.path);- if main_repo.is_builtin_fsmonitor_enabled() {+ if repo.is_builtin_fsmonitor_enabled() {for wt in &sorted_worktrees {// Skip prunable worktrees (directory missing)if !wt.is_prunable() {- Repository::at(&wt.path).start_fsmonitor_daemon();+ repo.start_fsmonitor_daemon_at(&wt.path);}}}diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rsindex b86efa49e..4f5201a9a 100644--- a/src/commands/list/collect_progressive_impl.rs+++ b/src/commands/list/collect_progressive_impl.rs@@ -94,8 +94,10 @@ pub struct TaskContext {}impl TaskContext {- fn repo(&self) -> Repository {- Repository::at(&self.repo_path)+ fn repo(&self, kind: TaskKind) -> Result<Repository, TaskError> {+ // Background tasks need Repository discovered from their specific worktree path,+ // not from base_path(). Each task operates on a potentially different worktree.+ Repository::at(&self.repo_path).map_err(|e| self.error(kind, e))}fn error(&self, kind: TaskKind, message: impl Display) -> TaskError {@@ -380,7 +382,7 @@ impl Task for CommitDetailsTask {const KIND: TaskKind = TaskKind::CommitDetails;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let timestamp = repo.commit_timestamp(&ctx.commit_sha).map_err(|e| ctx.error(Self::KIND, e))?;@@ -405,7 +407,7 @@ impl Task for AheadBehindTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let base = ctx.require_default_branch(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;// Check cache first (populated by batch_ahead_behind if it ran).// Cache lookup has minor overhead (rev-parse for cache key + allocations),@@ -439,7 +441,7 @@ impl Task for CommittedTreesMatchTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let base = ctx.require_target(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;// Use ctx.commit_sha (the item's commit) instead of HEAD,// since for branches without worktrees, HEAD is the main worktree's HEADlet committed_trees_match = repo@@ -477,7 +479,7 @@ impl Task for HasFileChangesTask {});};let target = ctx.require_target(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let has_file_changes = repo.has_added_changes(branch, target).map_err(|e| ctx.error(Self::KIND, e))?;@@ -514,7 +516,7 @@ impl Task for WouldMergeAddTask {});};let base = ctx.require_target(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let would_merge_add = repo.would_merge_add_to_target(branch, base).map_err(|e| ctx.error(Self::KIND, e))?;@@ -540,7 +542,7 @@ impl Task for IsAncestorTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let base = ctx.require_target(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let is_ancestor = repo.is_ancestor(&ctx.commit_sha, base).map_err(|e| ctx.error(Self::KIND, e))?;@@ -560,7 +562,7 @@ impl Task for BranchDiffTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let base = ctx.require_default_branch(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let diff = repo.branch_diff_stats(base, &ctx.commit_sha).map_err(|e| ctx.error(Self::KIND, e))?;@@ -579,7 +581,7 @@ impl Task for WorkingTreeDiffTask {const KIND: TaskKind = TaskKind::WorkingTreeDiff;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;// Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's// `git stash create` which needs the index lock.let status_output = repo@@ -622,7 +624,7 @@ impl Task for MergeTreeConflictsTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let base = ctx.require_default_branch(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let has_merge_tree_conflicts = repo.has_merge_conflicts(base, &ctx.commit_sha).map_err(|e| ctx.error(Self::KIND, e))?;@@ -645,7 +647,7 @@ impl Task for WorkingTreeConflictsTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {let base = ctx.require_default_branch(Self::KIND)?;- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;// Use --no-optional-locks to avoid index lock contention with WorkingTreeDiffTask.// Both tasks run in parallel, and `git stash create` below needs the index lock.@@ -711,7 +713,7 @@ impl Task for GitOperationTask {const KIND: TaskKind = TaskKind::GitOperation;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let git_operation = detect_git_operation(&repo);Ok(TaskResult::GitOperation {item_idx: ctx.item_idx,@@ -727,7 +729,7 @@ impl Task for UserMarkerTask {const KIND: TaskKind = TaskKind::UserMarker;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;let user_marker = repo.user_marker(ctx.branch.as_deref());Ok(TaskResult::UserMarker {item_idx: ctx.item_idx,@@ -743,7 +745,7 @@ impl Task for UpstreamTask {const KIND: TaskKind = TaskKind::Upstream;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = ctx.repo();+ let repo = ctx.repo(Self::KIND)?;// No branch means no upstreamlet Some(branch) = ctx.branch.as_deref() else {@@ -791,15 +793,10 @@ impl Task for CiStatusTask {const KIND: TaskKind = TaskKind::CiStatus;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- let repo = ctx.repo();- let repo_path = repo- .worktree_root()- .ok()- .unwrap_or_else(|| ctx.repo_path.clone());-+ let repo = ctx.repo(Self::KIND)?;let pr_status = ctx.branch.as_deref().and_then(|branch| {let has_upstream = repo.upstream_branch(branch).ok().flatten().is_some();- PrStatus::detect(branch, &ctx.commit_sha, &repo_path, has_upstream)+ PrStatus::detect(&repo, branch, &ctx.commit_sha, has_upstream)});Ok(TaskResult::CiStatus {diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex 971dbd9d7..b099736c6 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -150,7 +150,7 @@ pub fn handle_list() -> anyhow::Result<()> {use collect::TaskKind;- let repo = Repository::current();+ let repo = Repository::current()?;// Build skip set based on flags// Without --full: skip expensive operations (BranchDiff, CiStatus, WorkingTreeConflicts)@@ -211,78 +211,6 @@ pub fn handle_list(}}- // Show hint if CI status was requested but no tools can fetch it.- // Skip the check if any items already have CI status (tools must be available).- if show_full {- // pr_status semantics: None = not fetched, Some(None) = fetched but no PR,- // Some(Some(status)) = fetched with status. If any item is Some(_), we- // successfully communicated with CI tools, so they're available.- let any_ci_fetched = items.iter().any(|item| item.pr_status.is_some());-- if any_ci_fetched {- log::debug!("Skipping CI tools detection - CI status already fetched");- } else {- // No CI was fetched - run full detection to show helpful hint- let gitlab_host = repo- .worktree_root()- .ok()- .and_then(|p| p.to_str().map(|s| s.to_string()))- .and_then(|p| ci_status::get_gitlab_host_for_repo(&p));- let ci_tools = ci_status::CiToolsStatus::detect(gitlab_host.as_deref());-- if !ci_tools.any_available() {- use ci_status::{CiPlatform, get_platform_for_repo};- use color_print::cformat;- use worktrunk::config::ProjectConfig;- use worktrunk::styling::hint_message;-- // Detect platform from repo's remote URL (with config override support)- let project_config = ProjectConfig::load(&repo, true).ok().flatten();- let platform_override = project_config.as_ref().and_then(|c| c.ci_platform());- let platform = repo- .worktree_root()- .ok()- .and_then(|root| get_platform_for_repo(root.to_str()?, platform_override));-- // Only show hint for the relevant platform's tool- let hint = match platform {- Some(CiPlatform::GitHub) => {- if ci_tools.gh_installed && !ci_tools.gh_authenticated {- Some(cformat!(- "CI status unavailable; run <bright-black>gh auth login</> to authenticate"- ))- } else if !ci_tools.gh_installed {- Some(cformat!(- "CI status unavailable; install <bright-black>gh</>"- ))- } else {- None- }- }- Some(CiPlatform::GitLab) => {- if ci_tools.glab_installed && !ci_tools.glab_authenticated {- Some(cformat!(- "CI status unavailable; run <bright-black>glab auth login</> to authenticate"- ))- } else if !ci_tools.glab_installed {- Some(cformat!(- "CI status unavailable; install <bright-black>glab</>"- ))- } else {- None- }- }- None => None, // Unknown platform - don't show any hint- };-- if let Some(message) = hint {- crate::output::blank()?;- crate::output::print(hint_message(message))?;- }- }- }- }-Ok(())}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex aebd6dc36..39508f11d 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -46,7 +46,7 @@ fn collect_merge_commands(// Collect pre-commit commands if we'll commit (direct or via squash)let mut hooks = Vec::new();- if commit && verify && repo.is_dirty()? {+ if commit && verify && repo.current_worktree().is_dirty()? {hooks.push(HookType::PreCommit);}@@ -84,7 +84,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let current_branch = env.require_branch("merge")?.to_string();// Validate --no-commit: requires clean working tree- if !commit && repo.is_dirty()? {+ if !commit && repo.current_worktree().is_dirty()? {return Err(worktrunk::git::GitError::UncommittedChanges {action: Some("merge with --no-commit".into()),branch: Some(current_branch.clone()),@@ -101,7 +101,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let target_worktree_path = repo.worktree_for_branch(&target_branch)?;// When current == target or we're in the main worktree, disable remove (can't remove it)- let in_main = !repo.is_in_worktree().unwrap_or(false);+ let in_main = !repo.current_worktree().is_linked().unwrap_or(false);let on_target = current_branch == target_branch;let remove_effective = remove && !on_target && !in_main;@@ -122,7 +122,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {};// Handle uncommitted changes (skip if --no-commit) - track whether commit occurred- let committed = if commit && repo.is_dirty()? {+ let committed = if commit && repo.current_worktree().is_dirty()? {if squash_enabled {false // Squash path handles staging and committing} else {@@ -203,15 +203,15 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if remove_effective {// STEP 1: Check for uncommitted changes before attempting cleanup// This prevents showing "Cleaning up worktree..." before failing- repo.ensure_clean_working_tree("remove worktree after merge", Some(¤t_branch))?;+ repo.current_worktree()+ .ensure_clean("remove worktree after merge", Some(¤t_branch))?;// STEP 2: Remove worktree via shared remove output handler so final message matches wt remove- let worktree_root = repo.worktree_root()?.to_path_buf();+ let worktree_root = repo.current_worktree().root()?.to_path_buf();// After a successful merge, compute integration reason from main_path- let main_repo = worktrunk::git::Repository::at(&destination_path);- let effective_target = main_repo.effective_integration_target(&target_branch);+ let effective_target = repo.effective_integration_target(&target_branch);let mut provider =- worktrunk::git::LazyGitIntegration::new(&main_repo, ¤t_branch, &effective_target);+ worktrunk::git::LazyGitIntegration::new(repo, ¤t_branch, &effective_target);let integration_reason = worktrunk::git::check_integration(&mut provider);// Compute expected_path for path mismatch detectionlet expected_path = get_path_mismatch(repo, ¤t_branch, &worktree_root, config);@@ -247,15 +247,12 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if verify {// Execute post-merge commands in the destination worktree// This runs after cleanup so the context is clear to the user- // Create a fresh Repository instance at the destination (the old repo may be invalid)- let destination_repo = Repository::at(&destination_path);- let destination_repo_root = destination_path.clone();let ctx = CommandContext::new(- &destination_repo,+ repo,config,Some(¤t_branch),&destination_path,- &destination_repo_root,+ &destination_path,yes,);// Show path when user's shell won't be in the destination directory where hooks run.diff --git a/src/commands/process.rs b/src/commands/process.rsindex 4f06a14c6..b92b0912a 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -44,7 +44,7 @@ pub fn spawn_detached(context_json: Option<&str>,) -> anyhow::Result<std::path::PathBuf> {// Create log directory in the common git directory- let log_dir = repo.wt_logs_dir()?;+ let log_dir = repo.wt_logs_dir();fs::create_dir_all(&log_dir).with_context(|| {format!("Failed to create log directory {}",diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex e5ffcae5e..02b2ad943 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -76,7 +76,7 @@ impl RepositoryCliExt for Repository {force_worktree: bool,config: &WorktrunkConfig,) -> anyhow::Result<RemoveResult> {- let current_path = self.worktree_root()?.to_path_buf();+ let current_path = self.current_worktree().root()?.to_path_buf();let worktrees = self.list_worktrees()?;// Home worktree: prefer default branch's worktree, fall back to first worktree,// then repo base for bare repos with no worktrees.@@ -155,16 +155,14 @@ impl RepositoryCliExt for Repository {}};- // Create Repository at target for validation- let target_repo = Repository::at(&worktree_path);-// Cannot remove the main working tree (only linked worktrees can be removed)- if !target_repo.is_in_worktree()? {+ let target_wt = self.worktree_at(&worktree_path);+ if !target_wt.is_linked()? {return Err(GitError::CannotRemoveMainWorktree.into());}// Ensure the working tree is clean- target_repo.ensure_clean_working_tree("remove worktree", branch_name.as_deref())?;+ target_wt.ensure_clean("remove worktree", branch_name.as_deref())?;// Compute main_path and changed_directory based on whether we're removing currentlet (main_path, changed_directory) = if is_current {@@ -224,15 +222,15 @@ impl RepositoryCliExt for Repository {return Ok(None);}- let wt_repo = Repository::at(wt_path);- if !wt_repo.is_dirty()? {+ let wt = self.worktree_at(wt_path);+ if !wt.is_dirty()? {return Ok(None);}let push_files = self.changed_files(target_branch, "HEAD")?;// Use -z for NUL-separated output: handles filenames with spaces and renames correctly// Format: "XY path\0" for normal files, "XY new_path\0old_path\0" for renames/copies- let wt_status_output = wt_repo.run_command(&["status", "--porcelain", "-z"])?;+ let wt_status_output = wt.run_command(&["status", "--porcelain", "-z"])?;let wt_files: Vec<String> = parse_porcelain_z(&wt_status_output);@@ -268,13 +266,13 @@ impl RepositoryCliExt for Repository {)))?;let stash_output =- wt_repo.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;+ wt.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;if stash_output.contains("No local changes to save") {return Ok(None);}- let list_output = wt_repo.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;+ let list_output = wt.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;let mut parts = list_output.split('\0');let mut stash_ref = None;while let Some(id) = parts.next() {@@ -339,10 +337,12 @@ fn compute_integration_reason(return None;}let (branch, target) = branch_name.zip(target_branch)?;- let main_repo = Repository::at(main_path);- let effective_target = main_repo.effective_integration_target(target);- let mut provider =- worktrunk::git::LazyGitIntegration::new(&main_repo, branch, &effective_target);+ // Use main_path for git operations - this is where the user will end up,+ // and integration checks need to run from a stable location that won't be+ // removed during the operation.+ let repo = Repository::at(main_path).ok()?;+ let effective_target = repo.effective_integration_target(target);+ let mut provider = worktrunk::git::LazyGitIntegration::new(&repo, branch, &effective_target);worktrunk::git::check_integration(&mut provider)}@@ -378,7 +378,6 @@ pub(crate) struct TargetWorktreeStash {}struct StashData {- repo: Repository,path: PathBuf,stash_ref: String,}@@ -391,9 +390,17 @@ impl StashData {format_path_for_display(&self.path))));- if let Err(_e) = self- .repo- .run_command(&["stash", "pop", "--quiet", &self.stash_ref])+ let Ok(repo) = Repository::current() else {+ let _ = crate::output::print(warning_message(cformat!(+ "Failed to restore stash <bold>{stash_ref}</> - run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",+ stash_ref = self.stash_ref,+ path = format_path_for_display(&self.path),+ )));+ return;+ };+ if let Err(_e) =+ repo.worktree_at(&self.path)+ .run_command(&["stash", "pop", "--quiet", &self.stash_ref]){let _ = crate::output::print(warning_message(cformat!("Failed to restore stash <bold>{stash_ref}</> - run <bold>git stash pop {stash_ref}</> in <bold>{path}</>",@@ -416,7 +423,6 @@ impl TargetWorktreeStash {pub(crate) fn new(path: &Path, stash_ref: String) -> Self {Self {inner: Some(StashData {- repo: Repository::at(path),path: path.to_path_buf(),stash_ref,}),diff --git a/src/commands/select.rs b/src/commands/select.rsindex fb4cb7ddb..dc761b8c2 100644--- a/src/commands/select.rs+++ b/src/commands/select.rs@@ -453,7 +453,9 @@ impl WorktreeSkimItem {/// Common diff rendering pattern: check stat, show stat + full diff if non-emptyfn render_diff_preview(&self, args: &[&str], no_changes_msg: &str, width: usize) -> String {let mut output = String::new();- let repo = Repository::current();+ let Ok(repo) = Repository::current() else {+ return no_changes_msg.to_string();+ };// Check stat output firstlet mut stat_args = args.to_vec();@@ -515,7 +517,9 @@ impl WorktreeSkimItem {use worktrunk::styling::INFO_SYMBOL;let branch = self.item.branch_name();- let repo = Repository::current();+ let Ok(repo) = Repository::current() else {+ return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");+ };let Ok(default_branch) = repo.default_branch() else {return cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits ahead of main\n");};@@ -606,9 +610,14 @@ impl WorktreeSkimItem {let show_timestamps = width >= TIMESTAMP_WIDTH_THRESHOLD;// Calculate how many log lines fit in preview (height minus header)let log_limit = height.saturating_sub(HEADER_LINES).max(1);- let repo = Repository::current();let head = self.item.head();let branch = self.item.branch_name();+ let Ok(repo) = Repository::current() else {+ output.push_str(&cformat!(+ "{INFO_SYMBOL} <bold>{branch}</> has no commits\n"+ ));+ return output;+ };let Ok(default_branch) = repo.default_branch() else {output.push_str(&cformat!("{INFO_SYMBOL} <bold>{branch}</> has no commits\n"@@ -851,7 +860,7 @@ pub fn handle_select() -> anyhow::Result<()> {anyhow::bail!("wt select requires an interactive terminal");}- let repo = Repository::current();+ let repo = Repository::current()?;// Initialize preview mode state file (auto-cleanup on drop)let state = PreviewState::new();diff --git a/src/commands/statusline.rs b/src/commands/statusline.rsindex f5cf17063..da8a15929 100644--- a/src/commands/statusline.rs+++ b/src/commands/statusline.rs@@ -171,8 +171,9 @@ pub fn run(claude_code: bool) -> Result<()> {};// Git status segments (skip links in claude-code mode - OSC 8 not supported)- let repo = Repository::at(&cwd);- if repo.git_dir().is_ok() {+ if let Ok(repo) = Repository::current()+ && repo.worktree_at(&cwd).git_dir().is_ok()+ {let git_segments = get_git_status_segments(&repo, &cwd, !claude_code)?;// In claude-code mode, skip branch segment if directory matches worktrunk template@@ -255,7 +256,7 @@ fn get_git_status_segments(let Some(wt) = current_worktree else {// Not in a worktree - just show branch name as a segment- if let Ok(Some(branch)) = repo.current_branch() {+ if let Ok(Some(branch)) = repo.current_worktree().branch() {return Ok(vec![StatuslineSegment::from_column(branch.to_string(),ColumnKind::Branch,diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex eb89e307a..3acd77a82 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -237,7 +237,7 @@ pub fn handle_squash(generator.emit_hint_if_needed()?;// Get current branch and repo name for template variables- let repo_root = repo.worktree_root()?;+ let repo_root = repo.current_worktree().root()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())@@ -293,13 +293,16 @@ pub fn step_show_squash_prompt(target: Option<&str>,config: &worktrunk::config::CommitGenerationConfig,) -> anyhow::Result<()> {- let repo = Repository::current();+ 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());+ let current_branch = repo+ .current_worktree()+ .branch()?+ .unwrap_or_else(|| "HEAD".to_string());// Get merge base with target branchlet merge_base = repo.merge_base("HEAD", &target_branch)?;@@ -309,7 +312,7 @@ pub fn step_show_squash_prompt(let subjects = repo.commit_subjects(&range)?;// Get repo name from directory- let repo_root = repo.worktree_root()?;+ let repo_root = repo.current_worktree().root()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())@@ -339,7 +342,7 @@ pub enum RebaseResult {pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {use super::repository_ext::RepositoryCliExt;- let repo = Repository::current();+ let repo = Repository::current()?;// Get target branch (default to default branch if not provided)let target_branch = repo.resolve_target_branch(target)?;@@ -422,7 +425,7 @@ pub fn step_copy_ignored(use ignore::gitignore::GitignoreBuilder;use std::fs;- let repo = Repository::current();+ let repo = Repository::current()?;// Resolve source and destination worktree pathslet (source_path, source_context) = match from {@@ -443,7 +446,7 @@ pub fn step_copy_ignored(branch: branch.to_string(),}})?,- None => repo.worktree_root()?.to_path_buf(),+ None => repo.current_worktree().root()?.to_path_buf(),};if source_path == dest_path {diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 0fc06b136..55db65e17 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -453,11 +453,11 @@ pub fn handle_switch(no_verify: bool,config: &WorktrunkConfig,) -> anyhow::Result<(SwitchResult, SwitchBranchInfo)> {- let repo = Repository::current();+ let repo = Repository::current()?;// Get the actual current branch BEFORE switching.// This is what we'll record as "previous" in history for `wt switch -` support.- let actual_current_branch = repo.current_branch().ok().flatten();+ let actual_current_branch = repo.current_worktree().branch().ok().flatten();// Resolve special branch names ("@" for current, "-" for previous)let resolved_branch = repo@@ -689,8 +689,7 @@ pub fn handle_switch(// This happens when we don't use --create and the branch exists on a remotelet from_remote = if !create {// Query the new worktree for its upstream tracking branch- let worktree_repo = Repository::at(&worktree_path);- worktree_repo.upstream_branch(&resolved_branch)?+ repo.upstream_branch(&resolved_branch)?} else {None};@@ -756,7 +755,7 @@ pub fn handle_remove(force_worktree: bool,config: &WorktrunkConfig,) -> anyhow::Result<RemoveResult> {- let repo = Repository::current();+ let repo = Repository::current()?;// Progress message is shown in handle_removed_worktree_output() after pre-remove hooks runrepo.prepare_worktree_removal(@@ -777,7 +776,7 @@ pub fn handle_remove_current(force_worktree: bool,config: &WorktrunkConfig,) -> anyhow::Result<RemoveResult> {- let repo = Repository::current();+ let repo = Repository::current()?;// Progress message is shown in handle_removed_worktree_output() after pre-remove hooks runrepo.prepare_worktree_removal(@@ -883,7 +882,7 @@ pub fn handle_push(verb: &str,operations: Option<MergeOperations>,) -> anyhow::Result<()> {- let repo = Repository::current();+ let repo = Repository::current()?;// Get target branch (default to default branch if not provided)let target_branch = repo.resolve_target_branch(target)?;@@ -989,7 +988,7 @@ pub fn handle_push(}// Get git common dir for the push- let git_common_dir = repo.git_common_dir()?;+ let git_common_dir = repo.git_common_dir();let git_common_dir_str = git_common_dir.to_string_lossy();// Perform the push - stash guard will auto-restore on any exit pathdiff --git a/src/completion.rs b/src/completion.rsindex 5aad1619e..74a206153 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -268,8 +268,8 @@ fn complete_hook_commands() -> Vec<CompletionCandidate> {// Load project config and add project hook names// Pass write_hints=false to avoid side effects during completion- let repo = Repository::current();- if let Ok(Some(project_config)) = ProjectConfig::load(&repo, false)+ if let Ok(repo) = Repository::current()+ && let Ok(Some(project_config)) = ProjectConfig::load(&repo, false)&& let Some(config) = project_config.hooks.get(hook_type){add_named_commands(&mut candidates, config);@@ -319,7 +319,7 @@ fn complete_branches(return Vec::new();}- let branches = match Repository::current().branches_for_completion() {+ let branches = match Repository::current().and_then(|repo| repo.branches_for_completion()) {Ok(b) => b,Err(_) => return Vec::new(),};diff --git a/src/config/project.rs b/src/config/project.rsindex ece6eef10..2b320449b 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -123,7 +123,8 @@ impl ProjectConfig {write_hints: bool,) -> Result<Option<Self>, ConfigError> {let repo_root = repo- .worktree_root()+ .current_worktree()+ .root().map_err(|e| ConfigError::Message(format!("Failed to get worktree root: {}", e)))?;let config_path = repo_root.join(".config").join("wt.toml");diff --git a/src/diagnostic.rs b/src/diagnostic.rsindex ca68f420a..b826c973a 100644--- a/src/diagnostic.rs+++ b/src/diagnostic.rs@@ -170,7 +170,7 @@ impl DiagnosticReport {/// Write the diagnostic report to a file.fn write_file(&self, repo: &Repository) -> Option<PathBuf> {- let log_dir = repo.wt_logs_dir().ok()?;+ let log_dir = repo.wt_logs_dir();std::fs::create_dir_all(&log_dir).ok()?;let path = log_dir.join("diagnostic.md");@@ -258,7 +258,7 @@ fn get_config_show_output(repo: &Repository) -> Option<String> {}// Project config- if let Ok(root) = repo.worktree_root() {+ if let Ok(root) = repo.current_worktree().root() {let project_config_path = root.join(".config/wt.toml");output.push_str(&format!("\n{}",diff --git a/src/git/mod.rs b/src/git/mod.rsindex 6b49abace..e4ebdc3f6 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -41,7 +41,7 @@ pub use error::{exit_code,};pub use parse::{parse_porcelain_z, parse_untracked_files};-pub use repository::{Repository, ResolvedWorktree, set_base_path};+pub use repository::{Repository, ResolvedWorktree, WorktreeView, set_base_path};pub use url::{GitRemoteUrl, parse_owner_repo, parse_remote_host, parse_remote_owner};/// Why branch content is considered integrated into the target branch.///@@ -383,9 +383,8 @@ impl Worktree {/// Helper function to read rebase branch informationfn read_rebase_branch(worktree_path: &PathBuf) -> Option<String> {- // Create a Repository instance to get the correct git directory- let repo = Repository::at(worktree_path);- let git_dir = repo.git_dir().ok()?;+ let repo = Repository::current().ok()?;+ let git_dir = repo.worktree_at(worktree_path).git_dir().ok()?;// Check both rebase-merge and rebase-applyfor rebase_dir in ["rebase-merge", "rebase-apply"] {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex c076bd2bb..9a473ab6e 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -131,66 +131,313 @@ fn base_path() -> &'static PathBuf {.unwrap_or_else(|| DEFAULT.get_or_init(|| PathBuf::from(".")))}-/// Repository context for git operations.+/// Repository state for git operations.///-/// Provides a more ergonomic API than the `*_in(path, ...)` functions by-/// encapsulating the repository path.+/// Represents the shared state of a git repository (the `.git` directory).+/// For worktree-specific operations, use [`WorktreeView`] obtained via+/// [`current_worktree()`](Self::current_worktree) or [`worktree_at()`](Self::worktree_at).////// # Examples////// ```no_run/// use worktrunk::git::Repository;///-/// let repo = Repository::current();-/// let branch = repo.current_branch()?;-/// let is_dirty = repo.is_dirty()?;+/// let repo = Repository::current()?;+/// let wt = repo.current_worktree();+///+/// // Repo-wide operations+/// let default = repo.default_branch()?;+///+/// // Worktree-specific operations+/// let branch = wt.branch()?;+/// let dirty = wt.is_dirty()?;/// # Ok::<(), anyhow::Error>(())/// ```-#[derive(Debug)]+#[derive(Debug, Clone)]pub struct Repository {+ /// Path used for discovering the repository and running git commands.+ /// For repo-wide operations, any path within the repo works.+ discovery_path: PathBuf,+ /// The shared .git directory, computed at construction time.+ /// Used as key for global cache lookup.+ git_common_dir: PathBuf,+}++/// A view into a specific worktree within a repository.+///+/// This type borrows a [`Repository`] and holds a path to a specific worktree.+/// All worktree-specific operations (like `branch`, `is_dirty`) are on this type.+///+/// # Examples+///+/// ```no_run+/// use worktrunk::git::Repository;+///+/// let repo = Repository::current()?;+/// let wt = repo.current_worktree();+///+/// // Worktree-specific operations+/// let _ = wt.is_dirty();+/// let _ = wt.branch();+///+/// // View at a different worktree+/// let _other = repo.worktree_at("/path/to/other/worktree");+/// # Ok::<(), anyhow::Error>(())+/// ```+#[derive(Debug)]+#[must_use]+pub struct WorktreeView<'a> {+ repo: &'a Repository,path: PathBuf,- /// Per-instance cache of git_common_dir, used as key for global cache lookup.- git_common_dir: OnceCell<PathBuf>,}-impl Repository {- /// Create a repository context at the specified path.- pub fn at(path: impl Into<PathBuf>) -> Self {- Self {- path: path.into(),- git_common_dir: OnceCell::new(),+/// Get a short display name for a path, used in logging context.+fn path_to_logging_context(path: &Path) -> String {+ if path.to_str() == Some(".") {+ ".".to_string()+ } else {+ path.file_name()+ .and_then(|n| n.to_str())+ .unwrap_or(".")+ .to_string()+ }+}++impl<'a> WorktreeView<'a> {+ /// Run a git command in this worktree and return stdout.+ pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {+ use crate::shell_exec::run;++ let mut cmd = Command::new("git");+ cmd.args(args);+ cmd.current_dir(&self.path);++ let output = run(&mut cmd, Some(&path_to_logging_context(&self.path)))+ .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = stderr.replace('\r', "\n");+ for line in stderr.trim().lines() {+ log::debug!(" ! {}", line);+ }+ let stdout = String::from_utf8_lossy(&output.stdout);+ let error_msg = [stderr.trim(), stdout.trim()]+ .into_iter()+ .filter(|s| !s.is_empty())+ .collect::<Vec<_>>()+ .join("\n");+ bail!("{}", error_msg);}++ let stdout = String::from_utf8_lossy(&output.stdout).into_owned();+ if !stdout.is_empty() {+ for line in stdout.trim().lines() {+ log::debug!(" {}", line);+ }+ }+ Ok(stdout)}- /// Create a repository context for the current directory.+ // =========================================================================+ // Worktree-specific methods+ // =========================================================================++ /// Get the branch checked out in this worktree, or None if in detached HEAD state.///- /// This is the most common usage pattern. If the -C flag was used,+ /// Result is cached in the global shared cache (keyed by worktree path).+ pub fn branch(&self) -> anyhow::Result<Option<String>> {+ let cache = get_cache(self.repo.git_common_dir.clone());++ Ok(cache+ .current_branches+ .entry(self.path.clone())+ .or_insert_with(|| {+ self.run_command(&["branch", "--show-current"])+ .ok()+ .and_then(|s| {+ let branch = s.trim();+ if branch.is_empty() {+ None // Detached HEAD+ } else {+ Some(branch.to_string())+ }+ })+ })+ .clone())+ }++ /// Check if the working tree has uncommitted changes.+ pub fn is_dirty(&self) -> anyhow::Result<bool> {+ let stdout = self.run_command(&["status", "--porcelain"])?;+ Ok(!stdout.trim().is_empty())+ }++ /// Get the root directory of this worktree (top-level of the working tree).+ ///+ /// Returns the canonicalized absolute path to the top-level directory.+ /// This could be the main worktree or a linked worktree.+ /// Result is cached in the global shared cache (keyed by worktree path).+ pub fn root(&self) -> anyhow::Result<PathBuf> {+ let cache = get_cache(self.repo.git_common_dir.clone());++ Ok(cache+ .worktree_roots+ .entry(self.path.clone())+ .or_insert_with(|| {+ self.run_command(&["rev-parse", "--show-toplevel"])+ .ok()+ .map(|s| PathBuf::from(s.trim()))+ .and_then(|p| canonicalize(&p).ok())+ .unwrap_or_else(|| self.path.clone())+ })+ .clone())+ }++ /// Get the git directory (may be different from common-dir in worktrees).+ ///+ /// Always returns an absolute path, resolving any relative paths returned by git.+ pub fn git_dir(&self) -> anyhow::Result<PathBuf> {+ let stdout = self.run_command(&["rev-parse", "--git-dir"])?;+ let path = PathBuf::from(stdout.trim());++ // Resolve relative paths against the worktree's directory+ if path.is_relative() {+ canonicalize(self.path.join(&path)).context("Failed to resolve git directory")+ } else {+ Ok(path)+ }+ }++ /// Check if a rebase is in progress.+ pub fn is_rebasing(&self) -> anyhow::Result<bool> {+ let git_dir = self.git_dir()?;+ Ok(git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists())+ }++ /// Check if a merge is in progress.+ pub fn is_merging(&self) -> anyhow::Result<bool> {+ let git_dir = self.git_dir()?;+ Ok(git_dir.join("MERGE_HEAD").exists())+ }++ /// Check if this is a linked worktree (vs the main worktree).+ ///+ /// Returns `true` for linked worktrees (created via `git worktree add`),+ /// `false` for the main worktree (original clone location).+ ///+ /// Implementation: compares `git_dir` vs `common_dir`. In linked worktrees,+ /// the `.git` file points to `.git/worktrees/NAME`, so they differ. In the+ /// main worktree, both point to the same `.git` directory.+ ///+ /// For bare repos, all worktrees are "linked" (returns `true`).+ pub fn is_linked(&self) -> anyhow::Result<bool> {+ let git_dir = self.git_dir()?;+ let common_dir = self.repo.git_common_dir();+ Ok(git_dir != common_dir)+ }++ /// Ensure this worktree is clean (no uncommitted changes).+ ///+ /// Returns an error if there are uncommitted changes.+ /// - `action` describes what was blocked (e.g., "remove worktree").+ /// - `branch` identifies which branch for multi-worktree operations.+ pub fn ensure_clean(&self, action: &str, branch: Option<&str>) -> anyhow::Result<()> {+ if self.is_dirty()? {+ return Err(GitError::UncommittedChanges {+ action: Some(action.into()),+ branch: branch.map(String::from),+ }+ .into());+ }+ Ok(())+ }+}++impl Repository {+ /// Discover the repository from the current directory.+ ///+ /// This is the primary way to create a Repository. If the -C flag was used,/// this uses that path instead of the actual current directory.- pub fn current() -> Self {+ ///+ /// For worktree-specific operations on paths other than cwd, use+ /// `repo.worktree_at(path)` to get a [`WorktreeView`].+ pub fn current() -> anyhow::Result<Self> {Self::at(base_path().clone())}- /// Get the base path this repository was created with.- pub fn base_path(&self) -> &Path {- &self.path+ /// Discover the repository from the specified path.+ ///+ /// **For background tasks and tests only.** Inline production code should use+ /// [`Repository::current()`] combined with [`Repository::worktree_at()`] for+ /// worktree-specific operations.+ ///+ /// Use cases:+ /// - **Background tasks**: Tasks spawned to operate on specific worktrees+ /// (e.g., `wt list` tasks that analyze each worktree in parallel)+ /// - **Tests**: Tests run from the project directory but need to operate on+ /// test repositories in temporary directories+ pub fn at(path: impl Into<PathBuf>) -> anyhow::Result<Self> {+ let discovery_path = path.into();+ let git_common_dir = Self::resolve_git_common_dir(&discovery_path)?;+ Ok(Self {+ discovery_path,+ git_common_dir,+ })+ }++ /// Resolve the git common directory for a path.+ // TODO: Consolidate the "Failed to execute: git ..." context pattern.+ // Currently duplicated in WorktreeView::run_command, Repository::run_command, and here.+ // Consider extracting a helper that handles the context message consistently.+ fn resolve_git_common_dir(discovery_path: &Path) -> anyhow::Result<PathBuf> {+ use crate::shell_exec::run;++ let mut cmd = Command::new("git");+ cmd.args(["rev-parse", "--git-common-dir"]);+ cmd.current_dir(discovery_path);++ let output = run(&mut cmd, Some(&path_to_logging_context(discovery_path)))+ .context("Failed to execute: git rev-parse --git-common-dir")?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ bail!("{}", stderr.trim());+ }++ let stdout = String::from_utf8_lossy(&output.stdout);+ let path = PathBuf::from(stdout.trim());+ if path.is_relative() {+ canonicalize(discovery_path.join(&path))+ .context("Failed to resolve git common directory")+ } else {+ Ok(path)+ }+ }++ /// Get the path this repository was discovered from.+ ///+ /// This is primarily for internal use. For worktree operations,+ /// use [`current_worktree()`](Self::current_worktree) or [`worktree_at()`](Self::worktree_at).+ pub fn discovery_path(&self) -> &Path {+ &self.discovery_path}- /// Compute and cache the git common directory for this instance.+ /// Get a worktree view at the current directory.///- /// This is the key used to look up the shared cache.- fn compute_git_common_dir(&self) -> anyhow::Result<PathBuf> {- self.git_common_dir- .get_or_try_init(|| {- let stdout = self.run_command(&["rev-parse", "--git-common-dir"])?;- let path = PathBuf::from(stdout.trim());- if path.is_relative() {- canonicalize(self.path.join(&path))- .context("Failed to resolve git common directory")- } else {- Ok(path)- }- })- .cloned()+ /// This is the primary way to get a [`WorktreeView`] for worktree-specific operations.+ pub fn current_worktree(&self) -> WorktreeView<'_> {+ self.worktree_at(base_path().clone())+ }++ /// Get a worktree view at a specific path.+ ///+ /// Use this when you need to operate on a worktree other than the current one.+ pub fn worktree_at(&self, path: impl Into<PathBuf>) -> WorktreeView<'_> {+ WorktreeView {+ repo: self,+ path: path.into(),+ }}/// Get the primary remote name for this repository.@@ -206,7 +453,7 @@ impl Repository {////// [1]: https://git-scm.com/docs/git-config#Documentation/git-config.txt-checkoutdefaultRemotepub fn primary_remote(&self) -> anyhow::Result<String> {- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());cache.primary_remote.get_or_init(|| {@@ -254,6 +501,13 @@ impl Repository {.filter(|url| !url.is_empty())}+ /// Get the URL for the primary remote, if configured.+ pub fn primary_remote_url(&self) -> Option<String> {+ self.primary_remote()+ .ok()+ .and_then(|remote| self.remote_url(&remote))+ }+/// Check if a local git branch exists.pub fn local_branch_exists(&self, branch: &str) -> anyhow::Result<bool> {Ok(self@@ -308,35 +562,11 @@ impl Repository {Ok(remotes)}- /// Get the current branch name, or None if in detached HEAD state.- ///- /// Result is cached in the global shared cache (keyed by worktree path).- pub fn current_branch(&self) -> anyhow::Result<Option<String>> {- let cache = get_cache(self.compute_git_common_dir()?);-- Ok(cache- .current_branches- .entry(self.path.clone())- .or_insert_with(|| {- self.run_command(&["branch", "--show-current"])- .ok()- .and_then(|s| {- let branch = s.trim();- if branch.is_empty() {- None // Detached HEAD- } else {- Some(branch.to_string())- }- })- })- .clone())- }-/// Get the current branch name, or error if in detached HEAD state.////// `action` describes what requires being on a branch (e.g., "merge").pub fn require_current_branch(&self, action: &str) -> anyhow::Result<String> {- self.current_branch()?.ok_or_else(|| {+ self.current_worktree().branch()?.ok_or_else(|| {GitError::DetachedHead {action: Some(action.into()),}@@ -456,7 +686,7 @@ impl Repository {/// - `Err` if "-" but no previous branch in historypub fn resolve_worktree_name(&self, name: &str) -> anyhow::Result<String> {match name {- "@" => self.current_branch()?.ok_or_else(|| {+ "@" => self.current_worktree().branch()?.ok_or_else(|| {GitError::DetachedHead {action: Some("resolve '@' to current branch".into()),}@@ -500,9 +730,12 @@ impl Repository {"@" => {// Current worktree by path - works even in detached HEAD// If worktree_root fails (e.g., in bare repo directory), give a clear error- let path = self.worktree_root().map_err(|_| GitError::NotInWorktree {- action: Some("resolve '@'".into()),- })?;+ let path = self+ .current_worktree()+ .root()+ .map_err(|_| GitError::NotInWorktree {+ action: Some("resolve '@'".into()),+ })?;let worktrees = self.list_worktrees()?;let branch = worktrees.iter()@@ -545,7 +778,7 @@ impl Repository {/// Detection results are cached to `worktrunk.default-branch` for future calls./// Result is cached in the shared repo cache (shared across all worktrees).pub fn default_branch(&self) -> anyhow::Result<String> {- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());cache.default_branch.get_or_try_init(|| {@@ -626,8 +859,8 @@ impl Repository {// - Linked worktrees: HEAD points to CURRENT branch, so skip this heuristic// - Normal repos: HEAD points to CURRENT branch, so skip this heuristiclet is_bare = self.is_bare().unwrap_or(false);- let in_worktree = self.is_in_worktree().unwrap_or(false);- if ((is_bare && !in_worktree) || branches.is_empty())+ let in_linked_worktree = self.current_worktree().is_linked().unwrap_or(false);+ if ((is_bare && !in_linked_worktree) || branches.is_empty())&& let Ok(head_ref) = self.run_command(&["symbolic-ref", "HEAD"])&& let Some(branch) = head_ref.trim().strip_prefix("refs/heads/"){@@ -676,31 +909,16 @@ impl Repository {/// Result is cached per Repository instance (also used as key for global cache).////// [1]: https://git-scm.com/docs/git-rev-parse#Documentation/git-rev-parse.txt---git-common-dir- pub fn git_common_dir(&self) -> anyhow::Result<PathBuf> {- self.compute_git_common_dir()+ pub fn git_common_dir(&self) -> &Path {+ &self.git_common_dir}/// Get the directory where worktrunk background logs are stored.////// Logs are centralized under the main worktree's git directory:/// `.git/wt-logs/`.- pub fn wt_logs_dir(&self) -> anyhow::Result<PathBuf> {- Ok(self.git_common_dir()?.join("wt-logs"))- }-- /// Get the git directory (may be different from common-dir in worktrees).- ///- /// Always returns an absolute path, resolving any relative paths returned by git.- pub fn git_dir(&self) -> anyhow::Result<PathBuf> {- let stdout = self.run_command(&["rev-parse", "--git-dir"])?;- let path = PathBuf::from(stdout.trim());-- // Resolve relative paths against the repo's directory- if path.is_relative() {- canonicalize(self.path.join(&path)).context("Failed to resolve git directory")- } else {- Ok(path)- }+ pub fn wt_logs_dir(&self) -> PathBuf {+ self.git_common_dir().join("wt-logs")}/// Get the base directory where worktrees are created relative to.@@ -711,12 +929,12 @@ impl Repository {/// This is the path that should be used when constructing worktree paths./// Result is cached in the global shared cache (same for all worktrees in a repo).pub fn worktree_base(&self) -> anyhow::Result<PathBuf> {- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());cache.worktree_base.get_or_try_init(|| {let git_common_dir =- canonicalize(self.git_common_dir()?).context("Failed to canonicalize path")?;+ canonicalize(self.git_common_dir()).context("Failed to canonicalize path")?;if self.is_bare()? {Ok(git_common_dir)@@ -762,7 +980,7 @@ impl Repository {/// worktrees at templated paths, including the default branch./// Result is cached in the shared repo cache (shared across all worktrees).pub fn is_bare(&self) -> anyhow::Result<bool> {- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());cache.is_bare.get_or_try_init(|| {@@ -772,81 +990,6 @@ impl Repository {.copied()}- /// Check if the working tree has uncommitted changes.- pub fn is_dirty(&self) -> anyhow::Result<bool> {- let stdout = self.run_command(&["status", "--porcelain"])?;- Ok(!stdout.trim().is_empty())- }-- /// Ensure the working tree is clean (no uncommitted changes).- ///- /// Returns an error if there are uncommitted changes.- /// - `action` describes what was blocked (e.g., "remove worktree").- /// - `branch` identifies which branch for multi-worktree operations.- pub fn ensure_clean_working_tree(- &self,- action: &str,- branch: Option<&str>,- ) -> anyhow::Result<()> {- if self.is_dirty()? {- return Err(GitError::UncommittedChanges {- action: Some(action.into()),- branch: branch.map(String::from),- }- .into());- }- Ok(())- }-- /// Get the worktree root directory (top-level of the working tree).- ///- /// Returns the canonicalized absolute path to the top-level directory of the- /// current working tree. This could be the main worktree or a linked worktree.- /// Result is cached in the global shared cache (keyed by worktree path).- pub fn worktree_root(&self) -> anyhow::Result<PathBuf> {- let cache = get_cache(self.compute_git_common_dir()?);-- Ok(cache- .worktree_roots- .entry(self.path.clone())- .or_insert_with(|| {- self.run_command(&["rev-parse", "--show-toplevel"])- .ok()- .map(|s| PathBuf::from(s.trim()))- .and_then(|p| canonicalize(&p).ok())- .unwrap_or_else(|| self.path.clone())- })- .clone())- }-- /// Check if this is a linked worktree (vs the main worktree).- ///- /// Returns `true` for linked worktrees (created via `git worktree add`),- /// `false` for the main worktree (original clone location).- ///- /// Implementation: compares `git_dir` vs `common_dir`. In linked worktrees,- /// the `.git` file points to `.git/worktrees/NAME`, so they differ. In the- /// main worktree, both point to the same `.git` directory.- ///- /// For bare repos, all worktrees are "linked" (returns `true`).- pub fn is_in_worktree(&self) -> anyhow::Result<bool> {- let git_dir = self.git_dir()?;- let common_dir = self.git_common_dir()?;- Ok(git_dir != common_dir)- }-- /// Check if a rebase is in progress.- pub fn is_rebasing(&self) -> anyhow::Result<bool> {- let git_dir = self.git_dir()?;- Ok(git_dir.join("rebase-merge").exists() || git_dir.join("rebase-apply").exists())- }-- /// Check if a merge is in progress.- pub fn is_merging(&self) -> anyhow::Result<bool> {- let git_dir = self.git_dir()?;- Ok(git_dir.join("MERGE_HEAD").exists())- }-/// Check if git's builtin fsmonitor daemon is enabled.////// Returns true only for `core.fsmonitor=true` (the builtin daemon).@@ -869,6 +1012,18 @@ impl Repository {}}+ /// Start fsmonitor daemon at a specific worktree path.+ ///+ /// Like `start_fsmonitor_daemon` but runs the command in the specified worktree.+ pub fn start_fsmonitor_daemon_at(&self, path: &Path) {+ if let Err(e) = self+ .worktree_at(path)+ .run_command(&["fsmonitor--daemon", "start"])+ {+ log::debug!("fsmonitor daemon start failed (usually fine): {e}");+ }+ }+/// Check if base is an ancestor of head (i.e., would be a fast-forward).////// See [`--is-ancestor`][1] for details.@@ -1059,9 +1214,9 @@ impl Repository {local_target.to_string()}- /// Get merge/rebase status for the worktree.+ /// Get merge/rebase status for the worktree at this repository's discovery path.pub fn worktree_state(&self) -> anyhow::Result<Option<String>> {- let git_dir = self.git_dir()?;+ let git_dir = self.worktree_at(self.discovery_path()).git_dir()?;// Check for mergeif git_dir.join("MERGE_HEAD").exists() {@@ -1165,8 +1320,8 @@ impl Repository {}};- // Get cache (may fail if git_common_dir detection fails)- let cache = self.compute_git_common_dir().ok().map(get_cache);+ // Get cache keyed by git_common_dir+ let cache = Some(get_cache(self.git_common_dir().to_path_buf()));let results: std::collections::HashMap<String, (usize, usize)> = output.lines()@@ -1194,7 +1349,7 @@ impl Repository {/// Returns cached results from a prior `batch_ahead_behind()` call, or None/// if the branch wasn't in the batch or batch wasn't run.pub fn get_cached_ahead_behind(&self, base: &str, branch: &str) -> Option<(usize, usize)> {- let cache = get_cache(self.compute_git_common_dir().ok()?);+ let cache = get_cache(self.git_common_dir().to_path_buf());cache.ahead_behind.get(&(base.to_string(), branch.to_string()))@@ -1405,7 +1560,7 @@ impl Repository {/// ```no_run/// use worktrunk::git::Repository;///- /// let repo = Repository::current();+ /// let repo = Repository::current()?;/// let sha = repo.create_safety_backup("feature → main (squash)")?;/// println!("Backup created: {}", sha);/// # Ok::<(), anyhow::Error>(())@@ -1598,7 +1753,7 @@ impl Repository {(commit2.to_string(), commit1.to_string())};- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());Ok(cache.merge_base@@ -1620,7 +1775,7 @@ impl Repository {/// ```no_run/// use worktrunk::git::Repository;///- /// let repo = Repository::current();+ /// let repo = Repository::current()?;/// let has_conflicts = repo.has_merge_conflicts("main", "feature-branch")?;/// # Ok::<(), anyhow::Error>(())/// ```@@ -1691,11 +1846,14 @@ impl Repository {Ok(raw_worktrees.into_iter().filter(|wt| !wt.bare).collect())}- /// Get the current worktree if we're inside one.+ /// Get the Worktree info struct for the current worktree, if we're inside one.////// Returns `None` if not in a worktree (e.g., in bare repo directory).- pub fn current_worktree(&self) -> anyhow::Result<Option<Worktree>> {- let current_path = match self.worktree_root() {+ ///+ /// Note: For worktree-specific operations, use [`current_worktree()`](Self::current_worktree)+ /// to get a [`WorktreeView`] instead.+ pub fn current_worktree_info(&self) -> anyhow::Result<Option<Worktree>> {+ let current_path = match self.current_worktree().root() {Ok(p) => p.to_path_buf(),Err(_) => return Ok(None),};@@ -1872,7 +2030,7 @@ impl Repository {////// Result is cached in the shared repo cache (shared across all worktrees).pub fn project_identifier(&self) -> anyhow::Result<String> {- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());cache.project_identifier.get_or_try_init(|| {@@ -1921,11 +2079,11 @@ impl Repository {/// Result is cached in the global shared cache (same config for all worktrees)./// Returns `None` if not in a worktree or if no config file exists.pub fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {- let cache = get_cache(self.compute_git_common_dir()?);+ let cache = get_cache(self.git_common_dir.clone());cache.project_config.get_or_try_init(|| {- match self.worktree_root() {+ match self.current_worktree().root() {Ok(_) => {ProjectConfig::load(self, true).context("Failed to load project config")}@@ -1939,28 +2097,20 @@ impl Repository {////// Returns "." for the current directory, or the directory name otherwise.fn logging_context(&self) -> String {- if self.path.to_str() == Some(".") {- ".".to_string()- } else {- self.path- .file_name()- .and_then(|n| n.to_str())- .unwrap_or("?")- .to_string()- }+ path_to_logging_context(&self.discovery_path)}/// Run a git command in this repository's context.///- /// Executes the git command with this repository's path as the working directory- /// and returns the stdout output.+ /// Executes the git command with this repository's discovery path as the working directory.+ /// For repo-wide operations, any path within the repo works.////// # Examples/// ```no_run/// use worktrunk::git::Repository;///- /// let repo = Repository::current();- /// let status = repo.run_command(&["status", "--porcelain"])?;+ /// let repo = Repository::current()?;+ /// let branches = repo.run_command(&["branch", "--list"])?;/// # Ok::<(), anyhow::Error>(())/// ```pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {@@ -1968,7 +2118,7 @@ impl Repository {let mut cmd = Command::new("git");cmd.args(args);- cmd.current_dir(&self.path);+ cmd.current_dir(&self.discovery_path);let output = run(&mut cmd, Some(&self.logging_context())).with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;@@ -2011,7 +2161,7 @@ impl Repository {/// ```no_run/// use worktrunk::git::Repository;///- /// let repo = Repository::current();+ /// let repo = Repository::current()?;/// let is_clean = repo.run_command_check(&["diff", "--quiet", "--exit-code"])?;/// # Ok::<(), anyhow::Error>(())/// ```@@ -2020,7 +2170,7 @@ impl Repository {let mut cmd = Command::new("git");cmd.args(args);- cmd.current_dir(&self.path);+ cmd.current_dir(&self.discovery_path);let output = run(&mut cmd, Some(&self.logging_context())).with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;diff --git a/src/llm.rs b/src/llm.rsindex c529069d6..a907c3bcf 100644--- a/src/llm.rs+++ b/src/llm.rs@@ -451,7 +451,7 @@ pub fn generate_commit_message(}// Fallback: generate a descriptive commit message based on changed files- let repo = Repository::current();+ let repo = Repository::current()?;// Use -z for NUL-separated output to handle filenames with spaces/newlineslet file_list = repo.run_command(&["diff", "--staged", "--name-only", "-z"])?;let staged_files = file_list@@ -494,7 +494,7 @@ fn try_generate_commit_message(/// 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();+ let repo = Repository::current()?;// Get staged diff and diffstat// Use -c flags to ensure consistent format regardless of user's git config@@ -514,10 +514,13 @@ pub fn build_commit_prompt(config: &CommitGenerationConfig) -> anyhow::Result<Stlet prepared = prepare_diff(diff_output, diff_stat);// Get current branch- let current_branch = repo.current_branch()?.unwrap_or_else(|| "HEAD".to_string());+ let current_branch = repo+ .current_worktree()+ .branch()?+ .unwrap_or_else(|| "HEAD".to_string());// Get repo name from directory- let repo_root = repo.worktree_root()?;+ let repo_root = repo.current_worktree().root()?;let repo_name = repo_root.file_name().and_then(|n| n.to_str())@@ -592,7 +595,7 @@ pub fn build_squash_prompt(repo_name: &str,config: &CommitGenerationConfig,) -> anyhow::Result<String> {- let repo = Repository::current();+ 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 configdiff --git a/src/main.rs b/src/main.rsindex 100b51eeb..6bcb0d633 100644--- a/src/main.rs+++ b/src/main.rs@@ -1286,7 +1286,7 @@ fn main() {// This ensures approval happens once at the command entry point// If user declines, skip hooks but continue with worktree operationlet approved = if verify {- let repo = Repository::current();+ let repo = Repository::current().context("Failed to switch worktree")?;let repo_root = repo.worktree_base().context("Failed to switch worktree")?;// Compute worktree path for template expansion in approval promptlet worktree_path = compute_worktree_path(&repo, &branch, &config)?;@@ -1359,7 +1359,7 @@ fn main() {// - post-switch: runs on ALL switches (shows "@ path" when shell won't be there)// - post-start: runs only when creating a NEW worktreeif !skip_hooks {- let repo = Repository::current();+ let repo = Repository::current()?;let repo_root = repo.worktree_base().context("Failed to switch worktree")?;let ctx = CommandContext::new(&repo,@@ -1451,15 +1451,17 @@ fn main() {// TODO(pre-remove-context): The approval context uses current worktree (cwd + current_branch),// but hooks execute in each target worktree. When removing another worktree, the approval// preview shows the wrong branch/path. Consider building approval context per target worktree.- let repo = Repository::current();+ let repo = Repository::current().context("Failed to remove worktree")?;let verify = if verify {// Create context for template expansion in approval promptlet worktree_path =std::env::current_dir().context("Failed to get current directory")?;let repo_root = repo.worktree_base().context("Failed to remove worktree")?;// Keep as Option so detached HEAD maps to None -> "HEAD" via branch_or_head()- let current_branch =- repo.current_branch().context("Failed to remove worktree")?;+ let current_branch = repo+ .current_worktree()+ .branch()+ .context("Failed to remove worktree")?;let ctx = CommandContext::new(&repo,&config,@@ -1494,7 +1496,7 @@ fn main() {use worktrunk::git::ResolvedWorktree;// When removing multiple worktrees, we need to handle the current worktree last// to avoid deleting the directory we're currently in- let current_worktree = repo.worktree_root().ok();+ let current_worktree = repo.current_worktree().root().ok();// Partition branches into current worktree, others, and branch-only.// Track all errors (resolution + removal) so we can report them and continue.@@ -1718,10 +1720,12 @@ fn write_vv_diagnostic(verbose: u8, command_line: &str, error_msg: Option<&str>)}// Use Repository::current() which honors the -C flag- let repo = worktrunk::git::Repository::current();+ let Ok(repo) = worktrunk::git::Repository::current() else {+ return;+ };// Check if we're actually in a git repo- if repo.git_dir().is_err() {+ if repo.current_worktree().git_dir().is_err() {return;}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex f7a7918ab..3d8666f22 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -227,8 +227,11 @@ fn print_switch_message_if_changed(return Ok(());}- let repo = Repository::at(main_path);- let Ok(Some(dest_branch)) = repo.current_branch() else {+ // Use main_path for discovery - the worktree we came from may have been removed+ let Ok(repo) = Repository::at(main_path) else {+ return Ok(());+ };+ let Ok(Some(dest_branch)) = repo.worktree_at(main_path).branch() else {return Ok(());};@@ -386,8 +389,7 @@ pub fn handle_switch_output(// Show worktree-path config hint on first --create in this repo,// unless user already has a custom worktree-path config- if *created_branch {- let repo = worktrunk::git::Repository::current();+ if *created_branch && let Ok(repo) = worktrunk::git::Repository::current() {let has_custom_config = WorktrunkConfig::load().map(|c| c.has_custom_worktree_path()).unwrap_or(false);@@ -500,7 +502,7 @@ fn handle_branch_only_output(return Ok(());}- let repo = worktrunk::git::Repository::current();+ let repo = worktrunk::git::Repository::current()?;// Get default branch for integration check and reason display// Falls back to HEAD if default branch can't be determined@@ -542,11 +544,13 @@ fn spawn_post_switch_after_remove(let Ok(config) = WorktrunkConfig::load() else {return Ok(());};- let dest_repo = Repository::at(main_path);- let dest_branch = dest_repo.current_branch()?;- let repo_root = dest_repo.worktree_base()?;+ // Use main_path for discovery since we're called after the original worktree+ // is removed (cwd may no longer exist).+ let repo = Repository::at(main_path)?;+ let dest_branch = repo.worktree_at(main_path).branch()?;+ let repo_root = repo.worktree_base()?;let ctx = CommandContext::new(- &dest_repo,+ &repo,&config,dest_branch.as_deref(),main_path,@@ -578,15 +582,16 @@ fn handle_removed_worktree_output(super::flush()?; // Force flush to ensure shell processes the cd}- let repo = worktrunk::git::Repository::current();+ // Use main_path for discovery - the worktree being removed might be cwd,+ // and git operations after removal need a valid working directory.+ let repo = worktrunk::git::Repository::at(main_path)?;// Execute pre-remove hooks in the worktree being removed// Non-zero exit aborts removal (FailFast strategy)// For detached HEAD, {{ branch }} expands to "HEAD" in templatesif verify && let Ok(config) = WorktrunkConfig::load() {- let target_repo = Repository::at(worktree_path);let ctx = CommandContext::new(- &target_repo,+ &repo,&config,branch_name,worktree_path,@@ -623,8 +628,9 @@ fn handle_removed_worktree_output(super::print(progress_message("Removing worktree (detached HEAD, no branch to delete)...",))?;- let target_repo = worktrunk::git::Repository::at(worktree_path);- let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);+ let _ = repo+ .worktree_at(worktree_path)+ .run_command(&["fsmonitor--daemon", "stop"]);if let Err(err) = repo.remove_worktree(worktree_path, force_worktree) {return Err(GitError::WorktreeRemovalFailed {branch: path_dir_name(worktree_path).to_string(),@@ -753,8 +759,9 @@ fn handle_removed_worktree_output(// Stop fsmonitor daemon first (best effort - ignore errors)// This prevents zombie daemons from accumulating when using builtin fsmonitor- let target_repo = worktrunk::git::Repository::at(worktree_path);- let _ = target_repo.run_command(&["fsmonitor--daemon", "stop"]);+ let _ = repo+ .worktree_at(worktree_path)+ .run_command(&["fsmonitor--daemon", "stop"]);// Track whether branch was actually deleted (will be computed based on deletion attempt)if let Err(err) = repo.remove_worktree(worktree_path, force_worktree) {@@ -771,14 +778,9 @@ fn handle_removed_worktree_output(let branch_was_integrated = pre_computed_integration.is_some();let (outcome, effective_target, show_unmerged_hint) = if !deletion_mode.should_keep() {- let deletion_repo = worktrunk::git::Repository::at(main_path);let check_target = target_branch.unwrap_or("HEAD");- let result = delete_branch_if_safe(- &deletion_repo,- branch_name,- check_target,- deletion_mode.is_force(),- );+ let result =+ delete_branch_if_safe(&repo, branch_name, check_target, deletion_mode.is_force());let (deletion, needs_hint) = handle_branch_deletion_result(result, branch_name, true)?;// Only use effective_target for display if we had a real target (not "HEAD" fallback)let display_target = target_branch.map(|_| deletion.effective_target);diff --git a/src/pager.rs b/src/pager.rsindex 00555f3b3..add32ff20 100644--- a/src/pager.rs+++ b/src/pager.rs@@ -8,7 +8,7 @@ pub(crate) fn parse_pager_value(value: &str) -> Option<String> {/// Read `core.pager` from git config, returning None if unset or invalid.pub(crate) fn git_config_pager() -> Option<String> {- let repo = Repository::current();+ let repo = Repository::current().ok()?;repo.run_command(&["config", "--get", "core.pager"]).ok().and_then(|output| parse_pager_value(&output))diff --git a/src/verbose_log.rs b/src/verbose_log.rsindex 5b13dea5b..22a5c7817 100644--- a/src/verbose_log.rs+++ b/src/verbose_log.rs@@ -73,11 +73,10 @@ pub fn log_file_path() -> Option<PathBuf> {/// a repository parameter.fn try_create_log_file() -> Option<(PathBuf, File)> {// Find the git repo from current directory- let cwd = std::env::current_dir().ok()?;- let repo = worktrunk::git::Repository::at(cwd);+ let repo = worktrunk::git::Repository::current().ok()?;// Get the wt-logs directory (creates it if needed)- let log_dir = repo.wt_logs_dir().ok()?;+ let log_dir = repo.wt_logs_dir();std::fs::create_dir_all(&log_dir).ok()?;let path = log_dir.join("verbose.log");diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex b8d930f77..059bcba7e 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -2287,8 +2287,8 @@ pub fn make_snapshot_cmd(/// # Returns/// The common git directory pathpub fn resolve_git_common_dir(worktree_path: &Path) -> PathBuf {- let repo = worktrunk::git::Repository::at(worktree_path);- repo.git_common_dir().unwrap().to_path_buf()+ let repo = worktrunk::git::Repository::at(worktree_path).unwrap();+ repo.git_common_dir().to_path_buf()}/// Validates ANSI escape sequences for the specific nested reset pattern that causes color leaksdiff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rsindex 31cc75498..d11a43483 100644--- a/tests/integration_tests/ci_status.rs+++ b/tests/integration_tests/ci_status.rs@@ -250,3 +250,125 @@ fn test_list_full_filters_by_repo_owner(mut repo: TestRepo) {run_ci_status_test(&mut repo, "filters_by_repo_owner", &pr_json, "[]");}++#[rstest]+fn test_list_full_with_platform_override_github(mut repo: TestRepo) {+ // Add a non-GitHub remote (bitbucket) - platform won't be auto-detected+ repo.run_git(&[+ "remote",+ "add",+ "origin",+ "https://bitbucket.org/test-owner/test-repo.git",+ ]);++ // Set platform override in project config+ repo.write_project_config(+ r#"+[ci]+platform = "github"+"#,+ );++ // Create a feature branch+ repo.add_worktree("feature");++ // Get actual commit SHA+ let head_sha = get_branch_sha(&repo, "feature");++ // Setup mock gh with PR data - this should work because platform is overridden to github+ let pr_json = format!(+ r#"[{{+ "headRefOid": "{}",+ "mergeStateStatus": "CLEAN",+ "statusCheckRollup": [+ {{"status": "COMPLETED", "conclusion": "SUCCESS"}}+ ],+ "url": "https://github.com/test-owner/test-repo/pull/1",+ "headRepositoryOwner": {{"login": "test-owner"}}+ }}]"#,+ head_sha+ );+ let run_json = "[]";+ repo.setup_mock_gh_with_ci_data(&pr_json, run_json);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);+ repo.configure_mock_commands(&mut cmd);+ // Platform override should force GitHub detection even with bitbucket remote+ assert_cmd_snapshot!(cmd);+ });+}++#[rstest]+fn test_list_full_with_gitlab_remote(mut repo: TestRepo) {+ // Add GitLab remote - tests get_gitlab_host_for_repo path+ repo.run_git(&[+ "remote",+ "add",+ "origin",+ "https://gitlab.example.com/test-owner/test-repo.git",+ ]);++ // Create a feature branch+ repo.add_worktree("feature");++ // No mock glab setup - this tests the hint path when glab isn't available+ // The get_gitlab_host_for_repo function is called to detect GitLab platform++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);+ // Don't configure mocks - we want to test the "no CI tool" hint path+ // which exercises get_gitlab_host_for_repo+ assert_cmd_snapshot!(cmd);+ });+}++#[rstest]+fn test_list_full_with_invalid_platform_override(mut repo: TestRepo) {+ // Add GitHub remote+ repo.run_git(&[+ "remote",+ "add",+ "origin",+ "https://github.com/test-owner/test-repo.git",+ ]);++ // Set INVALID platform override - should warn and fall back to URL detection+ repo.write_project_config(+ r#"+[ci]+platform = "invalid_platform"+"#,+ );++ // Create a feature branch+ repo.add_worktree("feature");+ let head_sha = get_branch_sha(&repo, "feature");++ // Setup mock gh - platform should fall back to GitHub via URL detection+ let pr_json = format!(+ r#"[{{+ "headRefOid": "{}",+ "mergeStateStatus": "CLEAN",+ "statusCheckRollup": [+ {{"status": "COMPLETED", "conclusion": "SUCCESS"}}+ ],+ "url": "https://github.com/test-owner/test-repo/pull/1",+ "headRepositoryOwner": {{"login": "test-owner"}}+ }}]"#,+ head_sha+ );+ repo.setup_mock_gh_with_ci_data(&pr_json, "[]");++ let mut settings = setup_snapshot_settings(&repo);+ // Normalize worker thread ID prefix in log output (e.g., [n], [z], [A] -> [W])+ settings.add_filter(r"\[[a-zA-Z]\]", "[W]");+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);+ repo.configure_mock_commands(&mut cmd);+ // Invalid platform should fall back to URL detection (GitHub)+ assert_cmd_snapshot!(cmd);+ });+}diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rsindex a89f80cf6..1fcbfe0b4 100644--- a/tests/integration_tests/default_branch.rs+++ b/tests/integration_tests/default_branch.rs@@ -8,7 +8,10 @@ fn test_get_default_branch_with_origin_head(#[from(repo_with_remote)] repo: Testassert!(repo.has_origin_head());// Test that we can get the default branch- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "main");}@@ -19,7 +22,10 @@ fn test_get_default_branch_without_origin_head(#[from(repo_with_remote)] repo: Tassert!(!repo.has_origin_head());// Should still work by querying remote- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "main");// Verify that worktrunk's cache is now set@@ -41,7 +47,10 @@ fn test_get_default_branch_caches_result(#[from(repo_with_remote)] repo: TestRep.output();// First call queries remote and caches to worktrunk config- Repository::at(repo.root_path()).default_branch().unwrap();+ Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();let cached = repo.git_command().args(["config", "--get", "worktrunk.default-branch"])@@ -50,7 +59,10 @@ fn test_get_default_branch_caches_result(#[from(repo_with_remote)] repo: TestRepassert!(cached.status.success());// Second call uses cache (fast path)- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "main");}@@ -58,13 +70,17 @@ fn test_get_default_branch_caches_result(#[from(repo_with_remote)] repo: TestRepfn test_get_default_branch_no_remote(repo: TestRepo) {// No remote configured, should infer from local branches// Since there's only one local branch, it should return that- let result = Repository::at(repo.root_path()).default_branch();+ let result = Repository::at(repo.root_path()).unwrap().default_branch();assert!(result.is_ok());// The inferred branch should match the current branchlet inferred_branch = result.unwrap();- let repo_instance = Repository::at(repo.root_path());- let current_branch = repo_instance.current_branch().unwrap().unwrap();+ let repo_instance = Repository::at(repo.root_path()).unwrap();+ let current_branch = repo_instance+ .worktree_at(repo.root_path())+ .branch()+ .unwrap()+ .unwrap();assert_eq!(inferred_branch, current_branch);}@@ -73,7 +89,10 @@ fn test_get_default_branch_with_custom_remote(mut repo: TestRepo) {repo.setup_custom_remote("upstream", "main");// Test that we can get the default branch from a custom remote- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "main");}@@ -83,7 +102,7 @@ fn test_primary_remote_detects_custom_remote(mut repo: TestRepo) {repo.setup_custom_remote("upstream", "main");// Test that primary_remote detects the custom remote name- let git_repo = Repository::at(repo.root_path());+ let git_repo = Repository::at(repo.root_path()).unwrap();let remote = git_repo.primary_remote().unwrap();assert_eq!(remote, "upstream");}@@ -92,7 +111,7 @@ fn test_primary_remote_detects_custom_remote(mut repo: TestRepo) {fn test_branch_exists_with_custom_remote(mut repo: TestRepo) {repo.setup_custom_remote("upstream", "main");- let git_repo = Repository::at(repo.root_path());+ let git_repo = Repository::at(repo.root_path()).unwrap();// Should find the branch on the custom remoteassert!(git_repo.branch_exists("main").unwrap());@@ -115,7 +134,10 @@ fn test_get_default_branch_no_remote_common_names_fallback(repo: TestRepo) {// Now we have multiple branches: main, feature, bugfix// Should detect "main" from the common names list- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "main");}@@ -137,7 +159,10 @@ fn test_get_default_branch_no_remote_master_fallback(repo: TestRepo) {// Now we have: master, feature, bugfix (no "main")// Should detect "master" from the common names list- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "master");}@@ -161,7 +186,10 @@ fn test_default_branch_no_remote_uses_init_config(repo: TestRepo) {// Now we have: primary, feature (no common names like main/master)// Should detect "primary" via init.defaultBranch config- let branch = Repository::at(repo.root_path()).default_branch().unwrap();+ let branch = Repository::at(repo.root_path())+ .unwrap()+ .default_branch()+ .unwrap();assert_eq!(branch, "primary");}@@ -179,7 +207,7 @@ fn test_get_default_branch_no_remote_fails_when_no_match(repo: TestRepo) {// In normal repos (not bare), symbolic-ref HEAD isn't used because HEAD// points to the current branch, not the default branch.// Should fail with an error- let result = Repository::at(repo.root_path()).default_branch();+ let result = Repository::at(repo.root_path()).unwrap().default_branch();assert!(result.is_err());let err = result.unwrap_err().to_string();assert!(diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex f8b6fed65..773ca35a7 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -13,7 +13,7 @@ use crate::common::TestRepo;#[test]fn test_worktree_state_normal() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Normal state - no special fileslet state = repository.worktree_state().unwrap();@@ -23,7 +23,7 @@ fn test_worktree_state_normal() {#[test]fn test_worktree_state_merging() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate merge state by creating MERGE_HEADlet git_dir = repo.root_path().join(".git");@@ -36,7 +36,7 @@ fn test_worktree_state_merging() {#[test]fn test_worktree_state_rebasing_with_progress() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate rebase state with progresslet git_dir = repo.root_path().join(".git");@@ -52,7 +52,7 @@ fn test_worktree_state_rebasing_with_progress() {#[test]fn test_worktree_state_rebasing_apply() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate rebase-apply state (git am or git rebase without -m)let git_dir = repo.root_path().join(".git");@@ -68,7 +68,7 @@ fn test_worktree_state_rebasing_apply() {#[test]fn test_worktree_state_rebasing_no_progress() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate rebase state without progress fileslet git_dir = repo.root_path().join(".git");@@ -83,7 +83,7 @@ fn test_worktree_state_rebasing_no_progress() {#[test]fn test_worktree_state_cherry_picking() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate cherry-pick statelet git_dir = repo.root_path().join(".git");@@ -96,7 +96,7 @@ fn test_worktree_state_cherry_picking() {#[test]fn test_worktree_state_reverting() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate revert statelet git_dir = repo.root_path().join(".git");@@ -109,7 +109,7 @@ fn test_worktree_state_reverting() {#[test]fn test_worktree_state_bisecting() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Simulate bisect statelet git_dir = repo.root_path().join(".git");@@ -130,7 +130,7 @@ fn test_available_branches_all_have_worktrees() {// Create feature branch with worktreerepo.add_worktree("feature");- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let available = repository.available_branches().unwrap();// Both main and feature have worktrees, so nothing should be available@@ -146,7 +146,7 @@ fn test_available_branches_some_without_worktrees() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let available = repository.available_branches().unwrap();// orphan-branch has no worktree, so it should be available@@ -172,7 +172,7 @@ fn test_all_branches() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let branches = repository.all_branches().unwrap();assert!(branches.contains(&"main".to_string()));@@ -199,7 +199,7 @@ fn test_project_identifier_https() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let id = repository.project_identifier().unwrap();assert_eq!(id, "github.com/user/repo");}@@ -219,7 +219,7 @@ fn test_project_identifier_http() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let id = repository.project_identifier().unwrap();assert_eq!(id, "gitlab.example.com/team/project");}@@ -239,7 +239,7 @@ fn test_project_identifier_ssh_colon() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let id = repository.project_identifier().unwrap();assert_eq!(id, "github.com/user/repo");}@@ -259,7 +259,7 @@ fn test_project_identifier_ssh_protocol() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let id = repository.project_identifier().unwrap();// ssh://[email protected]/user/repo.git -> github.com/user/repoassert_eq!(id, "github.com/user/repo");@@ -280,7 +280,7 @@ fn test_project_identifier_ssh_protocol_with_port() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let id = repository.project_identifier().unwrap();// The port colon gets converted to /assert_eq!(id, "gitlab.example.com/2222/team/project");@@ -291,7 +291,7 @@ fn test_project_identifier_no_remote_fallback() {let repo = TestRepo::new();// Don't create a remote - should fall back to directory name- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let id = repository.project_identifier().unwrap();// Should be the repo directory nameassert_eq!(id, "repo");@@ -309,7 +309,7 @@ fn test_get_config_exists() {.output().unwrap();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let value = repository.get_config("test.key").unwrap();assert_eq!(value, Some("test-value".to_string()));}@@ -318,7 +318,7 @@ fn test_get_config_exists() {fn test_get_config_not_exists() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let value = repository.get_config("nonexistent.key").unwrap();assert!(value.is_none());}@@ -327,7 +327,7 @@ fn test_get_config_not_exists() {fn test_set_config() {let repo = TestRepo::new();- let repository = Repository::at(repo.root_path().to_path_buf());+ let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();repository.set_config("test.setting", "new-value").unwrap();// Verify it was setdiff --git a/tests/snapshots/integration__integration_tests__ci_status__list_full_with_gitlab_remote.snap b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_gitlab_remote.snapnew file mode 100644index 000000000..c29c9af3e--- /dev/null+++ b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_gitlab_remote.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/ci_status.rs+info:+ program: wt+ args:+ - list+ - "--full"+ 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mmain…±[0m [1mPath[0m [1mRemote⇅[0m [1mCI[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [2m^[22m . [2ma1e809f5[0m [2m1d[0m [2mInitial commit++ [2mfeature[0m [2m_[22m [2m../repo.feature[0m [2ma1e809f5[0m [2m1d[0m [2mInitial commit++[2m○[22m [2mShowing 2 worktrees++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_platform_override.snap b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_platform_override.snapnew file mode 100644index 000000000..788691607--- /dev/null+++ b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_invalid_platform_override.snap@@ -0,0 +1,41 @@+---+source: tests/integration_tests/ci_status.rs+info:+ program: wt+ args:+ - list+ - "--full"+ 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mmain…±[0m [1mPath[0m [1mRemote⇅[0m [1mCI[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [36m?[39m [2m^[22m . [32m●[0m [2ma1e809f5[0m [2m1d[0m [2mInitial commit++ [2mfeature[0m [2m_[22m [2m../repo.feature[0m [32m●[0m [2ma1e809f5[0m [2m1d[0m [2mInitial commit++[2m○[22m [2mShowing 2 worktrees, 1 with changes++----- stderr -----+[2m[W][22m Invalid CI platform in config: 'invalid_platform'. Expected 'github' or 'gitlab'.+[2m[W][22m Invalid CI platform in config: 'invalid_platform'. Expected 'github' or 'gitlab'.diff --git a/tests/snapshots/integration__integration_tests__ci_status__list_full_with_platform_override_github.snap b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_platform_override_github.snapnew file mode 100644index 000000000..f4c30bda9--- /dev/null+++ b/tests/snapshots/integration__integration_tests__ci_status__list_full_with_platform_override_github.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/ci_status.rs+info:+ program: wt+ args:+ - list+ - "--full"+ 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_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PATH: "[PATH]"+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mmain…±[0m [1mPath[0m [1mRemote⇅[0m [1mCI[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [36m?[39m [2m^[22m . [32m●[0m [2ma1e809f5[0m [2m1d[0m [2mInitial commit++ [2mfeature[0m [2m_[22m [2m../repo.feature[0m [32m●[0m [2ma1e809f5[0m [2m1d[0m [2mInitial commit++[2m○[22m [2mShowing 2 worktrees, 1 with changes++----- stderr -----