Skip to content

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

test: fill codecov/patch coverage gaps from recent PRs (#865)

Maximilian Roosd358f2ffeb01
diff --git a/src/config/user.rs b/src/config/user.rs
index 7c29cc27f..95a3ef1d5 100644
--- a/src/config/user.rs
+++ b/src/config/user.rs
@@ -3000,4 +3000,97 @@ test = "npm test"
assert_eq!(commands[0].template, "cargo test");
assert_eq!(commands[1].template, "npm test");
}
+
+ // =========================================================================
+ // reload_projects_from error path tests
+ // =========================================================================
+
+ /// Test that reload_projects_from returns a parse error with formatted path
+ /// when the config file contains invalid TOML.
+ #[test]
+ fn test_reload_projects_from_invalid_toml() {
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+
+ // Create initial valid config so file exists
+ std::fs::write(&config_path, "# Valid config\n").unwrap();
+
+ // Now corrupt it with invalid TOML
+ std::fs::write(&config_path, "this is not valid toml [[[").unwrap();
+
+ // Try to reload - should fail with parse error
+ let mut config = UserConfig::default();
+ let result = config.approve_command(
+ "github.com/test/repo".to_string(),
+ "echo test".to_string(),
+ Some(&config_path),
+ );
+
+ assert!(result.is_err());
+ let err = result.unwrap_err().to_string();
+ assert!(
+ err.contains("Failed to parse config file"),
+ "Expected parse error, got: {err}"
+ );
+ // Verify path is included in error (format_path_for_display would format it)
+ assert!(
+ err.contains("config.toml"),
+ "Expected path in error, got: {err}"
+ );
+ }
+
+ /// Test that reload_projects_from handles permission errors
+ /// when the config file exists but cannot be read.
+ #[cfg(unix)]
+ #[test]
+ fn test_reload_projects_from_permission_error() {
+ use std::os::unix::fs::PermissionsExt;
+
+ let dir = tempfile::tempdir().unwrap();
+ let config_path = dir.path().join("config.toml");
+
+ // Create a valid config file
+ std::fs::write(&config_path, "[projects]\n").unwrap();
+
+ // Remove read permissions
+ let mut perms = std::fs::metadata(&config_path).unwrap().permissions();
+ perms.set_mode(0o000); // No permissions
+ std::fs::set_permissions(&config_path, perms).unwrap();
+
+ // Restore permissions on drop to allow cleanup
+ struct RestorePerms<'a>(&'a std::path::Path);
+ impl Drop for RestorePerms<'_> {
+ fn drop(&mut self) {
+ let mut perms = std::fs::metadata(self.0).unwrap().permissions();
+ perms.set_mode(0o644);
+ let _ = std::fs::set_permissions(self.0, perms);
+ }
+ }
+ let _guard = RestorePerms(&config_path);
+
+ // Skip this test when running as root (common in CI containers)
+ if std::env::var("USER").as_deref() == Ok("root") {
+ return;
+ }
+
+ // Try to reload - should fail with read error
+ let mut config = UserConfig::default();
+ let result = config.approve_command(
+ "github.com/test/repo".to_string(),
+ "echo test".to_string(),
+ Some(&config_path),
+ );
+
+ assert!(result.is_err());
+ let err = result.unwrap_err().to_string();
+ assert!(
+ err.contains("Failed to read config file"),
+ "Expected read error, got: {err}"
+ );
+ // Verify path is included in error
+ assert!(
+ err.contains("config.toml"),
+ "Expected path in error, got: {err}"
+ );
+ }
}
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index 31510efab..6900c48a3 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -35,12 +35,20 @@ fn trace_epoch() -> &'static Instant {
/// (file descriptors, process limits) while maintaining good parallelism.
const DEFAULT_CONCURRENT_COMMANDS: usize = 32;
+/// Parse the concurrency limit from a string value.
+/// Returns None if invalid (not a number), otherwise applies the 0 = unlimited rule.
+fn parse_concurrent_limit(value: &str) -> Option<usize> {
+ value
+ .parse::<usize>()
+ .ok()
+ // 0 = no limit (use usize::MAX as effectively unlimited)
+ .map(|n| if n == 0 { usize::MAX } else { n })
+}
+
fn max_concurrent_commands() -> usize {
std::env::var("WORKTRUNK_MAX_CONCURRENT_COMMANDS")
.ok()
- .and_then(|s| s.parse().ok())
- // 0 = no limit (use usize::MAX as effectively unlimited)
- .map(|n: usize| if n == 0 { usize::MAX } else { n })
+ .and_then(|s| parse_concurrent_limit(&s))
.unwrap_or(DEFAULT_CONCURRENT_COMMANDS)
}
@@ -903,6 +911,23 @@ mod tests {
);
}
+ #[test]
+ fn test_parse_concurrent_limit() {
+ // Normal values pass through unchanged
+ assert_eq!(parse_concurrent_limit("1"), Some(1));
+ assert_eq!(parse_concurrent_limit("32"), Some(32));
+ assert_eq!(parse_concurrent_limit("100"), Some(100));
+
+ // 0 means unlimited (maps to usize::MAX)
+ assert_eq!(parse_concurrent_limit("0"), Some(usize::MAX));
+
+ // Invalid values return None
+ assert_eq!(parse_concurrent_limit(""), None);
+ assert_eq!(parse_concurrent_limit("abc"), None);
+ assert_eq!(parse_concurrent_limit("-1"), None);
+ assert_eq!(parse_concurrent_limit("1.5"), None);
+ }
+
#[test]
fn test_shell_config_is_available() {
let config = ShellConfig::get();
diff --git a/src/styling/constants.rs b/src/styling/constants.rs
index a6513ee40..c8ccf1b2e 100644
--- a/src/styling/constants.rs
+++ b/src/styling/constants.rs
@@ -370,4 +370,16 @@ mod tests {
// Empty string, still formatted
assert!(heading.is_empty() || heading.contains('\u{1b}'));
}
+
+ // ============================================================================
+ // FormattedMessage Tests
+ // ============================================================================
+
+ #[test]
+ fn test_formatted_message_into_inner() {
+ let msg = success_message("Done");
+ let inner: String = msg.into_inner();
+ assert!(inner.contains(SUCCESS_SYMBOL));
+ assert!(inner.contains("Done"));
+ }
}
diff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rs
index 379c29a16..236b748cb 100644
--- a/tests/integration_tests/ci_status.rs
+++ b/tests/integration_tests/ci_status.rs
@@ -565,6 +565,98 @@ fn test_list_full_with_gitlab_filters_by_project_id(mut repo: TestRepo) {
);
}
+// =============================================================================
+// GitLab project ID edge cases (PR #846 panic prevention)
+// =============================================================================
+
+/// Test that single MR without project ID works (unambiguous case).
+///
+/// When `glab repo view` fails to return a project ID but there's only one MR,
+/// we can safely use it since there's no ambiguity.
+#[rstest]
+fn test_list_full_with_gitlab_single_mr_no_project_id(mut repo: TestRepo) {
+ let head_sha = setup_gitlab_repo_with_feature(&mut repo);
+
+ // Single MR - should work even without project ID to filter by
+ let mr_json = format!(
+ r#"[{{
+ "iid": 1,
+ "sha": "{}",
+ "has_conflicts": false,
+ "detailed_merge_status": null,
+ "head_pipeline": {{"status": "success"}},
+ "source_project_id": 12345,
+ "web_url": "https://gitlab.com/test-group/test-project/-/merge_requests/1"
+ }}]"#,
+ head_sha
+ );
+
+ // Pass None for project_id to trigger "no project ID" path
+ run_gitlab_ci_status_test(&mut repo, "gitlab_single_mr_no_project_id", &mr_json, None);
+}
+
+/// Test that empty MR list without project ID returns None gracefully.
+///
+/// When no MRs are found and we don't have a project ID, the code should
+/// return None without panicking. This falls through to pipeline detection.
+#[rstest]
+fn test_list_full_with_gitlab_empty_mr_list_no_project_id(mut repo: TestRepo) {
+ setup_gitlab_repo_with_feature(&mut repo);
+
+ // Empty MR list + no project ID -> falls through to pipeline check
+ run_gitlab_ci_status_test(
+ &mut repo,
+ "gitlab_empty_mr_list_no_project_id",
+ "[]", // Empty MR list
+ None, // No project ID
+ );
+}
+
+/// Test that multiple MRs without project ID are skipped (ambiguous case).
+///
+/// When there are multiple MRs with the same branch name and we can't determine
+/// which project we're in, we skip CI detection rather than showing the wrong one.
+/// This falls through to pipeline detection via `glab ci list`.
+#[rstest]
+fn test_list_full_with_gitlab_multiple_mrs_no_project_id(mut repo: TestRepo) {
+ let head_sha = setup_gitlab_repo_with_feature(&mut repo);
+
+ // Multiple MRs from different projects - ambiguous without project ID
+ let mr_json = format!(
+ r#"[
+ {{
+ "iid": 1,
+ "sha": "{}",
+ "has_conflicts": false,
+ "detailed_merge_status": null,
+ "head_pipeline": {{"status": "failed"}},
+ "source_project_id": 11111,
+ "web_url": "https://gitlab.com/org-a/project/-/merge_requests/1"
+ }},
+ {{
+ "iid": 2,
+ "sha": "{}",
+ "has_conflicts": false,
+ "detailed_merge_status": null,
+ "head_pipeline": {{"status": "success"}},
+ "source_project_id": 22222,
+ "web_url": "https://gitlab.com/org-b/project/-/merge_requests/2"
+ }}
+ ]"#,
+ head_sha, head_sha
+ );
+
+ // Pass None for project_id - should skip MR detection due to ambiguity
+ // and fall through to pipeline detection (which will show NoCI since
+ // our mock returns empty pipeline list)
+ run_gitlab_ci_status_test(
+ &mut repo,
+ "gitlab_multiple_mrs_no_project_id",
+ &mr_json,
+ None,
+ );
+}
+
// =============================================================================
// URL-based pushremote tests (gh pr checkout scenario)
// =============================================================================
diff --git a/tests/snapshots/integration__integration_tests__ci_status__gitlab_empty_mr_list_no_project_id.snap b/tests/snapshots/integration__integration_tests__ci_status__gitlab_empty_mr_list_no_project_id.snap
new file mode 100644
index 000000000..00bd76c0e
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__ci_status__gitlab_empty_mr_list_no_project_id.snap
@@ -0,0 +1,45 @@
+---
+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
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+@ main ^| . | 05a4a45d 16h Initial commit
++ feature _| ../repo.feature | 05a4a45d 16h Initial commit
++ feature-a ↑| ↑1 +1 ../repo.feature-a | 1b87d473 16h Add feature-a file
++ feature-b ↑| ↑1 +1 ../repo.feature-b | f62940fc 16h Add feature-b file
++ feature-c ↑| ↑1 +1 ../repo.feature-c | 345c7c93 16h Add feature-c file
+
+○ Showing 5 worktrees, 3 ahead
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__ci_status__gitlab_multiple_mrs_no_project_id.snap b/tests/snapshots/integration__integration_tests__ci_status__gitlab_multiple_mrs_no_project_id.snap
new file mode 100644
index 000000000..00bd76c0e
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__ci_status__gitlab_multiple_mrs_no_project_id.snap
@@ -0,0 +1,45 @@
+---
+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
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+@ main ^| . | 05a4a45d 16h Initial commit
++ feature _| ../repo.feature | 05a4a45d 16h Initial commit
++ feature-a ↑| ↑1 +1 ../repo.feature-a | 1b87d473 16h Add feature-a file
++ feature-b ↑| ↑1 +1 ../repo.feature-b | f62940fc 16h Add feature-b file
++ feature-c ↑| ↑1 +1 ../repo.feature-c | 345c7c93 16h Add feature-c file
+
+○ Showing 5 worktrees, 3 ahead
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__ci_status__gitlab_single_mr_no_project_id.snap b/tests/snapshots/integration__integration_tests__ci_status__gitlab_single_mr_no_project_id.snap
new file mode 100644
index 000000000..5d88835a9
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__ci_status__gitlab_single_mr_no_project_id.snap
@@ -0,0 +1,45 @@
+---
+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
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WT_TEST_DELAYED_STREAM_MS: "-1"
+ WT_TEST_EPOCH: "1735776000"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+ Branch Status HEAD± main↕ main…± Path Remote⇅ CI Commit Age Message
+@ main ^| . | ● 05a4a45d 16h Initial commit
++ feature _| ../repo.feature | ● 05a4a45d 16h Initial commit
++ feature-a ↑| ↑1 +1 ../repo.feature-a | ● 1b87d473 16h Add feature-a file
++ feature-b ↑| ↑1 +1 ../repo.feature-b | ● f62940fc 16h Add feature-b file
++ feature-c ↑| ↑1 +1 ../repo.feature-c | ● 345c7c93 16h Add feature-c file
+
+○ Showing 5 worktrees, 3 ahead
+
+----- stderr -----