vkit 0.1.4

Fast Rust dev CLI: manage git worktrees, Node ports, run scripts, install & sync VS Code / Cursor extensions.
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
//! 通过调用系统 `git` 完成 worktree / 分支操作。

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};

use anyhow::{anyhow, bail, Context, Result};

use super::placement::{self, Placement};

/// HEAD 最近一次 commit 的摘要(对齐 Worktrunk Commit / Age / Message)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommitInfo {
    pub short: String,
    pub subject: String,
    /// committer unix 时间戳。
    pub committed_at: i64,
}

impl CommitInfo {
    /// 相对时间:`12s` / `5m` / `3h` / `2d` / `1mo`。
    pub fn age_label(&self) -> String {
        format_age(self.committed_at)
    }
}

/// 一条登记的 worktree(含 Main)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeEntry {
    pub path: PathBuf,
    pub head: String,
    /// 本地分支短名;detached 时为 `None`。
    pub branch: Option<String>,
    pub is_main: bool,
    /// Main 为 `None`;附加树按其路径分类,非约定 Placement 在加载时已过滤。
    pub placement: Option<Placement>,
    pub dirty: bool,
    /// 相对 Main 分支领先 / 落后 commit 数;无法解析基准为 `None`。
    pub ahead: Option<u32>,
    pub behind: Option<u32>,
    /// 关联 MR;无则为 `None`。merged/closed 也保留,便于发现可清理的树。
    pub mr: Option<super::mr::MrRef>,
    /// 最近一次 commit;enrich 前为 `None`。
    pub commit: Option<CommitInfo>,
}

/// 仓库上下文:Main 路径、仓库名、配置后的 global root。
#[derive(Debug, Clone)]
pub struct RepoContext {
    pub main_path: PathBuf,
    pub repo_name: String,
    pub global_root: PathBuf,
}

impl RepoContext {
    pub fn discover(cwd: &Path, global_root: PathBuf) -> Result<Self> {
        let main_path = main_worktree_path(cwd)?;
        let repo_name = main_path
            .file_name()
            .and_then(|s| s.to_str())
            .ok_or_else(|| anyhow!("无法解析仓库目录名"))?
            .to_string();
        Ok(Self {
            main_path,
            repo_name,
            global_root,
        })
    }

    /// 仅 `git worktree list` + Placement 过滤,不跑 status / glab(启动用)。
    pub fn list_managed_fast(&self) -> Result<Vec<WorktreeEntry>> {
        let raw = list_porcelain(&self.main_path)?;
        let mut out = Vec::new();
        for mut entry in raw {
            entry.is_main = paths_equal(&entry.path, &self.main_path);
            if entry.is_main {
                entry.placement = None;
                out.push(entry);
                continue;
            }
            if let Some(p) = placement::classify(
                &entry.path,
                &self.main_path,
                &self.global_root,
                &self.repo_name,
            ) {
                entry.placement = Some(p);
                out.push(entry);
            }
        }
        out.sort_by(|a, b| match (a.is_main, b.is_main) {
            (true, false) => std::cmp::Ordering::Less,
            (false, true) => std::cmp::Ordering::Greater,
            _ => a.path.cmp(&b.path),
        });
        Ok(out)
    }

    /// 并行补齐 dirty / 相对 Main 的 ahead-behind(可在后台线程调用)。
    pub fn enrich_status(&self, entries: &mut [WorktreeEntry]) {
        let base = divergence_base(&self.main_path, entries);
        // 限制并发,减轻对共享 pack/commit-graph 的 mmap 争用(对齐 worktrunk 思路)。
        const PARALLEL: usize = 4;
        let mut start = 0;
        while start < entries.len() {
            let end = (start + PARALLEL).min(entries.len());
            let chunk = &mut entries[start..end];
            std::thread::scope(|scope| {
                for entry in chunk.iter_mut() {
                    let base = base.clone();
                    scope.spawn(move || {
                        let _ = enrich_local(entry, base.as_deref());
                    });
                }
            });
            start = end;
        }
    }

