gwm 0.3.4

Git Worktree Manager - A CLI tool for managing Git worktrees with an interactive TUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
//! listコマンド実装
//!
//! `gwm list` コマンドのエントリーポイントを提供します。

use serde::Serialize;

use crate::cli::{ListArgs, OutputFormat};
use crate::config::load_config;
use crate::error::Result;
use crate::git::{
    get_worktrees, get_worktrees_with_details, Worktree, CHANGES_LEGEND, STATUS_LEGEND,
};
use crate::ui::widgets::{calculate_column_widths, truncate_and_pad, truncate_start, ColumnWidths};

/// デフォルトターミナルサイズ(幅, 高さ)
const DEFAULT_TERMINAL_SIZE: (u16, u16) = (120, 24);

/// worktreeが空の場合のメッセージを表示
fn print_empty_worktrees_message() {
    println!("\x1b[33mNo worktrees found\x1b[0m");
    println!("\x1b[90mUse \x1b[36mgwm add\x1b[90m to create one\x1b[0m");
}

/// リスト表示用の共通ヘッダーを出力
fn print_list_header(worktree_count: usize, base_path: &str) {
    println!("\x1b[1;36mWorktrees\x1b[0m");
    println!("\x1b[90mTotal: \x1b[1;37m{}\x1b[0m", worktree_count);
    println!("\x1b[90m${{B}} = {}\x1b[0m", base_path);
    println!();
}

/// SYNC列の幅
const SYNC_WIDTH: usize = 8;

/// CHANGES列の幅
const CHANGES_WIDTH: usize = 10;

/// ACTIVITY列の幅
const ACTIVITY_WIDTH: usize = 10;

/// JSON出力用の同期状態
#[derive(Serialize)]
struct SyncJson {
    ahead: usize,
    behind: usize,
}

/// JSON出力用の変更状態
#[derive(Serialize)]
struct ChangesJson {
    modified: usize,
    added: usize,
    deleted: usize,
    untracked: usize,
}

/// JSON出力用のworktree
#[derive(Serialize)]
struct WorktreeJson {
    branch: String,
    path: String,
    status: String,
    head: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    sync: Option<SyncJson>,
    #[serde(skip_serializing_if = "Option::is_none")]
    changes: Option<ChangesJson>,
    #[serde(skip_serializing_if = "Option::is_none")]
    last_activity: Option<String>,
}

/// listコマンドを実行
///
/// Gitリポジトリ内のworktree一覧を取得し、指定されたフォーマットで表示します。
pub fn run_list(args: ListArgs) -> Result<()> {
    match args.format {
        OutputFormat::Json => run_list_json(),
        OutputFormat::Names => run_list_names(),
        OutputFormat::Table => {
            if args.compact {
                run_list_compact()
            } else {
                run_list_detailed()
            }
        }
    }
}

/// 詳細表示(新レイアウト)
fn run_list_detailed() -> Result<()> {
    let config = load_config();
    let worktrees = get_worktrees_with_details()?;

    if worktrees.is_empty() {
        print_empty_worktrees_message();
        return Ok(());
    }

    // ターミナル幅を取得
    let (width, _) = crossterm::terminal::size().unwrap_or(DEFAULT_TERMINAL_SIZE);

    // 列幅計算(新カラム分を差し引く)
    let extra_width = SYNC_WIDTH + CHANGES_WIDTH + ACTIVITY_WIDTH + 3; // 余白分
    let adjusted_width = width.saturating_sub(extra_width as u16);

    let items: Vec<(String, String)> = worktrees
        .iter()
        .map(|w| (w.display_branch().to_string(), w.path.display().to_string()))
        .collect();
    let column_widths = calculate_column_widths(&items, adjusted_width);

    print_list_header(worktrees.len(), &config.worktree_base_path);

    // チルダ展開されたベースパス(パス比較用)
    let expanded_base_path = config
        .expanded_worktree_base_path()
        .map(|p| p.display().to_string())
        .unwrap_or_default();

    // テーブルヘッダー
    println!(
        "\x1b[1;36m   {:<branch$} {:^SYNC_WIDTH$} {:<CHANGES_WIDTH$} {:<path$} {:<ACTIVITY_WIDTH$}\x1b[0m",
        "BRANCH",
        "SYNC",
        "CHANGES",
        "PATH",
        "ACTIVITY",
        branch = column_widths.branch,
        path = column_widths.path,
    );
    println!(
        "\x1b[90m   {} {:^SYNC_WIDTH$} {:<CHANGES_WIDTH$} {} {:<ACTIVITY_WIDTH$}\x1b[0m",
        "".repeat(column_widths.branch),
        "════",
        "═══════",
        "".repeat(column_widths.path),
        "════════",
    );

    // データ行
    for worktree in &worktrees {
        print_worktree_row_detailed(worktree, &expanded_base_path, &column_widths);
    }

    println!();

    // 凡例
    println!("\x1b[90m{STATUS_LEGEND}\x1b[0m");
    println!("\x1b[90m{CHANGES_LEGEND}\x1b[0m");

    Ok(())
}

