wtui 0.1.4

A terminal UI and CLI for managing Git worktrees across repositories
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
use std::collections::HashMap;
use std::ffi::OsString;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use thiserror::Error;

use crate::model::{
    Catalog, RepositoryConfig, RepositoryDiscovery, RepositoryIdentity, Worktree, WorktreeStatus,
};

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CommandOutput {
    pub stdout: Vec<u8>,
    pub stderr: Vec<u8>,
    pub success: bool,
}

pub trait GitRunner {
    fn run(&self, directory: &Path, arguments: &[OsString]) -> Result<CommandOutput, GitError>;
}

#[derive(Clone, Copy, Debug, Default)]
pub struct SystemGit;

impl GitRunner for SystemGit {
    fn run(&self, directory: &Path, arguments: &[OsString]) -> Result<CommandOutput, GitError> {
        let output = Command::new("git")
            .arg("-C")
            .arg(directory)
            .args(arguments)
            .output()
            .map_err(|source| GitError::Launch { source })?;
        Ok(CommandOutput {
            stdout: output.stdout,
            stderr: output.stderr,
            success: output.status.success(),
        })
    }
}

#[derive(Debug, Error)]
pub enum GitError {
    #[error("failed to launch Git: {source}")]
    Launch { source: std::io::Error },
    #[error("Git command failed: {message}")]
    Command { message: String },
    #[error("Git returned a non-path value for {field}")]
    InvalidPath { field: &'static str },
    #[error("cannot canonicalize {path}: {source}")]
    Canonicalize {
        path: PathBuf,
        source: std::io::Error,
    },
    #[error("malformed worktree porcelain: {0}")]
    MalformedPorcelain(String),
    #[error("malformed status porcelain: {0}")]
    MalformedStatus(String),
}

pub fn resolve_repository(
    runner: &dyn GitRunner,
    path: &Path,
) -> Result<RepositoryIdentity, GitError> {
    let common_output = run_checked(
        runner,
        path,
        &["rev-parse", "--path-format=absolute", "--git-common-dir"],
    )?;
    let common_path = bytes_to_path(trim_ascii_line_end(&common_output), "Git common directory")?;
    let common_git_dir =
        fs::canonicalize(&common_path).map_err(|source| GitError::Canonicalize {
            path: common_path,
            source,
        })?;

    let worktrees = discover_worktrees(runner, path)?;
    let header = worktrees.first().ok_or_else(|| {
        GitError::MalformedPorcelain("Git reported no repository anchor".to_owned())
    })?;
    let anchor = fs::canonicalize(&header.path).map_err(|source| GitError::Canonicalize {
        path: header.path.clone(),
        source,
    })?;
    Ok(RepositoryIdentity {
        anchor,
        common_git_dir,
        bare: header.bare,
    })
}

pub fn discover_worktrees(
    runner: &dyn GitRunner,
    anchor: &Path,
) -> Result<Vec<Worktree>, GitError> {
    let output = run_checked(runner, anchor, &["worktree", "list", "--porcelain", "-z"])?;
    parse_worktree_porcelain(&output)
}

pub fn discover_catalog(runner: &dyn GitRunner, catalog: &Catalog) -> Vec<RepositoryDiscovery> {
    catalog
        .repositories
        .iter()
        .cloned()
        .map(|repository| {
            let result =
                discover_worktrees(runner, &repository.path).map_err(|error| error.to_string());
            RepositoryDiscovery { repository, result }
        })
        .collect()
}

pub fn infer_worktree_parents(
    runner: &dyn GitRunner,
    repository: &RepositoryConfig,
    worktrees: &[Worktree],
) -> Result<HashMap<PathBuf, PathBuf>, GitError> {
    let branches = worktrees
        .iter()
        .filter(|worktree| worktree.navigable() && worktree.branch.is_some())
        .filter_map(|worktree| {
            worktree
                .head
                .as_deref()
                .map(|head| (worktree.path.clone(), head))
        })
        .collect::<Vec<_>>();
    let mut parents = HashMap::new();
    for (child_path, child_head) in &branches {
        let mut candidates = Vec::new();
        for (parent_path, parent_head) in &branches {
            if parent_path == child_path || parent_head == child_head {
                continue;
            }
            if !git_succeeds(
                runner,
                &repository.path,
                &[
                    OsString::from("merge-base"),
                    OsString::from("--is-ancestor"),
                    OsString::from(parent_head),
                    OsString::from(child_head),
                ],
            )? {
                continue;
            }
            let range = format!("{parent_head}..{child_head}");
            let count = run_git(
                runner,
                &repository.path,
                &[
                    OsString::from("rev-list"),
                    OsString::from("--count"),
                    OsString::from(range),
                ],
            )?;
            let Ok(distance) = String::from_utf8_lossy(&count).trim().parse::<u64>() else {
                continue;
            };
            candidates.push((distance, parent_path.clone()));
        }
        candidates.sort();
        if let Some((distance, parent)) = candidates.first()
            && candidates
                .get(1)
                .is_none_or(|candidate| candidate.0 != *distance)
        {
            parents.insert(child_path.clone(), parent.clone());
        }
    }
    Ok(parents)
}

pub fn canonical_common_dir(
    runner: &dyn GitRunner,
    repository: &RepositoryConfig,
) -> Result<PathBuf, GitError> {
    resolve_repository(runner, &repository.path).map(|identity| identity.common_git_dir)
}

fn run_checked(
    runner: &dyn GitRunner,
    directory: &Path,
    arguments: &[&str],
) -> Result<Vec<u8>, GitError> {
    let arguments: Vec<OsString> = arguments.iter().map(OsString::from).collect();
    let output = runner.run(directory, &arguments)?;
    if output.success {
        return Ok(output.stdout);
    }
    let message = String::from_utf8_lossy(&output.stderr).trim().to_owned();
    Err(GitError::Command {
        message: if message.is_empty() {
            "unknown Git error".to_owned()
        } else {
            message
        },
    })
}

pub fn run_git(
    runner: &dyn GitRunner,
    directory: &Path,
    arguments: &[OsString],
) -> Result<Vec<u8>, GitError> {
    Ok(run_git_output(runner, directory, arguments)?.stdout)
}

pub fn run_git_output(
    runner: &dyn GitRunner,
    directory: &Path,
    arguments: &[OsString],
) -> Result<CommandOutput, GitError> {
    let output = runner.run(directory, arguments)?;
    if output.success {
        return Ok(output);
    }
    let message = String::from_utf8_lossy(&output.stderr).trim().to_owned();
    Err(GitError::Command {
        message: if message.is_empty() {
            "unknown Git error".to_owned()
        } else {
            message
        },
    })
}

pub fn git_succeeds(
    runner: &dyn GitRunner,
    directory: &Path,
    arguments: &[OsString],
) -> Result<bool, GitError> {
    Ok(runner.run(directory, arguments)?.success)
}

pub fn status(runner: &dyn GitRunner, worktree: &Path) -> Result<WorktreeStatus, GitError> {
    let output = run_git(
        runner,
        worktree,
        &[
            OsString::from("status"),
            OsString::from("--porcelain=v2"),
            OsString::from("--branch"),
            OsString::from("-z"),
        ],
    )?;
    parse_status_porcelain(&output)
}

pub fn parse_status_porcelain(input: &[u8]) -> Result<WorktreeStatus, GitError> {
    let fields: Vec<&[u8]> = input.split(|byte| *byte == 0).collect();
    let mut status = WorktreeStatus::default();
    let mut index = 0;
    while index < fields.len() {
        let field = fields[index];
        index += 1;
        if field.is_empty() {
            continue;
        }
        if let Some(value) = field.strip_prefix(b"# branch.oid ") {
            if value != b"(initial)" {
                status.head = Some(lossy(value));
            }
            continue;
        }
        if let Some(value) = field.strip_prefix(b"# branch.head ") {
            if value != b"(detached)" {
                status.branch = Some(lossy(value));
            }
            continue;
        }
        if let Some(value) = field.strip_prefix(b"# branch.upstream ") {
            status.upstream = Some(lossy(value));
            continue;
        }
        if field.starts_with(b"# ") {
            // Git emits further headers (branch.ab, stash) that carry no data we track.
            continue;
        }
        match field.first().copied() {
            Some(b'1' | b'2' | b'u') => {
                if field.len() < 4 || field[1] != b' ' {
                    return Err(GitError::MalformedStatus(lossy(field)));
                }
                let x = field[2];
                let y = field[3];
                if x != b'.' {
                    status.staged += 1;
                }
                if y != b'.' {
                    status.unstaged += 1;
                }
                if field[0] == b'2' {
                    if index >= fields.len() || fields[index].is_empty() {
                        return Err(GitError::MalformedStatus(
                            "rename record lacks its original path".to_owned(),
                        ));
                    }
                    index += 1;
                }
            }
            Some(b'?') if field.get(1) == Some(&b' ') => status.untracked += 1,
            Some(b'!') if field.get(1) == Some(&b' ') => {}
            _ => return Err(GitError::MalformedStatus(lossy(field))),
        }
    }
    Ok(status)
}

pub fn parse_worktree_porcelain(input: &[u8]) -> Result<Vec<Worktree>, GitError> {
    if input.is_empty() {
        return Ok(Vec::new());
    }

    let mut worktrees = Vec::new();
    let mut current: Option<Worktree> = None;
    for field in input.split(|byte| *byte == 0) {
        if field.is_empty() {
            if let Some(worktree) = current.take() {
                worktrees.push(worktree);
            }
            continue;
        }
        let (key, value) = split_field(field);
        match key {
            b"worktree" => {
                if current.is_some() {
                    return Err(GitError::MalformedPorcelain(
                        "worktree record was not terminated".to_owned(),
                    ));
                }
                let path = bytes_to_path(value, "worktree path")?;
                current = Some(Worktree {
                    path,
                    head: None,
                    branch: None,
                    detached: false,
                    bare: false,
                    locked: None,
                    prunable: None,
                });
            }
            b"HEAD" => record_mut(&mut current, "HEAD")?.head = Some(lossy(value)),
            b"branch" => record_mut(&mut current, "branch")?.branch = Some(lossy(value)),
            b"detached" => record_mut(&mut current, "detached")?.detached = true,
            b"bare" => record_mut(&mut current, "bare")?.bare = true,
            b"locked" => record_mut(&mut current, "locked")?.locked = Some(lossy(value)),
            b"prunable" => record_mut(&mut current, "prunable")?.prunable = Some(lossy(value)),
            _ => {}
        }
    }
    if let Some(worktree) = current {
        worktrees.push(worktree);
    }
    Ok(worktrees)
}

fn record_mut<'a>(
    current: &'a mut Option<Worktree>,
    field: &str,
) -> Result<&'a mut Worktree, GitError> {
    current.as_mut().ok_or_else(|| {
        GitError::MalformedPorcelain(format!("{field} appeared before a worktree path"))
    })
}

