Skip to content

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

Feat: Add JSON output format for `list` command

Maximilian Roos79798403a583
diff --git a/Cargo.lock b/Cargo.lock
index 547b56306..830e0f46b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2023,6 +2023,7 @@ dependencies = [
"rayon",
"rstest",
"serde",
+ "serde_json",
"tempfile",
"terminal_size",
"toml 0.8.23",
diff --git a/Cargo.toml b/Cargo.toml
index 66cf39e51..39a647ef2 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -26,6 +26,7 @@ config = "0.15"
directories = "6.0"
rayon = "1.10"
serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
terminal_size = "0.4"
unicode-width = "0.2"
diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rs
index 5ca665f15..48c6e1810 100644
--- a/src/commands/list/mod.rs
+++ b/src/commands/list/mod.rs
@@ -10,6 +10,7 @@ use worktrunk::git::{GitError, Repository};
use layout::calculate_responsive_layout;
use render::{format_header_line, format_worktree_line};
+#[derive(serde::Serialize)]
pub struct WorktreeInfo {
pub worktree: worktrunk::git::Worktree,
pub timestamp: i64,
@@ -98,7 +99,7 @@ impl WorktreeInfo {
}
}
-pub fn handle_list() -> Result<(), GitError> {
+pub fn handle_list(format: crate::OutputFormat) -> Result<(), GitError> {
let repo = Repository::current();
let worktrees = repo.list_worktrees()?;
@@ -141,15 +142,26 @@ pub fn handle_list() -> Result<(), GitError> {
// Sort by most recent commit (descending)
infos.sort_by(|a, b| b.timestamp.cmp(&a.timestamp));
- // Calculate responsive layout based on terminal width
- let layout = calculate_responsive_layout(&infos);
-
- // Display header
- format_header_line(&layout);
-
- // Display formatted output
- for info in &infos {
- format_worktree_line(info, &layout, current_worktree_path.as_ref());
+ match format {
+ crate::OutputFormat::Json => {
+ // Output JSON format
+ let json = serde_json::to_string_pretty(&infos).map_err(|e| {
+ GitError::CommandFailed(format!("Failed to serialize to JSON: {}", e))
+ })?;
+ println!("{}", json);
+ }
+ crate::OutputFormat::Table => {
+ // Calculate responsive layout based on terminal width
+ let layout = calculate_responsive_layout(&infos);
+
+ // Display header
+ format_header_line(&layout);
+
+ // Display formatted output
+ for info in &infos {
+ format_worktree_line(info, &layout, current_worktree_path.as_ref());
+ }
+ }
}
Ok(())
diff --git a/src/git.rs b/src/git.rs
index 4e4985e9f..a5ea6ea05 100644
--- a/src/git.rs
+++ b/src/git.rs
@@ -1,7 +1,7 @@
use std::path::PathBuf;
use std::process::Command;
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct Worktree {
pub path: PathBuf,
pub head: String,
diff --git a/src/main.rs b/src/main.rs
index be98c9035..bff75d68d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -12,6 +12,14 @@ use commands::{
handle_remove, handle_switch,
};
+#[derive(Debug, Clone, Copy, clap::ValueEnum)]
+pub enum OutputFormat {
+ /// Human-readable table format
+ Table,
+ /// JSON format
+ Json,
+}
+
#[derive(Parser)]
#[command(name = "wt")]
#[command(about = "Git worktree management", long_about = None)]
@@ -35,7 +43,11 @@ enum Commands {
},
/// List all worktrees
- List,
+ List {
+ /// Output format
+ #[arg(long, value_enum, default_value = "table")]
+ format: OutputFormat,
+ },
/// Switch to a worktree
Switch {
@@ -111,7 +123,7 @@ fn main() {
let mut cli_cmd = Cli::command();
handle_init(&shell, &cmd, &mut cli_cmd).map_err(GitError::CommandFailed)
}
- Commands::List => handle_list(),
+ Commands::List { format } => handle_list(format),
Commands::Switch {
branch,
create,
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 59eecd387..97d6709a7 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -33,6 +33,41 @@ fn snapshot_list(test_name: &str, repo: &TestRepo) {
});
}
+/// Helper to create snapshot for JSON output with normalized paths, SHAs, and timestamps
+fn snapshot_list_json(test_name: &str, repo: &TestRepo) {
+ let mut settings = Settings::clone_current();
+ settings.set_snapshot_path("../snapshots");
+
+ // Normalize paths - replace absolute paths with semantic names
+ settings.add_filter(repo.root_path().to_str().unwrap(), "[REPO]");
+ for (name, path) in &repo.worktrees {
+ settings.add_filter(
+ path.to_str().unwrap(),
+ &format!("[WORKTREE_{}]", name.to_uppercase().replace('-', "_")),
+ );
+ }
+
+ // Normalize git SHAs (40 hex chars in JSON)
+ settings.add_filter(r#""head": "[0-9a-f]{40}""#, r#""head": "[SHA]""#);
+
+ // Normalize timestamps to fixed value
+ settings.add_filter(r#""timestamp": \d+"#, r#""timestamp": 0"#);
+
+ // Normalize Windows paths to Unix style
+ settings.add_filter(r"\\\\", "/");
+
+ settings.bind(|| {
+ let mut cmd = Command::new(get_cargo_bin("wt"));
+ // Clean environment to avoid interference from global git config
+ repo.clean_cli_env(&mut cmd);
+ cmd.arg("list")
+ .arg("--format=json")
+ .current_dir(repo.root_path());
+
+ assert_cmd_snapshot!(test_name, cmd);
+ });
+}
+
#[test]
fn test_list_single_worktree() {
let repo = TestRepo::new();
@@ -153,3 +188,37 @@ fn test_list_many_worktrees_with_varied_stats() {
snapshot_list("many_worktrees_varied", &repo);
}
+
+#[test]
+fn test_list_json_single_worktree() {
+ let repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ snapshot_list_json("json_single_worktree", &repo);
+}
+
+#[test]
+fn test_list_json_multiple_worktrees() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ repo.add_worktree("feature-a", "feature-a");
+ repo.add_worktree("feature-b", "feature-b");
+
+ snapshot_list_json("json_multiple_worktrees", &repo);
+}
+
+#[test]
+fn test_list_json_with_metadata() {
+ let mut repo = TestRepo::new();
+ repo.commit("Initial commit");
+
+ // Create worktree with detached head
+ repo.add_worktree("feature-detached", "feature-detached");
+
+ // Create locked worktree
+ repo.add_worktree("locked-feature", "locked-feature");
+ repo.lock_worktree("locked-feature", Some("Testing"));
+
+ snapshot_list_json("json_with_metadata", &repo);
+}
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snap
index 07320e1ca..d909a730a 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap
@@ -180,12 +180,16 @@ _wt() {
return 0
;;
wt__list)
- opts="-h --help"
+ opts="-h --format --help"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
fi
case "${prev}" in
+ --format)
+ COMPREPLY=($(compgen -W "table json" -- "${cur}"))
+ return 0
+ ;;
*)
COMPREPLY=()
;;
diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
index 12ecdaee3..770f933ac 100644
--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap
@@ -182,12 +182,16 @@ _wt() {
return 0
;;
wt__list)
- opts="-h --help"
+ opts="-h --format --help"
if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )
return 0
fi
case "${prev}" in
+ --format)
+ COMPREPLY=($(compgen -W "table json" -- "${cur}"))
+ return 0
+ ;;
*)
COMPREPLY=()
;;
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 9af1cb937..17067d472 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -104,7 +104,9 @@ complete -c wt -n "__fish_wt_needs_command" -f -a "push" -d 'Push changes betwee
complete -c wt -n "__fish_wt_needs_command" -f -a "merge" -d 'Merge worktree into target branch'
complete -c wt -n "__fish_wt_using_subcommand init" -l cmd -d 'Command prefix (default: wt)' -r
complete -c wt -n "__fish_wt_using_subcommand init" -s h -l help -d 'Print help'
-complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help'
+complete -c wt -n "__fish_wt_using_subcommand list" -l format -d 'Output format' -r -f -a "table\t'Human-readable table format'
+json\t'JSON format'"
+complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help (see more with \'--help\')'
complete -c wt -n "__fish_wt_using_subcommand switch" -s b -l base -d 'Base branch to create from (only with --create)' -r
complete -c wt -n "__fish_wt_using_subcommand switch" -s c -l create -d 'Create a new branch'
complete -c wt -n "__fish_wt_using_subcommand switch" -l internal -d 'Use internal mode (outputs directives for shell wrapper)'
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index f5b31e03f..2faeff2dc 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -111,8 +111,10 @@ _arguments "${_arguments_options[@]}" : \
;;
(list)
_arguments "${_arguments_options[@]}" : \
-'-h[Print help]' \
-'--help[Print help]' \
+'--format=[Output format]:FORMAT:((table\:"Human-readable table format"
+json\:"JSON format"))' \
+'-h[Print help (see more with '\''--help'\'')]' \
+'--help[Print help (see more with '\''--help'\'')]' \
&& ret=0
;;
(switch)
diff --git a/tests/snapshots/integration__integration_tests__list__json_multiple_worktrees.snap b/tests/snapshots/integration__integration_tests__list__json_multiple_worktrees.snap
new file mode 100644
index 000000000..1c8f724e1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__json_multiple_worktrees.snap
@@ -0,0 +1,109 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--format=json"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+[
+ {
+ "worktree": {
+ "path": "[REPO]",
+ "head": "[SHA]",
+ "branch": "main",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": true,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ },
+ {
+ "worktree": {
+ "path": "[WORKTREE_FEATURE_A]",
+ "head": "[SHA]",
+ "branch": "feature-a",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": false,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ },
+ {
+ "worktree": {
+ "path": "[WORKTREE_FEATURE_B]",
+ "head": "[SHA]",
+ "branch": "feature-b",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": false,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ }
+]
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__list__json_single_worktree.snap b/tests/snapshots/integration__integration_tests__list__json_single_worktree.snap
new file mode 100644
index 000000000..685764e33
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__json_single_worktree.snap
@@ -0,0 +1,53 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--format=json"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+[
+ {
+ "worktree": {
+ "path": "[REPO]",
+ "head": "[SHA]",
+ "branch": "main",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": true,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ }
+]
+
+----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
new file mode 100644
index 000000000..8eb365080
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__list__json_with_metadata.snap
@@ -0,0 +1,109 @@
+---
+source: tests/integration_tests/list.rs
+info:
+ program: wt
+ args:
+ - list
+ - "--format=json"
+ env:
+ CLICOLOR_FORCE: "1"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: /dev/null
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ LANG: C
+ LC_ALL: C
+ SOURCE_DATE_EPOCH: "1704067200"
+---
+success: true
+exit_code: 0
+----- stdout -----
+[
+ {
+ "worktree": {
+ "path": "[REPO]",
+ "head": "[SHA]",
+ "branch": "main",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": true,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ },
+ {
+ "worktree": {
+ "path": "[WORKTREE_FEATURE_DETACHED]",
+ "head": "[SHA]",
+ "branch": "feature-detached",
+ "bare": false,
+ "detached": false,
+ "locked": null,
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": false,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ },
+ {
+ "worktree": {
+ "path": "[WORKTREE_LOCKED_FEATURE]",
+ "head": "[SHA]",
+ "branch": "locked-feature",
+ "bare": false,
+ "detached": false,
+ "locked": "Testing",
+ "prunable": null
+ },
+ "timestamp": 0,
+ "commit_message": "Initial commit",
+ "ahead": 0,
+ "behind": 0,
+ "working_tree_diff": [
+ 0,
+ 0
+ ],
+ "branch_diff": [
+ 0,
+ 0
+ ],
+ "is_primary": false,
+ "upstream_remote": null,
+ "upstream_ahead": 0,
+ "upstream_behind": 0,
+ "worktree_state": null
+ }
+]
+
+----- stderr -----