Skip to content

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

Refactor ClaudeCodeContext parsing and add tests

Maximilian Roos5414addc2cd2
diff --git a/src/commands/statusline.rs b/src/commands/statusline.rs
index 7f203fbbc..37d886295 100644
--- a/src/commands/statusline.rs
+++ b/src/commands/statusline.rs
@@ -25,31 +25,15 @@ struct ClaudeCodeContext {
}
impl ClaudeCodeContext {
- /// Try to read and parse Claude Code context from stdin.
- /// Returns None if stdin is empty or not valid JSON.
- fn from_stdin() -> Option<Self> {
- // Non-blocking read with timeout
- // Claude Code pipes JSON to stdin, but we shouldn't block if nothing is there
- use std::sync::mpsc;
- use std::thread;
-
- let (tx, rx) = mpsc::channel();
-
- thread::spawn(move || {
- let mut input = String::new();
- let _ = io::stdin().read_to_string(&mut input);
- let _ = tx.send(input);
- });
-
- // Wait up to 10ms for stdin
- let input = rx.recv_timeout(Duration::from_millis(10)).ok()?;
-
+ /// Parse Claude Code context from a JSON string.
+ /// Returns None if the string is empty or not valid JSON.
+ fn parse(input: &str) -> Option<Self> {
if input.is_empty() {
return None;
}
// Parse JSON
- let json: serde_json::Value = serde_json::from_str(&input).ok()?;
+ let json: serde_json::Value = serde_json::from_str(input).ok()?;
let current_dir = json
.get("workspace")
@@ -69,6 +53,28 @@ impl ClaudeCodeContext {
model_name,
})
}
+
+ /// Try to read and parse Claude Code context from stdin.
+ /// Returns None if stdin is empty or not valid JSON.
+ fn from_stdin() -> Option<Self> {
+ // Non-blocking read with timeout
+ // Claude Code pipes JSON to stdin, but we shouldn't block if nothing is there
+ use std::sync::mpsc;
+ use std::thread;
+
+ let (tx, rx) = mpsc::channel();
+
+ thread::spawn(move || {
+ let mut input = String::new();
+ let _ = io::stdin().read_to_string(&mut input);
+ let _ = tx.send(input);
+ });
+
+ // Wait up to 10ms for stdin
+ let input = rx.recv_timeout(Duration::from_millis(10)).ok()?;
+
+ Self::parse(&input)
+ }
}
/// Format a directory path in fish-style (abbreviated parent directories).
@@ -117,8 +123,9 @@ fn format_directory_fish_style(path: &str) -> String {
/// Run the statusline command.
///
-/// Uses the output system like other commands - output goes to stderr in both interactive
-/// and directive modes, keeping stdout clean for shell directives.
+/// Uses the output system like other commands:
+/// - Interactive mode: output goes to stdout
+/// - Directive mode: output goes to stderr, keeping stdout clean for shell directives
pub fn run(claude_code: bool) -> Result<()> {
// Get context - either from stdin (claude-code mode) or current directory
let (cwd, model_name) = if claude_code {
@@ -252,4 +259,71 @@ mod tests {
);
}
}
+
+ #[test]
+ fn test_claude_code_context_parse_full() {
+ // Full Claude Code context JSON (as documented)
+ let json = r#"{
+ "hook_event_name": "Status",
+ "session_id": "abc123",
+ "cwd": "/current/working/directory",
+ "model": {
+ "id": "claude-opus-4-1",
+ "display_name": "Opus"
+ },
+ "workspace": {
+ "current_dir": "/home/user/project",
+ "project_dir": "/home/user/project"
+ },
+ "version": "1.0.80"
+ }"#;
+
+ let ctx = ClaudeCodeContext::parse(json).expect("should parse");
+ assert_eq!(ctx.current_dir, "/home/user/project");
+ assert_eq!(ctx.model_name, Some("Opus".to_string()));
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_minimal() {
+ // Minimal JSON with just the fields we need
+ let json = r#"{
+ "workspace": {"current_dir": "/tmp/test"},
+ "model": {"display_name": "Haiku"}
+ }"#;
+
+ let ctx = ClaudeCodeContext::parse(json).expect("should parse");
+ assert_eq!(ctx.current_dir, "/tmp/test");
+ assert_eq!(ctx.model_name, Some("Haiku".to_string()));
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_missing_model() {
+ // Model is optional
+ let json = r#"{"workspace": {"current_dir": "/tmp/test"}}"#;
+
+ let ctx = ClaudeCodeContext::parse(json).expect("should parse");
+ assert_eq!(ctx.current_dir, "/tmp/test");
+ assert_eq!(ctx.model_name, None);
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_missing_workspace() {
+ // Missing workspace defaults to "."
+ let json = r#"{"model": {"display_name": "Sonnet"}}"#;
+
+ let ctx = ClaudeCodeContext::parse(json).expect("should parse");
+ assert_eq!(ctx.current_dir, ".");
+ assert_eq!(ctx.model_name, Some("Sonnet".to_string()));
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_empty() {
+ assert!(ClaudeCodeContext::parse("").is_none());
+ }
+
+ #[test]
+ fn test_claude_code_context_parse_invalid_json() {
+ assert!(ClaudeCodeContext::parse("not json").is_none());
+ assert!(ClaudeCodeContext::parse("{invalid}").is_none());
+ }
}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index fc621be8f..f9eaa17d1 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -36,4 +36,5 @@ pub mod security;
pub mod select;
pub mod shell_wrapper;
pub mod spacing_edge_cases;
+pub mod statusline;
pub mod switch;
diff --git a/tests/integration_tests/statusline.rs b/tests/integration_tests/statusline.rs
new file mode 100644
index 000000000..a627b28f1
--- /dev/null
+++ b/tests/integration_tests/statusline.rs
@@ -0,0 +1,236 @@
+//! Snapshot tests for `wt beta statusline` command.
+//!
+//! Tests the statusline output for shell prompts and Claude Code integration.
+
+use crate::common::{TestRepo, wt_command};
+use insta::assert_snapshot;
+use std::io::Write;
+use std::process::Stdio;
+
+/// Run statusline command with optional JSON piped to stdin
+fn run_statusline_from_dir(
+ repo: &TestRepo,
+ args: &[&str],
+ stdin_json: Option<&str>,
+ cwd: &std::path::Path,
+) -> String {
+ let mut cmd = wt_command();
+ cmd.current_dir(cwd);
+ cmd.args(["beta", "statusline"]);
+ cmd.args(args);
+
+ // Apply repo's git environment
+ repo.clean_cli_env(&mut cmd);
+
+ if stdin_json.is_some() {
+ cmd.stdin(Stdio::piped());
+ }
+ cmd.stdout(Stdio::piped());
+ cmd.stderr(Stdio::piped());
+
+ let mut child = cmd.spawn().expect("failed to spawn command");
+
+ if let Some(json) = stdin_json {
+ let stdin = child.stdin.as_mut().expect("failed to get stdin");
+ stdin
+ .write_all(json.as_bytes())
+ .expect("failed to write stdin");
+ }
+
+ let output = child.wait_with_output().expect("failed to wait for output");
+
+ // Statusline outputs to stdout in interactive mode, stderr in directive mode
+ // For tests without --internal, we capture stdout
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ // Return whichever has content (stdout for interactive, stderr for --internal)
+ if !stdout.is_empty() {
+ stdout.to_string()
+ } else {
+ stderr.to_string()
+ }
+}
+
+fn run_statusline(repo: &TestRepo, args: &[&str], stdin_json: Option<&str>) -> String {
+ run_statusline_from_dir(repo, args, stdin_json, repo.root_path())
+}
+
+// --- Test Fixtures ---
+
+fn setup_basic_repo() -> TestRepo {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo
+}
+
+fn setup_repo_with_changes() -> TestRepo {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create uncommitted changes
+ std::fs::write(repo.root_path().join("modified.txt"), "modified content").unwrap();
+
+ repo
+}
+
+fn setup_repo_with_commits_ahead() -> TestRepo {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+ repo.setup_remote("main");
+
+ // Create feature branch with commits ahead
+ let feature_path = repo.add_worktree("feature", "feature");
+
+ // Add commits in the feature worktree
+ std::fs::write(feature_path.join("feature.txt"), "feature content").unwrap();
+ repo.git_command(&["add", "."])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ repo.git_command(&["commit", "-m", "Feature commit 1"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ std::fs::write(feature_path.join("feature2.txt"), "more content").unwrap();
+ repo.git_command(&["add", "."])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+ repo.git_command(&["commit", "-m", "Feature commit 2"])
+ .current_dir(&feature_path)
+ .output()
+ .unwrap();
+
+ repo
+}
+
+// --- Basic Tests ---
+
+#[test]
+fn test_statusline_basic() {
+ let repo = setup_basic_repo();
+ let output = run_statusline(&repo, &[], None);
+ assert_snapshot!(output, @"main");
+}
+
+#[test]
+fn test_statusline_with_changes() {
+ let repo = setup_repo_with_changes();
+ let output = run_statusline(&repo, &[], None);
+ assert_snapshot!(output, @"main ?");
+}
+
+#[test]
+fn test_statusline_commits_ahead() {
+ let repo = setup_repo_with_commits_ahead();
+ // Run from the feature worktree to see commits ahead
+ let feature_path = repo.worktree_path("feature");
+ let output = run_statusline_from_dir(&repo, &[], None, feature_path);
+ assert_snapshot!(output, @"feature ↑2");
+}
+
+// --- Claude Code Mode Tests ---
+
+/// Create snapshot settings that filter the dynamic temp path
+fn claude_code_snapshot_settings(repo: &TestRepo) -> insta::Settings {
+ let mut settings = insta::Settings::clone_current();
+ // The path gets fish-style abbreviated, so filter the abbreviated form
+ // e.g., /private/var/folders/.../test-repo -> /p/v/f/.../test-repo
+ // We replace everything up to "test-repo" with [PATH]
+ settings.add_filter(r"(?m)^.*test-repo", "[PATH]");
+ // Also filter the raw path in case it appears
+ settings.add_filter(&repo.root_path().display().to_string(), "[PATH]");
+ settings
+}
+
+#[test]
+fn test_statusline_claude_code_full_context() {
+ let repo = setup_repo_with_changes();
+
+ let json = format!(
+ r#"{{
+ "hook_event_name": "Status",
+ "session_id": "test-session",
+ "model": {{
+ "id": "claude-opus-4-1",
+ "display_name": "Opus"
+ }},
+ "workspace": {{
+ "current_dir": "{}",
+ "project_dir": "{}"
+ }},
+ "version": "1.0.80"
+ }}"#,
+ repo.root_path().display(),
+ repo.root_path().display()
+ );
+
+ let output = run_statusline(&repo, &["--claude-code"], Some(&json));
+ claude_code_snapshot_settings(&repo).bind(|| {
+ assert_snapshot!(output, @"[PATH] main ? | Opus");
+ });
+}
+
+#[test]
+fn test_statusline_claude_code_minimal() {
+ let repo = setup_basic_repo();
+
+ let json = format!(
+ r#"{{"workspace": {{"current_dir": "{}"}}}}"#,
+ repo.root_path().display()
+ );
+
+ let output = run_statusline(&repo, &["--claude-code"], Some(&json));
+ claude_code_snapshot_settings(&repo).bind(|| {
+ assert_snapshot!(output, @"[PATH] main");
+ });
+}
+
+#[test]
+fn test_statusline_claude_code_with_model() {
+ let repo = setup_basic_repo();
+
+ let json = format!(
+ r#"{{
+ "workspace": {{"current_dir": "{}"}},
+ "model": {{"display_name": "Haiku"}}
+ }}"#,
+ repo.root_path().display()
+ );
+
+ let output = run_statusline(&repo, &["--claude-code"], Some(&json));
+ claude_code_snapshot_settings(&repo).bind(|| {
+ assert_snapshot!(output, @"[PATH] main | Haiku");
+ });
+}
+
+// --- Directive Mode Tests ---
+
+#[test]
+fn test_statusline_directive_mode() {
+ // When called with --internal, output goes to stderr (stdout empty for shell eval)
+ let repo = setup_repo_with_changes();
+
+ let mut cmd = wt_command();
+ cmd.current_dir(repo.root_path());
+ cmd.args(["--internal", "beta", "statusline"]);
+ repo.clean_cli_env(&mut cmd);
+
+ let output = cmd.output().expect("failed to run command");
+
+ // stdout should be empty in directive mode
+ assert!(
+ output.stdout.is_empty(),
+ "stdout should be empty in directive mode, got: {:?}",
+ String::from_utf8_lossy(&output.stdout)
+ );
+
+ // stderr should have the statusline
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !stderr.is_empty(),
+ "stderr should have statusline output in directive mode"
+ );
+}