    /// 批量补齐各 HEAD 的短 hash / 时间 / subject(一次 `git log --no-walk`)。
    pub fn enrich_commits(&self, entries: &mut [WorktreeEntry]) {
        let mut shas: Vec<String> = entries
            .iter()
            .map(|e| e.head.clone())
            .filter(|h| !h.is_empty())
            .collect();
        shas.sort();
        shas.dedup();
        let map = commit_details_many(&self.main_path, &shas);
        for entry in entries.iter_mut() {
            if let Some(info) = map.get(&entry.head) {
                entry.commit = Some(info.clone());
            }
        }
    }
}

fn enrich_local(entry: &mut WorktreeEntry, base: Option<&str>) -> Result<()> {
    entry.dirty = is_dirty(&entry.path)?;
    if let Some(base) = base {
        if let Some((ahead, behind)) = ahead_behind(&entry.path, base) {
            entry.ahead = Some(ahead);
            entry.behind = Some(behind);
        }
    }
    Ok(())
}

/// 对齐 Worktrunk:一次 `git log --no-walk` 批量取 tip commit 详情。
///
/// 返回 `full_sha → CommitInfo`。失败返回空 map。
pub fn commit_details_many(cwd: &Path, shas: &[String]) -> HashMap<String, CommitInfo> {
    if shas.is_empty() {
        return HashMap::new();
    }
    let mut args: Vec<String> = vec![
        "log".into(),
        "--no-walk".into(),
        "--no-show-signature".into(),
        "--format=%H%x00%h%x00%ct%x00%s".into(),
    ];
    args.extend(shas.iter().cloned());
    let Ok(out) = git_in_owned(cwd, &args) else {
        return HashMap::new();
    };
    parse_commit_details(&out)
}

/// 最近一次 commit 的 `--stat` 摘要(文件列表 + shortstat),供详情卡展示。
pub fn commit_stat(cwd: &Path, sha: &str) -> Result<String> {
    if sha.is_empty() {
        bail!("空 commit SHA");
    }
    let out = git_in(
        cwd,
        &["show", "--stat", "--format=", "--no-color", "--no-ext-diff", sha],
    )?;
    Ok(out.trim_end().to_string())
}

/// 最近一次 commit 的统一 diff 正文(无 commit message),供 Diff 视图。
pub fn commit_patch(cwd: &Path, sha: &str) -> Result<String> {
    if sha.is_empty() {
        bail!("空 commit SHA");
    }
    let out = git_in(
        cwd,
        &[
            "show",
            "--format=",
            "--no-color",
            "--no-ext-diff",
            "-U3",
            sha,
        ],
    )?;
    Ok(out.trim_end().to_string())
}

fn parse_commit_details(out: &str) -> HashMap<String, CommitInfo> {
    let mut map = HashMap::new();
    for line in out.lines() {
        let mut parts = line.split('\0');
        let Some(full) = parts.next().filter(|s| !s.is_empty()) else {
            continue;
        };
        let Some(short) = parts.next() else {
            continue;
        };
        let Some(ct) = parts.next().and_then(|s| s.parse::<i64>().ok()) else {
            continue;
        };
        let subject = parts.next().unwrap_or("").to_string();
        map.insert(
            full.to_string(),
            CommitInfo {
                short: short.to_string(),
                subject,
                committed_at: ct,
            },
        );
    }
    map
}

fn format_age(committed_at: i64) -> String {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(committed_at);
    let secs = (now - committed_at).max(0);
    if secs < 60 {
        format!("{secs}s")
    } else if secs < 3600 {
        format!("{}m", secs / 60)
    } else if secs < 86_400 {
        format!("{}h", secs / 3600)
    } else if secs < 86_400 * 30 {
        format!("{}d", secs / 86_400)
    } else {
        format!("{}mo", secs / (86_400 * 30))
    }
}

