Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Simplify code and improve coverage (#226)
Maximilian Roos0888aee06121
diff --git a/Cargo.lock b/Cargo.lockindex 533e90e3f..8d72a0acc 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2997,7 +2997,6 @@ dependencies = ["serde_json","shell-escape","shellexpand",- "signal-hook","skim","strum","synoptic",diff --git a/Cargo.toml b/Cargo.tomlindex b4c397b89..7584a017f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -104,12 +104,10 @@ dunce = "1.0"[target.'cfg(unix)'.dependencies]skim = "0.20"-nix = { version = "0.30", default-features = false, features = ["process", "signal"] }-signal-hook = { version = "0.3.17", default-features = false, features = ["iterator"] }[target.'cfg(unix)'.dev-dependencies]# Match version used by portable-pty to avoid compiling multiple nix versions-nix = { version = "0.30", default-features = false, features = ["signal"] }+nix = { version = "0.30", default-features = false, features = ["process", "signal"] }[build-dependencies]vergen-gitcl = { version = "1.0.8", features = ["build"] }diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 244adc7c6..fbade769f 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -102,11 +102,6 @@ impl Repository {Self::at(base_path().clone())}- /// Get the path this repository context operates on.- pub fn path(&self) -> &std::path::Path {- &self.path- }-/// Get the repository layout, initializing it if needed.fn layout(&self) -> anyhow::Result<&RepositoryLayout> {if let Some(layout) = self.layout.get() {@@ -659,12 +654,10 @@ impl Repository {let range = format!("{}..{}", base, head);let stdout = self.run_command(&["rev-list", "--count", &range])?;- stdout.trim().parse().map_err(|e| {- GitError::ParseError {- message: format!("Failed to parse commit count: {}", e),- }- .into()- })+ stdout+ .trim()+ .parse()+ .context("Failed to parse commit count")}/// Check if there are merge commits in the range base..head.@@ -708,12 +701,7 @@ impl Repository {/// Get commit timestamp in seconds since epoch.pub fn commit_timestamp(&self, commit: &str) -> anyhow::Result<i64> {let stdout = self.run_command(&["show", "-s", "--format=%ct", commit])?;- stdout.trim().parse().map_err(|e| {- GitError::ParseError {- message: format!("Failed to parse timestamp: {}", e),- }- .into()- })+ stdout.trim().parse().context("Failed to parse timestamp")}/// Get commit message (subject line) for a commit.@@ -833,12 +821,11 @@ impl Repository {// Example: "5\t3" means 5 commits behind, 3 commits ahead// git rev-list --left-right outputs left (base) first, then right (head)let parts: Vec<&str> = output.trim().split('\t').collect();- if parts.len() != 2 {- return Err(crate::git::GitError::ParseError {- message: format!("Unexpected rev-list output format: {}", output),- }- .into());- }+ anyhow::ensure!(+ parts.len() == 2,+ "Unexpected rev-list output format: {}",+ output+ );let behind: usize = parts[0].parse().context("Failed to parse behind count")?;let ahead: usize = parts[1].parse().context("Failed to parse ahead count")?;diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rsindex e22596680..e03f6deb2 100644--- a/tests/integration_tests/mod.rs+++ b/tests/integration_tests/mod.rs@@ -39,6 +39,7 @@ pub mod post_start_commands;pub mod push;pub mod readme_sync;pub mod remove;+pub mod repository;pub mod security;pub mod select;pub mod shell_wrapper;diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsnew file mode 100644index 000000000..063c28f35--- /dev/null+++ b/tests/integration_tests/repository.rs@@ -0,0 +1,323 @@+//! Tests for git repository methods to improve code coverage.++use std::fs;++use worktrunk::git::Repository;++use crate::common::TestRepo;++// =============================================================================+// worktree_state() tests - simulate various git operation states+// =============================================================================++#[test]+fn test_worktree_state_normal() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Normal state - no special files+ let state = repository.worktree_state().unwrap();+ assert!(state.is_none());+}++#[test]+fn test_worktree_state_merging() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate merge state by creating MERGE_HEAD+ let git_dir = repo.root_path().join(".git");+ fs::write(git_dir.join("MERGE_HEAD"), "abc123\n").unwrap();++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("MERGING".to_string()));+}++#[test]+fn test_worktree_state_rebasing_with_progress() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate rebase state with progress+ let git_dir = repo.root_path().join(".git");+ let rebase_dir = git_dir.join("rebase-merge");+ fs::create_dir_all(&rebase_dir).unwrap();+ fs::write(rebase_dir.join("msgnum"), "2\n").unwrap();+ fs::write(rebase_dir.join("end"), "5\n").unwrap();++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("REBASING 2/5".to_string()));+}++#[test]+fn test_worktree_state_rebasing_apply() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate rebase-apply state (git am or git rebase without -m)+ let git_dir = repo.root_path().join(".git");+ let rebase_dir = git_dir.join("rebase-apply");+ fs::create_dir_all(&rebase_dir).unwrap();+ fs::write(rebase_dir.join("msgnum"), "3\n").unwrap();+ fs::write(rebase_dir.join("end"), "7\n").unwrap();++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("REBASING 3/7".to_string()));+}++#[test]+fn test_worktree_state_rebasing_no_progress() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate rebase state without progress files+ let git_dir = repo.root_path().join(".git");+ let rebase_dir = git_dir.join("rebase-merge");+ fs::create_dir_all(&rebase_dir).unwrap();+ // No msgnum/end files - just the directory++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("REBASING".to_string()));+}++#[test]+fn test_worktree_state_cherry_picking() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate cherry-pick state+ let git_dir = repo.root_path().join(".git");+ fs::write(git_dir.join("CHERRY_PICK_HEAD"), "def456\n").unwrap();++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("CHERRY-PICKING".to_string()));+}++#[test]+fn test_worktree_state_reverting() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate revert state+ let git_dir = repo.root_path().join(".git");+ fs::write(git_dir.join("REVERT_HEAD"), "789abc\n").unwrap();++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("REVERTING".to_string()));+}++#[test]+fn test_worktree_state_bisecting() {+ let repo = TestRepo::new();+ let repository = Repository::at(repo.root_path().to_path_buf());++ // Simulate bisect state+ let git_dir = repo.root_path().join(".git");+ fs::write(git_dir.join("BISECT_LOG"), "# bisect log\n").unwrap();++ let state = repository.worktree_state().unwrap();+ assert_eq!(state, Some("BISECTING".to_string()));+}++// =============================================================================+// available_branches() tests+// =============================================================================++#[test]+fn test_available_branches_all_have_worktrees() {+ let mut repo = TestRepo::new();+ // main branch already has a worktree (the main repo)+ // Create feature branch with worktree+ repo.add_worktree("feature");++ let repository = Repository::at(repo.root_path().to_path_buf());+ let available = repository.available_branches().unwrap();++ // Both main and feature have worktrees, so nothing should be available+ assert!(available.is_empty());+}++#[test]+fn test_available_branches_some_without_worktrees() {+ let repo = TestRepo::new();+ // Create a branch without a worktree+ repo.git_command(&["branch", "orphan-branch"])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let available = repository.available_branches().unwrap();++ // orphan-branch has no worktree, so it should be available+ assert!(available.contains(&"orphan-branch".to_string()));+ // main has a worktree, so it should not be available+ assert!(!available.contains(&"main".to_string()));+}++// =============================================================================+// all_branches() tests+// =============================================================================++#[test]+fn test_all_branches() {+ let repo = TestRepo::new();+ // Create some branches+ repo.git_command(&["branch", "alpha"]).output().unwrap();+ repo.git_command(&["branch", "beta"]).output().unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let branches = repository.all_branches().unwrap();++ assert!(branches.contains(&"main".to_string()));+ assert!(branches.contains(&"alpha".to_string()));+ assert!(branches.contains(&"beta".to_string()));+}++// =============================================================================+// project_identifier() URL parsing tests+// =============================================================================++#[test]+fn test_project_identifier_https() {+ let mut repo = TestRepo::new();+ repo.setup_remote("main");+ // Override the remote URL to https format+ repo.git_command(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/user/repo.git",+ ])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let id = repository.project_identifier().unwrap();+ assert_eq!(id, "github.com/user/repo");+}++#[test]+fn test_project_identifier_http() {+ let mut repo = TestRepo::new();+ repo.setup_remote("main");+ // Override the remote URL to http format (no SSL)+ repo.git_command(&[+ "remote",+ "set-url",+ "origin",+ "http://gitlab.example.com/team/project.git",+ ])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let id = repository.project_identifier().unwrap();+ assert_eq!(id, "gitlab.example.com/team/project");+}++#[test]+fn test_project_identifier_ssh_colon() {+ let mut repo = TestRepo::new();+ repo.setup_remote("main");+ // Override the remote URL to SSH format with colon+ repo.git_command(&[+ "remote",+ "set-url",+ "origin",+ "[email protected]:user/repo.git",+ ])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let id = repository.project_identifier().unwrap();+ assert_eq!(id, "github.com/user/repo");+}++#[test]+fn test_project_identifier_ssh_protocol() {+ let mut repo = TestRepo::new();+ repo.setup_remote("main");+ // Override the remote URL to ssh:// format+ repo.git_command(&[+ "remote",+ "set-url",+ "origin",+ "ssh://[email protected]/user/repo.git",+ ])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let id = repository.project_identifier().unwrap();+ // ssh://[email protected]/user/repo.git -> github.com/user/repo+ assert_eq!(id, "github.com/user/repo");+}++#[test]+fn test_project_identifier_ssh_protocol_with_port() {+ let mut repo = TestRepo::new();+ repo.setup_remote("main");+ // Override the remote URL to ssh:// format with port+ repo.git_command(&[+ "remote",+ "set-url",+ "origin",+ "ssh://[email protected]:2222/team/project.git",+ ])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let id = repository.project_identifier().unwrap();+ // The port colon gets converted to /+ assert_eq!(id, "gitlab.example.com/2222/team/project");+}++#[test]+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 id = repository.project_identifier().unwrap();+ // Should be the repo directory name+ assert_eq!(id, "repo");+}++// =============================================================================+// get_config/set_config tests+// =============================================================================++#[test]+fn test_get_config_exists() {+ let repo = TestRepo::new();+ repo.git_command(&["config", "test.key", "test-value"])+ .output()+ .unwrap();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let value = repository.get_config("test.key").unwrap();+ assert_eq!(value, Some("test-value".to_string()));+}++#[test]+fn test_get_config_not_exists() {+ let repo = TestRepo::new();++ let repository = Repository::at(repo.root_path().to_path_buf());+ let value = repository.get_config("nonexistent.key").unwrap();+ assert!(value.is_none());+}++#[test]+fn test_set_config() {+ let repo = TestRepo::new();++ let repository = Repository::at(repo.root_path().to_path_buf());+ repository.set_config("test.setting", "new-value").unwrap();++ // Verify it was set+ let value = repository.get_config("test.setting").unwrap();+ assert_eq!(value, Some("new-value".to_string()));+}