/// 詳細レイアウトで1行出力
fn print_worktree_row_detailed(worktree: &Worktree, base_path: &str, widths: &ColumnWidths) {
    let status = &worktree.status;

    // ブランチ名(末尾を切り詰め)
    let branch = truncate_and_pad(worktree.display_branch(), widths.branch);

    // SYNC表示(中央寄せ)
    let sync_str = worktree
        .sync_status
        .as_ref()
        .map(|s| s.display())
        .unwrap_or_else(|| "-".to_string());
    let sync_display = format!("{:^SYNC_WIDTH$}", sync_str);
    let sync_color = if worktree.sync_status.as_ref().is_some_and(|s| s.is_synced()) {
        "\x1b[32m" // Green
    } else {
        "\x1b[37m" // White
    };

    // CHANGES表示
    let changes_str = worktree
        .change_status
        .as_ref()
        .map(|c| c.display())
        .unwrap_or_else(|| "-".to_string());
    let changes_display = format!("{:<CHANGES_WIDTH$}", changes_str);
    let changes_color = if worktree
        .change_status
        .as_ref()
        .is_some_and(|c| c.is_clean())
    {
        "\x1b[32m" // Green
    } else {
        "\x1b[33m" // Yellow
    };

    // パス短縮
    let path_str = worktree.path.display().to_string();
    let short_path = if let Some(suffix) = path_str.strip_prefix(base_path) {
        let suffix = suffix.trim_start_matches('/');
        format!("${{B}}/{}", suffix)
    } else {
        path_str
    };
    let path = truncate_start(&short_path, widths.path);

    // ACTIVITY表示
    let activity = worktree.last_activity.as_deref().unwrap_or("-");
    let activity_display = format!("{:<ACTIVITY_WIDTH$}", activity);

    // ブランチの色分け
    let branch_display = format!("{}{}\x1b[0m", status.ansi_bold_color(), branch);

    println!(
        "{}{}\x1b[0m {} {}{}\x1b[0m {}{}\x1b[0m \x1b[90m{}\x1b[0m \x1b[90m{}\x1b[0m",
        status.ansi_color(),
        status.bracketed_icon(),
        branch_display,
        sync_color,
        sync_display,
        changes_color,
        changes_display,
        path,
        activity_display,
    );
}

/// コンパクト表示(従来レイアウト)
fn run_list_compact() -> Result<()> {
    let config = load_config();
    let worktrees = get_worktrees()?;

    if worktrees.is_empty() {
        print_empty_worktrees_message();
        return Ok(());
    }

    // ターミナル幅を取得
    let (width, _) = crossterm::terminal::size().unwrap_or(DEFAULT_TERMINAL_SIZE);

    // 列幅計算
    let items: Vec<(String, String)> = worktrees
        .iter()
        .map(|w| (w.display_branch().to_string(), w.path.display().to_string()))
        .collect();
    let column_widths = calculate_column_widths(&items, width);

    // HEAD列のヘッダー幅
    const HEAD_HEADER_WIDTH: usize = 10;

    print_list_header(worktrees.len(), &config.worktree_base_path);

    // チルダ展開されたベースパス(パス比較用)
    let expanded_base_path = config
        .expanded_worktree_base_path()
        .map(|p| p.display().to_string())
        .unwrap_or_default();

    // テーブルヘッダー
    println!(
        "\x1b[1;36m   {:<branch$} {:<path$} {:<HEAD_HEADER_WIDTH$}\x1b[0m",
        "BRANCH",
        "DIR_PATH",
        "HEAD",
        branch = column_widths.branch,
        path = column_widths.path,
    );
    println!(
        "\x1b[90m   {} {} {:<HEAD_HEADER_WIDTH$}\x1b[0m",
        "".repeat(column_widths.branch),
        "".repeat(column_widths.path),
        "══════════",
    );

    // データ行
    for worktree in &worktrees {
        print_worktree_row_compact(worktree, &expanded_base_path, &column_widths);
    }

    println!();

    // 凡例
    println!("\x1b[90m{STATUS_LEGEND}\x1b[0m");
    println!(
        "\x1b[90mUse \x1b[36mgwm go [query]\x1b[90m to navigate, \x1b[36mgwm remove\x1b[90m to delete\x1b[0m"
    );

    Ok(())
}