/// STATUS 基准:优先 Main 当前分支,否则 origin/HEAD → main → master。
fn divergence_base(main_path: &Path, entries: &[WorktreeEntry]) -> Option<String> {
    if let Some(branch) = entries.iter().find(|e| e.is_main).and_then(|e| e.branch.clone()) {
        return Some(branch);
    }
    if let Ok(b) = git_in(main_path, &["rev-parse", "--abbrev-ref", "HEAD"]) {
        let b = b.trim();
        if !b.is_empty() && b != "HEAD" {
            return Some(b.to_string());
        }
    }
    if let Ok(sym) = git_in(
        main_path,
        &["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
    ) {
        // 如 `origin/main` → 用本地 `main`(若存在),否则保留 remote-tracking。
        let sym = sym.trim();
        if let Some(short) = sym.strip_prefix("origin/") {
            if rev_exists(main_path, short) {
                return Some(short.to_string());
            }
            return Some(sym.to_string());
        }
        if !sym.is_empty() {
            return Some(sym.to_string());
        }
    }
    for candidate in ["main", "master"] {
        if rev_exists(main_path, candidate) {
            return Some(candidate.to_string());
        }
    }
    None
}

fn rev_exists(cwd: &Path, rev: &str) -> bool {
    git_in(cwd, &["rev-parse", "--verify", "--quiet", rev]).is_ok()
}

/// `git rev-list --left-right --count <base>...HEAD` → (ahead, behind),相对 Main。
fn ahead_behind(worktree: &Path, base: &str) -> Option<(u32, u32)> {
    let range = format!("{base}...HEAD");
    let out = git_in(
        worktree,
        &["rev-list", "--left-right", "--count", &range],
    )
    .ok()?;
    let mut parts = out.split_whitespace();
    // 输出:`<behind>\t<ahead>`(left=base, right=HEAD)
    let behind = parts.next()?.parse().ok()?;
    let ahead = parts.next()?.parse().ok()?;
    Some((ahead, behind))
}

/// 自 cwd 解析 git-common-dir 绝对路径。
pub fn git_common_dir(cwd: &Path) -> Result<PathBuf> {
    let out = git_in(cwd, &["rev-parse", "--path-format=absolute", "--git-common-dir"])?;
    Ok(PathBuf::from(out.trim()))
}

/// 自 cwd 解析 Main Worktree 绝对路径。
pub fn main_worktree_path(cwd: &Path) -> Result<PathBuf> {
    let common = git_common_dir(cwd)?;
    // common-dir 通常是 `<main>/.git` 或 bare 的 git dir;附加 worktree 的 common 仍指向主仓 .git。
    let main = if common.file_name().and_then(|s| s.to_str()) == Some(".git") {
        common
            .parent()
            .ok_or_else(|| anyhow!("无法从 git-common-dir 推导 Main Worktree"))?
            .to_path_buf()
    } else {
        // bare 或不标准布局:退回 `git worktree list` 第一条。
        list_porcelain(cwd)?
            .into_iter()
            .next()
            .map(|e| e.path)
            .ok_or_else(|| anyhow!("当前不在 git 仓库内"))?
    };
    Ok(main)
}

/// 所有登记的 worktree(不过滤 Placement),用于 switch 查找。
pub fn list_all(cwd: &Path) -> Result<Vec<WorktreeEntry>> {
    list_porcelain(cwd)
}

/// 按分支名查找工作树路径(任一 Placement)。
pub fn worktree_for_branch(cwd: &Path, branch: &str) -> Result<Option<PathBuf>> {
    Ok(list_all(cwd)?
        .into_iter()
        .find(|e| e.branch.as_deref() == Some(branch))
        .map(|e| e.path))
}

/// 当前 worktree 路径(`git rev-parse --show-toplevel`)。
pub fn current_toplevel(cwd: &Path) -> Result<PathBuf> {
    let out = git_in(cwd, &["rev-parse", "--path-format=absolute", "--show-toplevel"])?;
    Ok(PathBuf::from(out.trim()))
}

pub fn list_local_branches(cwd: &Path) -> Result<Vec<String>> {
    let out = git_in(cwd, &["branch", "--format=%(refname:short)"])?;
    Ok(nonempty_lines(&out))
}

pub fn list_remote_branches(cwd: &Path) -> Result<Vec<String>> {
    let out = git_in(cwd, &["branch", "-r", "--format=%(refname:short)"])?;
    Ok(nonempty_lines(&out)
        .into_iter()
        .filter(|b| !b.ends_with("/HEAD"))
        .collect())
}

/// 探测默认主分支短名(main / master / 远程 HEAD)。
pub fn default_base_branch(cwd: &Path) -> Result<String> {
    if let Ok(out) = git_in(cwd, &["symbolic-ref", "refs/remotes/origin/HEAD"]) {
        // refs/remotes/origin/main → main
        if let Some(name) = out.trim().rsplit('/').next() {
            if !name.is_empty() {
                return Ok(name.to_string());
            }
        }
    }
    for candidate in ["main", "master"] {
        if git_in(cwd, &["show-ref", "--verify", "--quiet", &format!("refs/heads/{candidate}")])
            .is_ok()
        {
            return Ok(candidate.to_string());
        }
    }
    // 当前分支兜底。
    let cur = git_in(cwd, &["branch", "--show-current"])?;
    let cur = cur.trim();
    if cur.is_empty() {
        bail!("无法探测默认主分支");
    }
    Ok(cur.to_string())
}

pub fn is_dirty(worktree: &Path) -> Result<bool> {
    let out = git_in(worktree, &["status", "--porcelain"])?;
    Ok(!out.trim().is_empty())
}

/// 本地分支是否已合并进 `into`。
pub fn is_merged_into(cwd: &Path, branch: &str, into: &str) -> Result<bool> {
    // `git merge-base --is-ancestor branch into`
    match Command::new("git")
        .args(["merge-base", "--is-ancestor", branch, into])
        .current_dir(cwd)
        .status()
    {
        Ok(status) if status.success() => Ok(true),
        Ok(_) => Ok(false),
        Err(err) => Err(err).context("检查分支合并状态失败"),
    }
}

pub struct AddNewBranch {
    pub path: PathBuf,
    pub branch: String,
    pub base: String,
}

pub struct AddExistingBranch {
    pub path: PathBuf,
    /// 本地分支名;若来自远程则为将要创建的本地名。
    pub branch: String,
    /// 若从远程创建,为 `origin/foo` 这类;本地已有则为 `None`。
    pub start_point: Option<String>,
}

pub fn add_new_branch(cwd: &Path, opts: &AddNewBranch) -> Result<()> {
    if let Some(parent) = opts.path.parent() {
        fs_create_dir_all(parent)?;
    }
    git_in(
        cwd,
        &[
            "worktree",
            "add",
            "-b",
            &opts.branch,
            opts.path.to_str().ok_or_else(|| anyhow!("路径含非法 UTF-8"))?,
            &opts.base,
        ],
    )?;
    Ok(())
}

pub fn add_existing_branch(cwd: &Path, opts: &AddExistingBranch) -> Result<()> {
    if let Some(parent) = opts.path.parent() {
        fs_create_dir_all(parent)?;
    }
    let path = opts
        .path
        .to_str()
        .ok_or_else(|| anyhow!("路径含非法 UTF-8"))?;
    match &opts.start_point {
        Some(start) => {
            git_in(
                cwd,
                &[
                    "worktree",
                    "add",
                    "--track",
                    "-b",
                    &opts.branch,
                    path,
                    start,
                ],
            )?;
        }
        None => {
            git_in(cwd, &["worktree", "add", path, &opts.branch])?;
        }
    }
    Ok(())
}

/// Remove:去掉工作树,保留分支。脏目录时 `force`。
///
/// 快路径(对齐 Worktrunk):同盘 `rename` 到 `$GIT_COMMON_DIR/wt/trash/`(瞬时),
/// 立刻清 git 元数据,目录内容后台 `rm`;跨盘或失败则回退 `git worktree remove`。
pub fn remove_worktree(cwd: &Path, path: &Path, force: bool) -> Result<()> {
    if path.exists() {
        if let Ok(()) = remove_worktree_fast(cwd, path) {
            return Ok(());
        }
    } else {
        // 目录已无:只清登记信息。
        let _ = git_in(cwd, &["worktree", "prune"]);
        return Ok(());
    }
    remove_worktree_git(cwd, path, force)
}

fn remove_worktree_git(cwd: &Path, path: &Path, force: bool) -> Result<()> {
    let path_s = path
        .to_str()
        .ok_or_else(|| anyhow!("路径含非法 UTF-8"))?;
    let mut args = vec!["worktree", "remove"];
    if force {
        args.push("--force");
    }
    args.push(path_s);
    git_in(cwd, &args)?;
    Ok(())
}

fn remove_worktree_fast(cwd: &Path, path: &Path) -> Result<()> {
    let common = git_common_dir(cwd)?;
    let trash_root = common.join("wt").join("trash");
    fs::create_dir_all(&trash_root)
        .with_context(|| format!("创建 trash 失败:{}", trash_root.display()))?;

    let base = path
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("worktree");
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis())
        .unwrap_or(0);
    let staged = trash_root.join(format!("{stamp}-{base}"));

    // 同文件系统 rename 接近瞬时;跨盘会失败并走 git 回退。
    fs::rename(path, &staged)
        .with_context(|| format!("移入 trash 失败:{}{}", path.display(), staged.display()))?;

    // 优先按 .git 文件删掉 admin(含 locked);再 prune 兜底。
    if let Ok(admin) = linked_worktree_admin(&staged) {
        let _ = fs::remove_dir_all(admin);
    }
    let _ = git_in(cwd, &["worktree", "prune"]);

    spawn_dir_cleanup(staged);
    sweep_stale_trash(&trash_root);
    Ok(())
}

