Skip to content

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

Refactor CI status and config saving logic

Maximilian Roos11dd4c1948c2
diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rs
index b48a84e7f..76fe40a38 100644
--- a/src/commands/list/ci_status.rs
+++ b/src/commands/list/ci_status.rs
@@ -1,6 +1,30 @@
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Serialize, de::DeserializeOwned};
use std::process::Command;
+/// Configure command to disable color output
+fn disable_color_output(cmd: &mut Command) {
+ cmd.env_remove("CLICOLOR_FORCE");
+ cmd.env_remove("GH_FORCE_TTY");
+ cmd.env("NO_COLOR", "1");
+ cmd.env("CLICOLOR", "0");
+}
+
+/// Check if a CLI tool is available
+fn tool_available(tool: &str, args: &[&str]) -> bool {
+ Command::new(tool)
+ .args(args)
+ .output()
+ .map(|o| o.status.success())
+ .unwrap_or(false)
+}
+
+/// Parse JSON output from CLI tools
+fn parse_json<T: DeserializeOwned>(stdout: &[u8], command: &str, branch: &str) -> Option<T> {
+ serde_json::from_slice(stdout)
+ .map_err(|e| log::warn!("Failed to parse {} JSON for {}: {}", command, branch, e))
+ .ok()
+}
+
/// CI status from GitHub/GitLab checks
/// Matches the statusline.sh color scheme:
/// - Passed: Green (all checks passed)
@@ -115,14 +139,7 @@ impl PrStatus {
"state,headRefOid,mergeStateStatus,statusCheckRollup,url",
]);
- // Remove environment variables that force color output
- cmd.env_remove("CLICOLOR_FORCE");
- cmd.env_remove("GH_FORCE_TTY");
- cmd.env("NO_COLOR", "1");
- cmd.env("CLICOLOR", "0");
-
- // Always set working directory and let gh auto-detect the repo
- // This handles forks correctly (gh will detect upstream repo from git context)
+ disable_color_output(&mut cmd);
cmd.current_dir(repo_root);
let output = match cmd.output() {
@@ -140,17 +157,7 @@ impl PrStatus {
}
// gh pr list returns an array, take the first (and only) item
- let pr_list: Vec<GitHubPrInfo> = match serde_json::from_slice(&output.stdout) {
- Ok(list) => list,
- Err(e) => {
- log::warn!(
- "Failed to parse gh pr list JSON for branch {}: {}",
- branch,
- e
- );
- return None;
- }
- };
+ let pr_list: Vec<GitHubPrInfo> = parse_json(&output.stdout, "gh pr list", branch)?;
let pr_info = pr_list.first()?;
// Only process open PRs
@@ -180,13 +187,7 @@ impl PrStatus {
}
fn detect_gitlab(branch: &str, local_head: &str) -> Option<Self> {
- // Check if glab is available
- if !Command::new("glab")
- .arg("--version")
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
- {
+ if !tool_available("glab", &["--version"]) {
return None;
}
@@ -212,17 +213,7 @@ impl PrStatus {
return None;
}
- let mr_info: GitLabMrInfo = match serde_json::from_slice(&output.stdout) {
- Ok(info) => info,
- Err(e) => {
- log::warn!(
- "Failed to parse glab mr view JSON for branch {}: {}",
- branch,
- e
- );
- return None;
- }
- };
+ let mr_info: GitLabMrInfo = parse_json(&output.stdout, "glab mr view", branch)?;
// Only process open MRs
if mr_info.state != "opened" {
@@ -255,14 +246,8 @@ impl PrStatus {
}
fn detect_github_workflow(branch: &str, local_head: &str, repo_root: &str) -> Option<Self> {
- // Check if gh is available and authenticated
// Note: We don't log auth failures here since detect_github already logged them
- if !Command::new("gh")
- .args(["auth", "status"])
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
- {
+ if !tool_available("gh", &["auth", "status"]) {
return None;
}
@@ -279,16 +264,7 @@ impl PrStatus {
"status,conclusion,headSha",
]);
- // Remove environment variables that force color output even when piped
- // CLICOLOR_FORCE and GH_FORCE_TTY override NO_COLOR and TTY detection
- cmd.env_remove("CLICOLOR_FORCE");
- cmd.env_remove("GH_FORCE_TTY");
- // Request no color output
- cmd.env("NO_COLOR", "1");
- cmd.env("CLICOLOR", "0");
-
- // Always set working directory and let gh auto-detect the repo
- // This handles forks correctly (gh will detect upstream repo from git context)
+ disable_color_output(&mut cmd);
cmd.current_dir(repo_root);
let output = match cmd.output() {
@@ -305,17 +281,7 @@ impl PrStatus {
return None;
}
- let runs: Vec<GitHubWorkflowRun> = match serde_json::from_slice(&output.stdout) {
- Ok(runs) => runs,
- Err(e) => {
- log::warn!(
- "Failed to parse gh run list JSON for branch {}: {}",
- branch,
- e
- );
- return None;
- }
- };
+ let runs: Vec<GitHubWorkflowRun> = parse_json(&output.stdout, "gh run list", branch)?;
let run = runs.first()?;
// Check if the workflow run matches our local HEAD commit
@@ -337,13 +303,7 @@ impl PrStatus {
}
fn detect_gitlab_pipeline(branch: &str, local_head: &str) -> Option<Self> {
- // Check if glab is available
- if !Command::new("glab")
- .arg("--version")
- .output()
- .map(|o| o.status.success())
- .unwrap_or(false)
- {
+ if !tool_available("glab", &["--version"]) {
return None;
}
@@ -370,18 +330,7 @@ impl PrStatus {
return None;
}
- // Parse JSON output
- let pipelines: Vec<GitLabPipeline> = match serde_json::from_slice(&output.stdout) {
- Ok(pipelines) => pipelines,
- Err(e) => {
- log::warn!(
- "Failed to parse glab ci list JSON for branch {}: {}",
- branch,
- e
- );
- return None;
- }
- };
+ let pipelines: Vec<GitLabPipeline> = parse_json(&output.stdout, "glab ci list", branch)?;
let pipeline = pipelines.first()?;
// Check if the pipeline matches our local HEAD commit
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 4c34a0bfc..a2e7de58e 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -466,7 +466,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
.approve_command_to(
"github.com/user/repo".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
assert!(config.is_command_approved("github.com/user/repo", "npm install"));
@@ -482,7 +482,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
.approve_command_to(
"github.com/user/repo".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
assert_eq!(
@@ -510,14 +510,14 @@ task2 = "echo 'Task 2 running' > task2.txt"
.approve_command_to(
"github.com/user/repo".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
config
.approve_command_to(
"github.com/user/repo".to_string(),
"npm test".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
@@ -526,7 +526,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
// Revoke one command
config
- .revoke_command_to("github.com/user/repo", "npm install", &config_path)
+ .revoke_command_to("github.com/user/repo", "npm install", Some(&config_path))
.unwrap();
assert!(!config.is_command_approved("github.com/user/repo", "npm install"));
assert!(config.is_command_approved("github.com/user/repo", "npm test"));
@@ -536,7 +536,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
// Revoke the last command - should remove the project entry
config
- .revoke_command_to("github.com/user/repo", "npm test", &config_path)
+ .revoke_command_to("github.com/user/repo", "npm test", Some(&config_path))
.unwrap();
assert!(!config.is_command_approved("github.com/user/repo", "npm test"));
assert!(!config.projects.contains_key("github.com/user/repo"));
@@ -553,7 +553,7 @@ task2 = "echo 'Task 2 running' > task2.txt"
// Revoking from non-existent project is a no-op
config
- .revoke_command_to("github.com/user/repo", "npm install", &config_path)
+ .revoke_command_to("github.com/user/repo", "npm install", Some(&config_path))
.unwrap();
// Set up one command
@@ -561,13 +561,13 @@ task2 = "echo 'Task 2 running' > task2.txt"
.approve_command_to(
"github.com/user/repo".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
// Revoking non-existent command is a no-op
config
- .revoke_command_to("github.com/user/repo", "npm test", &config_path)
+ .revoke_command_to("github.com/user/repo", "npm test", Some(&config_path))
.unwrap();
assert!(config.is_command_approved("github.com/user/repo", "npm install"));
}
@@ -586,21 +586,21 @@ task2 = "echo 'Task 2 running' > task2.txt"
.approve_command_to(
"github.com/user/repo1".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
config
.approve_command_to(
"github.com/user/repo1".to_string(),
"npm test".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
config
.approve_command_to(
"github.com/user/repo2".to_string(),
"cargo build".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
@@ -609,17 +609,17 @@ task2 = "echo 'Task 2 running' > task2.txt"
// Revoke entire project
config
- .revoke_project_to("github.com/user/repo1", &config_path)
+ .revoke_project_to("github.com/user/repo1", Some(&config_path))
.unwrap();
assert!(!config.projects.contains_key("github.com/user/repo1"));
assert!(config.projects.contains_key("github.com/user/repo2"));
// Revoking non-existent project is a no-op
config
- .revoke_project_to("github.com/user/repo1", &config_path)
+ .revoke_project_to("github.com/user/repo1", Some(&config_path))
.unwrap();
config
- .revoke_project_to("github.com/nonexistent/repo", &config_path)
+ .revoke_project_to("github.com/nonexistent/repo", Some(&config_path))
.unwrap();
}
diff --git a/src/config/user.rs b/src/config/user.rs
index 66d18e4c0..a2d1caf0a 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -334,31 +334,16 @@ impl WorktrunkConfig {
/// Add an approved command and save to config file
pub fn approve_command(&mut self, project: String, command: String) -> Result<(), ConfigError> {
- // Don't add duplicates
- if self.is_command_approved(&project, &command) {
- return Ok(());
- }
-
- self.projects
- .entry(project)
- .or_default()
- .approved_commands
- .push(command);
- self.save()
+ self.approve_command_to(project, command, None)
}
/// Add an approved command and save to a specific config file (for testing)
- ///
- /// This is the same as `approve_command()` but saves to an explicit path
- /// instead of the default user config location. Use this in tests to avoid
- /// polluting the user's actual config.
pub fn approve_command_to(
&mut self,
project: String,
command: String,
- config_path: &std::path::Path,
+ config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
- // Don't add duplicates
if self.is_command_approved(&project, &command) {
return Ok(());
}
@@ -368,92 +353,72 @@ impl WorktrunkConfig {
.or_default()
.approved_commands
.push(command);
- self.save_to(config_path)
+ self.save_impl(config_path)
}
/// Revoke an approved command and save to config file
- ///
- /// Removes the specified command from the project's approved commands list.
- /// If this results in an empty project entry, the project is removed entirely.
pub fn revoke_command(&mut self, project: &str, command: &str) -> Result<(), ConfigError> {
- if let Some(project_config) = self.projects.get_mut(project) {
- let len_before = project_config.approved_commands.len();
- project_config.approved_commands.retain(|c| c != command);
- let changed = len_before != project_config.approved_commands.len();
-
- // Clean up empty project entries
- if project_config.approved_commands.is_empty() {
- self.projects.remove(project);
- }
-
- if changed {
- self.save()?;
- }
- }
- Ok(())
- }
-
- /// Remove all approvals for a project and save to config file
- ///
- /// Removes the entire project entry from the configuration.
- pub fn revoke_project(&mut self, project: &str) -> Result<(), ConfigError> {
- if self.projects.remove(project).is_some() {
- self.save()?;
- }
- Ok(())
+ self.revoke_command_to(project, command, None)
}
/// Revoke an approved command and save to a specific config file (for testing)
- ///
- /// This is the same as `revoke_command()` but saves to an explicit path
- /// instead of the default user config location. Use this in tests to avoid
- /// polluting the user's actual config.
#[doc(hidden)]
pub fn revoke_command_to(
&mut self,
project: &str,
command: &str,
- config_path: &std::path::Path,
+ config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
if let Some(project_config) = self.projects.get_mut(project) {
let len_before = project_config.approved_commands.len();
project_config.approved_commands.retain(|c| c != command);
let changed = len_before != project_config.approved_commands.len();
- // Clean up empty project entries
if project_config.approved_commands.is_empty() {
self.projects.remove(project);
}
if changed {
- self.save_to(config_path)?;
+ self.save_impl(config_path)?;
}
}
Ok(())
}
+ /// Remove all approvals for a project and save to config file
+ pub fn revoke_project(&mut self, project: &str) -> Result<(), ConfigError> {
+ self.revoke_project_to(project, None)
+ }
+
/// Remove all approvals for a project and save to a specific config file (for testing)
- ///
- /// This is the same as `revoke_project()` but saves to an explicit path
- /// instead of the default user config location. Use this in tests to avoid
- /// polluting the user's actual config.
#[doc(hidden)]
pub fn revoke_project_to(
&mut self,
project: &str,
- config_path: &std::path::Path,
+ config_path: Option<&std::path::Path>,
) -> Result<(), ConfigError> {
if self.projects.remove(project).is_some() {
- self.save_to(config_path)?;
+ self.save_impl(config_path)?;
}
Ok(())
}
/// Save the current configuration to the default config file location
pub fn save(&self) -> Result<(), ConfigError> {
- let config_path = get_config_path()
- .ok_or_else(|| ConfigError::Message("Could not determine config path".to_string()))?;
- self.save_to(&config_path)
+ self.save_impl(None)
+ }
+
+ /// Internal save implementation that handles both default and custom paths
+ fn save_impl(&self, config_path: Option<&std::path::Path>) -> Result<(), ConfigError> {
+ match config_path {
+ Some(path) => self.save_to(path),
+ None => {
+ let path = get_config_path().ok_or_else(|| {
+ ConfigError::Message("Could not determine config path".to_string())
+ })?;
+ self.save_to(&path)
+ }
+ }
}
/// Save the current configuration to a specific file path
diff --git a/tests/integration_tests/approval_save.rs b/tests/integration_tests/approval_save.rs
index f32567bfc..f28c89f96 100644
--- a/tests/integration_tests/approval_save.rs
+++ b/tests/integration_tests/approval_save.rs
@@ -19,7 +19,7 @@ fn test_approval_saves_to_disk() {
.approve_command_to(
"github.com/test/repo".to_string(),
"test command".to_string(),
- &config_path,
+ Some(&config_path),
)
.expect("Failed to save approval");
@@ -59,14 +59,14 @@ fn test_duplicate_approvals_not_saved_twice() {
.approve_command_to(
"github.com/test/repo".to_string(),
"test".to_string(),
- &config_path,
+ Some(&config_path),
)
.ok();
config
.approve_command_to(
"github.com/test/repo".to_string(),
"test".to_string(),
- &config_path,
+ Some(&config_path),
)
.ok();
@@ -110,21 +110,21 @@ fn test_multiple_project_approvals() {
.approve_command_to(
"github.com/user1/repo1".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
config
.approve_command_to(
"github.com/user2/repo2".to_string(),
"cargo build".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
config
.approve_command_to(
"github.com/user1/repo1".to_string(),
"npm test".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
@@ -179,7 +179,7 @@ fn test_isolated_config_safety() {
.approve_command_to(
"github.com/safety-test/repo".to_string(),
"THIS SHOULD NOT APPEAR IN USER CONFIG".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
@@ -246,7 +246,7 @@ fn test_force_flag_saves_to_new_config_file() {
.approve_command_to(
"github.com/test/nested".to_string(),
"test command".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
@@ -301,7 +301,7 @@ args = ["-s"]
.approve_command_to(
"github.com/test/repo".to_string(),
"npm install".to_string(),
- &config_path,
+ Some(&config_path),
)
.unwrap();
@@ -381,7 +381,7 @@ fn test_permission_error_prevents_save() {
let result = config.approve_command_to(
"github.com/test/readonly".to_string(),
"test command".to_string(),
- &config_path,
+ Some(&config_path),
);
// Restore write permissions so temp_dir can be cleaned up
diff --git a/tests/integration_tests/approvals.rs b/tests/integration_tests/approvals.rs
index 809833505..13670a583 100644
--- a/tests/integration_tests/approvals.rs
+++ b/tests/integration_tests/approvals.rs
@@ -92,7 +92,7 @@ fn test_clear_approvals_with_approvals() {
.approve_command_to(
project_id,
"echo 'test'".to_string(),
- repo.test_config_path(),
+ Some(repo.test_config_path()),
)
.expect("Failed to save approval");
@@ -122,7 +122,7 @@ fn test_clear_approvals_global_with_approvals() {
.approve_command_to(
project_id,
"echo 'test'".to_string(),
- repo.test_config_path(),
+ Some(repo.test_config_path()),
)
.expect("Failed to save approval");
@@ -148,7 +148,7 @@ fn test_clear_approvals_after_clear() {
.approve_command_to(
project_id.clone(),
"echo 'test'".to_string(),
- repo.test_config_path(),
+ Some(repo.test_config_path()),
)
.expect("Failed to save approval");
@@ -182,21 +182,21 @@ lint = "echo 'third'"
.approve_command_to(
project_id.clone(),
"echo 'first'".to_string(),
- repo.test_config_path(),
+ Some(repo.test_config_path()),
)
.expect("Failed to save approval");
config
.approve_command_to(
project_id.clone(),
"echo 'second'".to_string(),
- repo.test_config_path(),
+ Some(repo.test_config_path()),
)
.expect("Failed to save approval");
config
.approve_command_to(
project_id,
"echo 'third'".to_string(),
- repo.test_config_path(),
+ Some(repo.test_config_path()),
)
.expect("Failed to save approval");