Skip to content

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

fix: prevent panics and incorrect behavior in hooks and CI status (#846)

Maximilian Roos5678759446d1
diff --git a/src/commands/list/ci_status/gitlab.rs b/src/commands/list/ci_status/gitlab.rs
index 81b4f2b1b..69dee6e53 100644
--- a/src/commands/list/ci_status/gitlab.rs
+++ b/src/commands/list/ci_status/gitlab.rs
@@ -139,14 +139,21 @@ pub(super) fn detect_gitlab(
);
}
matched
+ } else if mr_list.len() == 1 {
+ // If we can't determine project ID but there's only one MR, it's unambiguous
+ mr_list.first()
+ } else if mr_list.is_empty() {
+ // No MRs found
+ None
} else {
- // If we can't determine project ID, fall back to first MR
+ // Multiple MRs exist but we can't determine which project we're in.
+ // Don't guess - return None to avoid showing wrong project's CI status.
log::debug!(
- "No project ID for {}, using first MR for branch {}",
- repo_root.display(),
+ "Found {} MRs for branch {} but no project ID to filter - skipping to avoid ambiguity",
+ mr_list.len(),
branch.full_name
);
- mr_list.first()
+ None
}?;
// Step 2: Fetch full MR details to get pipeline status.
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 53e970939..bcdd4a6f5 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -139,7 +139,7 @@ impl HookLog {
Ok(Self::Internal(op))
}
// source:hook-type:name
- [source_str, hook_type_str, name] => {
+ [source_str, hook_type_str, name] if !name.is_empty() => {
let source = HookSource::from_str(source_str).map_err(|_| {
cformat!(
"Unknown source: <bold>{}</>. Valid: user, project",
@@ -648,19 +648,18 @@ mod tests {
#[test]
fn test_hook_log_parse_invalid_format() {
- // Too many colons
- let result = HookLog::parse("user:post-start:server:extra");
- assert!(result.is_err());
- assert!(result.unwrap_err().contains("Invalid log spec"));
-
- // Single word (not valid anymore)
+ // Single word (no colons)
let result = HookLog::parse("remove");
assert!(result.is_err());
assert!(result.unwrap_err().contains("Invalid log spec"));
- // Two colons but not internal:op
+ // Two parts but not internal:op (missing hook name)
let result = HookLog::parse("foo:bar");
assert!(result.is_err());
+
+ // Missing hook-type segment
+ let result = HookLog::parse("user:");
+ assert!(result.is_err());
}
#[test]
@@ -704,4 +703,20 @@ mod tests {
let parsed = HookLog::parse(&spec).unwrap();
assert_eq!(original, parsed);
}
+
+ #[test]
+ fn test_hook_log_parse_rejects_colons_in_name() {
+ // Hook names cannot contain colons (would make parsing ambiguous)
+ let result = HookLog::parse("user:post-start:my:server");
+ assert!(result.is_err(), "Colons in hook names should be rejected");
+ assert!(result.unwrap_err().contains("Invalid log spec"));
+ }
+
+ #[test]
+ fn test_hook_log_parse_rejects_empty_name() {
+ // Empty hook name should be rejected
+ let result = HookLog::parse("user:post-start:");
+ assert!(result.is_err(), "Empty hook name should be rejected");
+ assert!(result.unwrap_err().contains("Invalid log spec"));
+ }
}
diff --git a/src/config/commands.rs b/src/config/commands.rs
index a44cd8e1f..4958c7150 100644
--- a/src/config/commands.rs
+++ b/src/config/commands.rs
@@ -93,6 +93,15 @@ impl<'de> Deserialize<'de> for CommandConfig {
}
CommandConfigToml::Named(map) => {
// IndexMap preserves insertion order from TOML
+ // Validate hook names don't contain colons (would break log spec parsing)
+ for name in map.keys() {
+ if name.contains(':') {
+ return Err(serde::de::Error::custom(format!(
+ "hook name '{}' cannot contain colons",
+ name
+ )));
+ }
+ }
map.into_iter()
.map(|(name, template)| Command::new(Some(name), template))
.collect()
@@ -131,11 +140,19 @@ impl Serialize for CommandConfig {
return self.commands[0].template.serialize(serializer);
}
- // Serialize as named map (all commands from Named format have names)
+ // Serialize as named map. Auto-generate names for unnamed commands
+ // (can happen when merging unnamed global hooks with named project hooks).
let mut map = serializer.serialize_map(Some(self.commands.len()))?;
+ let mut unnamed_counter = 0u32;
for cmd in &self.commands {
- let key = cmd.name.as_ref().unwrap();
- map.serialize_entry(key, &cmd.template)?;
+ let key = match &cmd.name {
+ Some(name) => name.clone(),
+ None => {
+ unnamed_counter += 1;
+ format!("_{}", unnamed_counter)
+ }
+ };
+ map.serialize_entry(&key, &cmd.template)?;
}
map.end()
}
@@ -241,6 +258,30 @@ third = "echo 3"
assert_eq!(commands[2].name, Some("third".to_string()));
}
+ #[test]
+ fn test_deserialize_rejects_colons_in_name() {
+ // Hook names cannot contain colons (would break log spec parsing)
+ let toml_str = r#"
+[command]
+"my:server" = "npm start"
+"#;
+
+ #[derive(Debug, Deserialize)]
+ struct Wrapper {
+ #[serde(rename = "command")]
+ _command: CommandConfig,
+ }
+
+ let result: Result<Wrapper, _> = toml::from_str(toml_str);
+ assert!(result.is_err());
+ let err = result.unwrap_err().to_string();
+ assert!(
+ err.contains("cannot contain colons"),
+ "Expected colon rejection error: {}",
+ err
+ );
+ }
+
// ============================================================================
// CommandConfig Serialization Tests
// ============================================================================
@@ -399,4 +440,40 @@ third = "echo 3"
assert_eq!(merged.commands.len(), 1);
assert_eq!(merged.commands[0].template, "echo base");
}
+
+ #[test]
+ fn test_serialize_mixed_named_unnamed_commands() {
+ // When merging unnamed global hooks with named project hooks,
+ // the result has both named and unnamed commands. Serialization
+ // must handle this without panicking.
+ #[derive(Serialize)]
+ struct Wrapper {
+ cmd: CommandConfig,
+ }
+
+ // Simulate merge of unnamed global + named project
+ let global = CommandConfig {
+ commands: vec![Command::new(None, "echo global".to_string())],
+ };
+ let project = CommandConfig {
+ commands: vec![Command::new(
+ Some("build".to_string()),
+ "cargo build".to_string(),
+ )],
+ };
+ let merged = global.merge_append(&project);
+
+ // This should NOT panic
+ let wrapper = Wrapper { cmd: merged };
+ let result = toml::to_string(&wrapper);
+
+ // Should succeed and contain both commands
+ assert!(result.is_ok(), "Serialization panicked or failed");
+ let serialized = result.unwrap();
+ assert!(serialized.contains("echo global"), "Missing global command");
+ assert!(
+ serialized.contains("cargo build"),
+ "Missing project command"
+ );
+ }
}
diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rs
index cfc661ac4..600ee3815 100644
--- a/tests/integration_tests/config_state.rs
+++ b/tests/integration_tests/config_state.rs
@@ -1312,8 +1312,8 @@ fn test_state_logs_get_hook_with_branch_flag(repo: TestRepo) {
#[rstest]
fn test_state_logs_get_hook_invalid_format(repo: TestRepo) {
- // Test invalid hook spec format (too many colons)
- let output = wt_state_cmd(&repo, "logs", "get", &["--hook=a:b:c:d"])
+ // Test invalid hook spec format (missing required segments)
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user"])
.output()
.unwrap();
assert!(!output.status.success());
@@ -1325,6 +1325,21 @@ fn test_state_logs_get_hook_invalid_format(repo: TestRepo) {
);
}
+#[rstest]
+fn test_state_logs_get_hook_rejects_colons_in_name(repo: TestRepo) {
+ // Hook names cannot contain colons (makes parsing ambiguous)
+ let output = wt_state_cmd(&repo, "logs", "get", &["--hook=user:post-start:my:server"])
+ .output()
+ .unwrap();
+ assert!(!output.status.success());
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Invalid log spec"),
+ "Colons in hook names should be rejected: {}",
+ stderr
+ );
+}
+
#[rstest]
fn test_state_logs_get_hook_invalid_source(repo: TestRepo) {
// Test invalid source