/// 解析 linked worktree 的 `$GIT_COMMON_DIR/worktrees/<id>`。
fn linked_worktree_admin(worktree_path: &Path) -> Result<PathBuf> {
    let gitfile = worktree_path.join(".git");
    let content = fs::read_to_string(&gitfile)
        .with_context(|| format!("读取 {} 失败", gitfile.display()))?;
    for line in content.lines() {
        if let Some(rest) = line.strip_prefix("gitdir:") {
            let admin = PathBuf::from(rest.trim());
            if admin.is_absolute() {
                return Ok(admin);
            }
            return Ok(worktree_path.join(admin));
        }
    }
    bail!(".git 文件中无 gitdir")
}

fn spawn_dir_cleanup(path: PathBuf) {
    thread::spawn(move || {
        let _ = fs::remove_dir_all(&path);
    });
}

/// 清掉超过 24h 的 trash 残留(上次删除被打断时)。
fn sweep_stale_trash(trash_root: &Path) {
    let Ok(entries) = fs::read_dir(trash_root) else {
        return;
    };
    let now = SystemTime::now();
    for entry in entries.flatten() {
        let path = entry.path();
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        let Ok(modified) = meta.modified() else {
            continue;
        };
        let Ok(age) = now.duration_since(modified) else {
            continue;
        };
        if age.as_secs() >= 24 * 3600 {
            spawn_dir_cleanup(path);
        }
    }
}