fn split_field(field: &[u8]) -> (&[u8], &[u8]) {
    match field.iter().position(|byte| *byte == b' ') {
        Some(index) => (&field[..index], &field[index + 1..]),
        None => (field, &[]),
    }
}

fn trim_ascii_line_end(mut bytes: &[u8]) -> &[u8] {
    while matches!(bytes.last(), Some(b'\n' | b'\r')) {
        bytes = &bytes[..bytes.len() - 1];
    }
    bytes
}

fn lossy(bytes: &[u8]) -> String {
    String::from_utf8_lossy(bytes).into_owned()
}

#[cfg(unix)]
fn bytes_to_path(bytes: &[u8], field: &'static str) -> Result<PathBuf, GitError> {
    use std::os::unix::ffi::OsStringExt;
    if bytes.is_empty() {
        return Err(GitError::InvalidPath { field });
    }
    Ok(PathBuf::from(OsString::from_vec(bytes.to_vec())))
}

#[cfg(not(unix))]
fn bytes_to_path(bytes: &[u8], field: &'static str) -> Result<PathBuf, GitError> {
    if bytes.is_empty() {
        return Err(GitError::InvalidPath { field });
    }
    Ok(PathBuf::from(String::from_utf8_lossy(bytes).into_owned()))
}

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

    #[test]
    fn parses_all_worktree_states_and_spaces() {
        let input = b"worktree /tmp/main tree\0HEAD abc123\0branch refs/heads/main\0\0worktree /tmp/other\0HEAD def456\0detached\0locked maintenance window\0prunable gitdir file points to missing location\0\0";
        let parsed = parse_worktree_porcelain(input).unwrap();
        assert_eq!(parsed.len(), 2);
        assert_eq!(parsed[0].path, PathBuf::from("/tmp/main tree"));
        assert_eq!(parsed[0].branch.as_deref(), Some("refs/heads/main"));
        assert!(parsed[1].detached);
        assert_eq!(parsed[1].locked.as_deref(), Some("maintenance window"));
        assert!(parsed[1].prunable.is_some());
    }

    #[test]
    fn parses_bare_anchor() {
        let parsed = parse_worktree_porcelain(b"worktree /tmp/project.git\0bare\0\0").unwrap();
        assert!(parsed[0].bare);
        assert!(!parsed[0].navigable());
    }

    #[test]
    fn rejects_fields_outside_records() {
        let error = parse_worktree_porcelain(b"HEAD abc\0").unwrap_err();
        assert!(matches!(error, GitError::MalformedPorcelain(_)));
    }

    #[cfg(unix)]
    #[test]
    fn preserves_non_utf8_paths() {
        use std::os::unix::ffi::OsStrExt;
        let parsed = parse_worktree_porcelain(b"worktree /tmp/bad\xffpath\0HEAD abc\0\0").unwrap();
        assert_eq!(parsed[0].path.as_os_str().as_bytes(), b"/tmp/bad\xffpath");
    }

    #[test]
    fn parses_v2_status_headers_and_counts() {
        let input = b"# branch.oid abc123\0# branch.head topic\0# branch.upstream origin/topic\0# branch.ab +0 -0\x001 M. N... 100644 100644 100644 a b file\x002 .M N... 100644 100644 100644 a b R100 new\0old\0? untracked\0";
        let status = parse_status_porcelain(input).unwrap();
        assert_eq!(status.head.as_deref(), Some("abc123"));
        assert_eq!(status.branch.as_deref(), Some("topic"));
        assert_eq!(status.upstream.as_deref(), Some("origin/topic"));
        assert_eq!(status.staged, 1);
        assert_eq!(status.unstaged, 1);
        assert_eq!(status.untracked, 1);
        assert!(status.is_dirty());
    }

    #[test]
    fn rejects_incomplete_rename_status() {
        let input = b"2 R. N... 100644 100644 100644 a b R100 new\0";
        assert!(matches!(
            parse_status_porcelain(input),
            Err(GitError::MalformedStatus(_))
        ));
    }

    #[test]
    fn resolves_main_and_linked_worktrees_to_the_same_anchor() {
        let directory = tempfile::tempdir().unwrap();
        let main = directory.path().join("main");
        let linked = directory.path().join("linked tree");
        git(directory.path(), &["init", main.to_str().unwrap()]);
        git(&main, &["config", "user.email", "test@example.com"]);
        git(&main, &["config", "user.name", "Test User"]);
        git(&main, &["commit", "--allow-empty", "-m", "initial"]);
        git(
            &main,
            &["worktree", "add", "-b", "linked", linked.to_str().unwrap()],
        );

        let main_identity = resolve_repository(&SystemGit, &main).unwrap();
        let linked_identity = resolve_repository(&SystemGit, &linked).unwrap();
        assert_eq!(main_identity, linked_identity);
        assert_eq!(main_identity.anchor, fs::canonicalize(main).unwrap());
        assert!(!main_identity.bare);
    }

    #[test]
    fn infers_nearest_local_worktree_parent_from_commit_ancestry() {
        let directory = tempfile::tempdir().unwrap();
        let main = directory.path().join("main");
        let parent = directory.path().join("parent");
        let child = directory.path().join("child");
        git(
            directory.path(),
            &["init", "-b", "main", main.to_str().unwrap()],
        );
        git(&main, &["config", "user.email", "test@example.com"]);
        git(&main, &["config", "user.name", "Test User"]);
        git(&main, &["commit", "--allow-empty", "-m", "initial"]);
        git(
            &main,
            &["worktree", "add", "-b", "parent", parent.to_str().unwrap()],
        );
        git(&parent, &["commit", "--allow-empty", "-m", "parent"]);
        git(
            &main,
            &[
                "worktree",
                "add",
                "-b",
                "child",
                child.to_str().unwrap(),
                "parent",
            ],
        );
        git(&child, &["commit", "--allow-empty", "-m", "child"]);
        let config = RepositoryConfig {
            path: fs::canonicalize(&main).unwrap(),
            label: None,
            worktree_root: None,
            github_remote: None,
            github_remotes: Default::default(),
            github_preferred_remote: None,
        };
        let worktrees = discover_worktrees(&SystemGit, &config.path).unwrap();

        let parents = infer_worktree_parents(&SystemGit, &config, &worktrees).unwrap();

        assert_eq!(
            parents[&fs::canonicalize(&parent).unwrap()],
            fs::canonicalize(&main).unwrap()
        );
        assert_eq!(
            parents[&fs::canonicalize(&child).unwrap()],
            fs::canonicalize(&parent).unwrap()
        );
    }

    #[test]
    fn resolves_and_discovers_a_bare_repository_anchor() {
        let directory = tempfile::tempdir().unwrap();
        let bare = directory.path().join("project.git");
        git(
            directory.path(),
            &["init", "--bare", bare.to_str().unwrap()],
        );

        let identity = resolve_repository(&SystemGit, &bare).unwrap();
        assert!(identity.bare);
        assert_eq!(identity.anchor, fs::canonicalize(&bare).unwrap());
        let worktrees = discover_worktrees(&SystemGit, &bare).unwrap();
        assert_eq!(worktrees.len(), 1);
        assert!(worktrees[0].bare);
    }

    #[test]
    fn catalog_discovery_isolates_stale_repositories() {
        let directory = tempfile::tempdir().unwrap();
        let repository = directory.path().join("repository");
        git(directory.path(), &["init", repository.to_str().unwrap()]);
        let catalog = Catalog {
            repositories: vec![
                RepositoryConfig {
                    path: repository,
                    label: Some("valid".to_owned()),
                    worktree_root: None,
                    github_remote: None,
                    github_remotes: Default::default(),
                    github_preferred_remote: None,
                },
                RepositoryConfig {
                    path: directory.path().join("missing"),
                    label: Some("stale".to_owned()),
                    worktree_root: None,
                    github_remote: None,
                    github_remotes: Default::default(),
                    github_preferred_remote: None,
                },
            ],
            ..Catalog::default()
        };
        let discoveries = discover_catalog(&SystemGit, &catalog);
        assert!(discoveries[0].result.is_ok());
        assert!(discoveries[1].result.is_err());
    }

    fn git(directory: &Path, arguments: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(directory)
            .args(arguments)
            .status()
            .unwrap();
        assert!(status.success(), "git {arguments:?} failed");
    }
}