/// コンパクトレイアウトで1行出力
fn print_worktree_row_compact(worktree: &Worktree, base_path: &str, widths: &ColumnWidths) {
    let status = &worktree.status;
    // ブランチ名は末尾を切り詰める(先頭のプレフィックスが重要なため)
    let branch = truncate_and_pad(worktree.display_branch(), widths.branch);

    // パス短縮
    let path_str = worktree.path.display().to_string();
    let short_path = if let Some(suffix) = path_str.strip_prefix(base_path) {
        let suffix = suffix.trim_start_matches('/');
        format!("${{B}}/{}", suffix)
    } else {
        path_str
    };
    let path = truncate_start(&short_path, widths.path);

    let head = worktree.short_head();

    // ブランチの色分け(アクティブの場合は太字)
    let branch_display = format!("{}{}\x1b[0m", status.ansi_bold_color(), branch);

    println!(
        "{}{}\x1b[0m {} \x1b[90m{}\x1b[0m \x1b[36m{}\x1b[0m",
        status.ansi_color(),
        status.bracketed_icon(),
        branch_display,
        path,
        head,
    );
}

/// JSON出力
fn run_list_json() -> Result<()> {
    let worktrees = get_worktrees_with_details()?;

    let json_data: Vec<WorktreeJson> = worktrees
        .iter()
        .map(|w| WorktreeJson {
            branch: w.display_branch().to_string(),
            path: w.path.display().to_string(),
            status: w.status.label().to_lowercase(),
            head: w.head.clone(),
            sync: w.sync_status.as_ref().map(|s| SyncJson {
                ahead: s.ahead,
                behind: s.behind,
            }),
            changes: w.change_status.as_ref().map(|c| ChangesJson {
                modified: c.modified,
                added: c.added,
                deleted: c.deleted,
                untracked: c.untracked,
            }),
            last_activity: w.last_activity.clone(),
        })
        .collect();

    println!("{}", serde_json::to_string_pretty(&json_data)?);

    Ok(())
}

/// ブランチ名のみ出力(シェル補完用)
///
/// 各行にブランチ名を1つずつ出力します。
/// シェル補完スクリプトから呼び出されることを想定しています。
fn run_list_names() -> Result<()> {
    let worktrees = get_worktrees()?;

    for worktree in &worktrees {
        println!("{}", worktree.display_branch());
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_sync_json_construction() {
        let sync = SyncJson {
            ahead: 5,
            behind: 3,
        };
        assert_eq!(sync.ahead, 5);
        assert_eq!(sync.behind, 3);
    }

    #[test]
    fn test_changes_json_construction() {
        let changes = ChangesJson {
            modified: 1,
            added: 2,
            deleted: 3,
            untracked: 4,
        };
        assert_eq!(changes.modified, 1);
        assert_eq!(changes.added, 2);
        assert_eq!(changes.deleted, 3);
        assert_eq!(changes.untracked, 4);
    }

    #[test]
    fn test_worktree_json_serialization() {
        let json = WorktreeJson {
            branch: "feature/test".to_string(),
            path: "/path/to/worktree".to_string(),
            status: "other".to_string(),
            head: "abc1234".to_string(),
            sync: Some(SyncJson {
                ahead: 2,
                behind: 1,
            }),
            changes: Some(ChangesJson {
                modified: 3,
                added: 1,
                deleted: 0,
                untracked: 2,
            }),
            last_activity: Some("2d ago".to_string()),
        };
        let serialized = serde_json::to_string(&json).unwrap();
        assert!(serialized.contains("feature/test"));
        assert!(serialized.contains("ahead"));
    }

    #[test]
    fn test_worktree_json_skip_serializing_none() {
        let json = WorktreeJson {
            branch: "main".to_string(),
            path: "/path".to_string(),
            status: "main".to_string(),
            head: "def5678".to_string(),
            sync: None,
            changes: None,
            last_activity: None,
        };
        let serialized = serde_json::to_string(&json).unwrap();
        assert!(!serialized.contains("sync"));
        assert!(!serialized.contains("changes"));
        assert!(!serialized.contains("last_activity"));
    }

    #[test]
    fn test_default_terminal_size() {
        assert_eq!(DEFAULT_TERMINAL_SIZE, (120, 24));
    }

    #[test]
    fn test_column_width_constants() {
        assert_eq!(SYNC_WIDTH, 8);
        assert_eq!(CHANGES_WIDTH, 10);
        assert_eq!(ACTIVITY_WIDTH, 10);
    }

    #[test]
    fn test_worktree_json_all_fields() {
        let json = WorktreeJson {
            branch: "feature/x".to_string(),
            path: "/p".to_string(),
            status: "other".to_string(),
            head: "1234567".to_string(),
            sync: Some(SyncJson {
                ahead: 0,
                behind: 0,
            }),
            changes: Some(ChangesJson {
                modified: 0,
                added: 0,
                deleted: 0,
                untracked: 0,
            }),
            last_activity: Some("just now".to_string()),
        };
        let serialized = serde_json::to_string(&json).unwrap();
        assert!(serialized.contains("\"ahead\":0"));
        assert!(serialized.contains("\"modified\":0"));
    }

    #[test]
    fn test_sync_json_zero_values() {
        let sync = SyncJson {
            ahead: 0,
            behind: 0,
        };
        assert_eq!(sync.ahead, 0);
        assert_eq!(sync.behind, 0);
    }
}