/// 删除本地分支;`force` 时用 `-D`。
pub fn delete_branch(cwd: &Path, branch: &str, force: bool) -> Result<()> {
    let flag = if force { "-D" } else { "-d" };
    git_in(cwd, &["branch", flag, branch])?;
    Ok(())
}

fn list_porcelain(cwd: &Path) -> Result<Vec<WorktreeEntry>> {
    let out = git_in(cwd, &["worktree", "list", "--porcelain"])?;
    parse_porcelain(&out)
}

/// 解析 `git worktree list --porcelain`(纯函数,便于单测)。
pub fn parse_porcelain(out: &str) -> Result<Vec<WorktreeEntry>> {
    let mut entries = Vec::new();
    let mut path: Option<PathBuf> = None;
    let mut head = String::new();
    let mut branch: Option<String> = None;

    let push = |entries: &mut Vec<WorktreeEntry>,
                path: &mut Option<PathBuf>,
                head: &mut String,
                branch: &mut Option<String>| {
        if let Some(p) = path.take() {
            entries.push(WorktreeEntry {
                path: p,
                head: std::mem::take(head),
                branch: branch.take(),
                is_main: false,
                placement: None,
                dirty: false,
                ahead: None,
                behind: None,
                mr: None,
                commit: None,
            });
        }
    };

    for line in out.lines() {
        if line.is_empty() {
            push(&mut entries, &mut path, &mut head, &mut branch);
            continue;
        }
        if let Some(rest) = line.strip_prefix("worktree ") {
            push(&mut entries, &mut path, &mut head, &mut branch);
            path = Some(PathBuf::from(rest));
        } else if let Some(rest) = line.strip_prefix("HEAD ") {
            head = rest.to_string();
        } else if let Some(rest) = line.strip_prefix("branch ") {
            branch = Some(
                rest.strip_prefix("refs/heads/")
                    .unwrap_or(rest)
                    .to_string(),
            );
        } else if line == "detached" {
            branch = None;
        }
    }
    push(&mut entries, &mut path, &mut head, &mut branch);
    Ok(entries)
}

fn git_in(cwd: &Path, args: &[&str]) -> Result<String> {
    let owned: Vec<String> = args.iter().map(|s| (*s).to_string()).collect();
    git_in_owned(cwd, &owned)
}

fn git_in_owned(cwd: &Path, args: &[String]) -> Result<String> {
    let output = Command::new("git")
        .args(args)
        .current_dir(cwd)
        .output()
        .with_context(|| format!("执行 git {} 失败", args.join(" ")))?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("git {} 失败:{}", args.join(" "), stderr.trim());
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

fn nonempty_lines(s: &str) -> Vec<String> {
    s.lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .map(str::to_string)
        .collect()
}

fn paths_equal(a: &Path, b: &Path) -> bool {
    a == b
}

fn fs_create_dir_all(path: &Path) -> Result<()> {
    std::fs::create_dir_all(path).with_context(|| format!("创建目录失败:{}", path.display()))
}

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

    #[test]
    fn parses_porcelain_main_and_linked() {
        let raw = "\
worktree /proj/repo
HEAD abc
branch refs/heads/main

worktree /proj/repo/.worktrees/feat-x
HEAD def
branch refs/heads/feat/x

worktree /proj/repo/.worktrees/detached-one
HEAD ghi
detached
";
        let entries = parse_porcelain(raw).unwrap();
        assert_eq!(entries.len(), 3);
        assert_eq!(entries[0].path, PathBuf::from("/proj/repo"));
        assert_eq!(entries[0].branch.as_deref(), Some("main"));
        assert_eq!(entries[1].branch.as_deref(), Some("feat/x"));
        assert_eq!(entries[2].branch, None);
    }

    #[test]
    fn parses_commit_details_batch() {
        let raw = "\
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\x00aaaaaaa\x001700000000\x00Initial commit
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\x00bbbbbbb\x001700000100\x00Add feature
";
        let map = parse_commit_details(raw);
        assert_eq!(map.len(), 2);
        let a = &map["aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"];
        assert_eq!(a.short, "aaaaaaa");
        assert_eq!(a.subject, "Initial commit");
        assert_eq!(a.committed_at, 1_700_000_000);
    }
}