git-loom 0.25.0

A Git CLI tool that weaves together multiple feature branches into integration branches
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
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
use crate::core::repo::{
    CommitInfo, ContextCommit, FileChange, RemoteStatus, RepoInfo, UpstreamInfo,
};
use crate::core::shortid::{self, IdAllocator};
use colored::{Color, Colorize};
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::fmt::Write;

// ── Theme ────────────────────────────────────────────────────────────────

/// Color palette for graph output. Use [`Theme::dark`] or [`Theme::light`].
#[derive(Clone)]
pub struct Theme {
    /// Graph structure: lines, connectors, dots on the integration line.
    pub graph: Color,
    /// Branch names in brackets (local and remote).
    pub branch: Color,
    /// Labels like (upstream) and (common base).
    pub label: Color,
    /// Dimmed secondary text: messages, dates, file changes, "no changes".
    pub dim: Color,
    pub message: Color,
    /// Short ID prefix (also underlined in rendering).
    pub shortid: Color,
    /// Staged (index) file status: green, matching git convention.
    pub staged: Color,
    /// Unstaged (worktree) file status: red, matching git convention.
    pub unstaged: Color,
    /// Untracked file marker and path color.
    pub untracked: Color,
    /// Branch remote tracking ref exists and is in sync.
    pub remote_synced: Color,
    /// Branch has unpushed commits ahead of its remote.
    pub remote_ahead: Color,
    /// Branch remote tracking ref is gone (deleted on remote).
    pub remote_gone: Color,
    /// Conflicted file status: bold red, matching git convention.
    pub conflict: Color,
    /// Background of the cursor/selected line in TUIs: a shade clearly
    /// distinct from the terminal background while keeping the line's
    /// foreground colors readable (dim text switches to `dim_selected`).
    pub selection_bg: Color,
    /// Replacement for `dim` on the cursor/selected line, with enough
    /// contrast against `selection_bg`.
    pub dim_selected: Color,
    pub branch_dots: &'static [Color],
}

impl Theme {
    /// Dark terminal background theme (default).
    pub fn dark() -> Self {
        Theme {
            graph: Color::BrightBlack,
            branch: Color::Green,
            label: Color::Cyan,
            dim: Color::AnsiColor(240),
            message: Color::AnsiColor(248),
            shortid: Color::Blue,
            staged: Color::Green,
            unstaged: Color::Red,
            untracked: Color::Magenta,
            remote_synced: Color::Green,
            remote_ahead: Color::Yellow,
            remote_gone: Color::Red,
            conflict: Color::Red,
            selection_bg: Color::AnsiColor(239),
            dim_selected: Color::AnsiColor(245),
            branch_dots: BRANCH_DOTS,
        }
    }

    pub fn light() -> Self {
        Theme {
            graph: Color::AnsiColor(248),
            branch: Color::Green,
            label: Color::Blue,
            dim: Color::AnsiColor(248),
            message: Color::AnsiColor(243),
            shortid: Color::Blue,
            staged: Color::Green,
            unstaged: Color::Red,
            untracked: Color::Magenta,
            remote_synced: Color::Green,
            remote_ahead: Color::Yellow,
            remote_gone: Color::Red,
            conflict: Color::Red,
            selection_bg: Color::AnsiColor(251),
            dim_selected: Color::AnsiColor(242),
            branch_dots: BRANCH_DOTS,
        }
    }
}

/// Rotating colors for commit dots on feature branches (shared by all themes).
const BRANCH_DOTS: &[Color] = &[
    Color::Yellow,
    Color::Cyan,
    Color::Magenta,
    Color::Blue,
    Color::Red,
    Color::Green,
];

/// Number of untracked files above which the display switches to multi-column layout.
const UNTRACKED_MULTICOLUMN_THRESHOLD: usize = 5;

/// Width of the graph prefix ("│   ") in visible columns.
const GRAPH_PREFIX_WIDTH: usize = 4;

// ── Data types ──────────────────────────────────────────────────────────

/// Display configuration for the status graph renderer.
pub struct RenderOpts {
    /// Terminal column width, used for multi-column untracked layout.
    /// `None` means non-TTY (e.g. pipe) — fall back to single-column.
    pub terminal_width: Option<u16>,
    pub theme: Theme,
    /// CWD prefix relative to repo root (empty string if at root).
    pub cwd_prefix: String,
}

/// A logical section in the rendered status output. Sections are built from
/// RepoInfo and rendered top-to-bottom with UTF-8 box-drawing characters.
/// Also consumed by `loom tui` to build its interactive tree.
pub(crate) enum Section {
    /// Working tree status (always present, may contain zero changes).
    WorkingChanges(Vec<FileChange>),
    /// A feature branch: its name(s) and the commits it owns.
    /// Multiple names occur when several branches point to the same tip commit.
    /// Each name is paired with its remote tracking status (None = never pushed).
    Branch {
        names: Vec<(String, Option<RemoteStatus>)>,
        commits: Vec<CommitInfo>,
    },
    /// Commits on the integration line that don't belong to any feature branch.
    Loose(Vec<CommitInfo>),
    /// The upstream tracking branch / common base marker at the bottom of the status.
    Upstream(UpstreamInfo),
    /// Context commits before the base (display-only, dimmed).
    Context(Vec<ContextCommit>),
}

// ── Public API ──────────────────────────────────────────────────────────

/// Detect terminal width and build render options for the given theme. The
/// width is the one of the stream the tree is written to, which `msg` owns.
pub fn default_render_opts(theme: Theme, cwd_prefix: String) -> RenderOpts {
    RenderOpts {
        terminal_width: crate::core::msg::human_stream_width(),
        theme,
        cwd_prefix,
    }
}

/// Convert a repo-relative path to CWD-relative for display.
fn display_path(repo_path: &str, cwd_prefix: &str) -> String {
    crate::core::repo::cwd_relative_path(repo_path, cwd_prefix)
}

/// The three groups the local-changes section renders, in that order
/// (Spec 001). The renderer partitions by it and the agent JSON reports it, so
/// the two classifications cannot drift.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum FileGroup {
    Conflicted,
    Tracked,
    Untracked,
}

/// Classify a working-tree change from its `XY` status characters. A conflict
/// wins over every other marker: `gather` sets `?` on the worktree side of a
/// conflicted add, and such a file belongs with the conflicts rather than
/// vanishing between the groups. Takes the two characters rather than a
/// [`FileChange`] so the TUI, which carries them loose, classifies here too.
pub(crate) fn file_group(index: char, worktree: char) -> FileGroup {
    if index == '!' || worktree == '!' {
        FileGroup::Conflicted
    } else if index == '?' && worktree == '?' {
        FileGroup::Untracked
    } else {
        FileGroup::Tracked
    }
}

// ── Section building ────────────────────────────────────────────────────

/// The name commit assignment uses for the branch(es) at `tip`: the first one
/// listed, which matters only when several branch names are co-located there.
fn canonical_branch_name(info: &RepoInfo, tip: git2::Oid) -> &str {
    info.branches
        .iter()
        .find(|b| b.tip_oid == tip)
        .map_or("", |b| b.name.as_str())
}

/// Assign each in-range commit to the feature branch that owns it by walking
/// parent links from every branch tip. Commits absent from the returned map
/// are "loose": they sit on the integration line and belong to no feature
/// branch.
fn assign_commits_to_branches(info: &RepoInfo) -> HashMap<git2::Oid, String> {
    let branch_tip_set: HashSet<git2::Oid> = info.branches.iter().map(|b| b.tip_oid).collect();

    let parent_map: HashMap<git2::Oid, Option<git2::Oid>> =
        info.commits.iter().map(|c| (c.oid, c.parent_oid)).collect();

    // From each branch tip, walk parent links until a commit outside the range
    // or another branch's tip (the stacked-branch boundary). The first name in a
    // co-located group is the canonical one for assignment.
    let mut commit_to_branch: HashMap<git2::Oid, String> = HashMap::new();
    let mut seen_tips: HashSet<git2::Oid> = HashSet::new();
    for b in &info.branches {
        if !seen_tips.insert(b.tip_oid) {
            continue; // Already processed commits for this tip
        }
        let canonical_name = canonical_branch_name(info, b.tip_oid).to_string();
        let mut current = Some(b.tip_oid);
        let mut is_tip = true;
        while let Some(oid) = current {
            if !parent_map.contains_key(&oid) {
                break; // outside our commit range
            }
            // Stop at another branch's tip (but not at our own tip)
            if !is_tip && branch_tip_set.contains(&oid) {
                break;
            }
            is_tip = false;
            commit_to_branch.insert(oid, canonical_name.clone());
            current = parent_map.get(&oid).and_then(|p| *p);
        }
    }

    commit_to_branch
}

/// OIDs of the commits shown on the integration line: those belonging to no
/// feature branch, in topological order (newest first).
pub fn loose_commits(info: &RepoInfo) -> Vec<git2::Oid> {
    let commit_to_branch = assign_commits_to_branches(info);
    info.commits
        .iter()
        .filter(|c| !commit_to_branch.contains_key(&c.oid))
        .map(|c| c.oid)
        .collect()
}

/// OIDs of the commits the status graph attributes to `branch`, in topological
/// order (newest first). Empty when `branch` is not a feature branch in the
/// graph, or owns no commits of its own.
pub fn commits_in_branch(info: &RepoInfo, branch: &str) -> Vec<git2::Oid> {
    let Some(tip) = info
        .branches
        .iter()
        .find(|b| b.name == branch)
        .map(|b| b.tip_oid)
    else {
        return Vec::new();
    };
    let owner = canonical_branch_name(info, tip);

    let commit_to_branch = assign_commits_to_branches(info);
    info.commits
        .iter()
        .filter(|c| commit_to_branch.get(&c.oid).is_some_and(|n| n == owner))
        .map(|c| c.oid)
        .collect()
}

/// The name the stack helpers use for `branch`: the canonical name of its
/// tip, so branch names co-located on one commit compare equal. Unknown
/// names are returned unchanged.
fn canonical_name<'a>(info: &'a RepoInfo, branch: &'a str) -> &'a str {
    info.branches
        .iter()
        .find(|b| b.name == branch)
        .map(|b| canonical_branch_name(info, b.tip_oid))
        .unwrap_or(branch)
}

/// The feature branch `branch` is stacked on: the one whose tip is the parent
/// of the oldest commit `branch` owns. `None` when that parent is a loose
/// commit or the upstream base, or when `branch` owns no commits.
///
/// Co-located tips resolve to their canonical name, like the status graph.
pub fn stack_parent(info: &RepoInfo, branch: &str) -> Option<String> {
    let tip = info.branches.iter().find(|b| b.name == branch)?.tip_oid;
    StackIndex::new(info).parent(tip).map(str::to_string)
}

/// Every branch's [`stack_parent`], keyed by branch name — co-located names
/// included, each resolving to the same parent as its canonical one.
///
/// Lets a caller holding only the section list answer what that list cannot:
/// an empty branch below a stack owns no commits, so section adjacency misses
/// the edge (Spec 011).
pub(crate) fn stack_parents(info: &RepoInfo) -> HashMap<String, String> {
    let index = StackIndex::new(info);
    info.branches
        .iter()
        .filter_map(|b| Some((b.name.clone(), index.parent(b.tip_oid)?.to_string())))
        .collect()
}

/// The one assignment pass both stack-parent lookups share, so a whole-graph
/// query stays linear instead of re-assigning commits per branch.
struct StackIndex<'a> {
    /// Branch tip → canonical name, the first branch listed at that tip.
    canonical: HashMap<git2::Oid, &'a str>,
    /// Canonical owner → the oldest commit it owns.
    oldest: HashMap<String, &'a CommitInfo>,
}

impl<'a> StackIndex<'a> {
    fn new(info: &'a RepoInfo) -> Self {
        let mut canonical: HashMap<git2::Oid, &str> = HashMap::new();
        for b in &info.branches {
            canonical.entry(b.tip_oid).or_insert(b.name.as_str());
        }
        // `info.commits` is newest first, so the last commit seen for an owner
        // is the oldest it owns — the one whose parent leaves the branch.
        let mut commit_to_branch = assign_commits_to_branches(info);
        let mut oldest = HashMap::new();
        for c in &info.commits {
            if let Some(owner) = commit_to_branch.remove(&c.oid) {
                oldest.insert(owner, c);
            }
        }
        Self { canonical, oldest }
    }

    /// The canonical name of the branch the one at `tip` is stacked on.
    fn parent(&self, tip: git2::Oid) -> Option<&'a str> {
        let owner = *self.canonical.get(&tip)?;
        let parent = self.oldest.get(owner)?.parent_oid?;
        self.canonical.get(&parent).copied()
    }
}

/// The branches `branch` depends on, bottom first, ending with `branch`
/// itself. A branch that is not stacked yields just `[branch]`.
pub fn downstack(info: &RepoInfo, branch: &str) -> Vec<String> {
    let mut chain = vec![branch.to_string()];
    while let Some(parent) = stack_parent(info, chain.last().unwrap()) {
        if chain.contains(&parent) {
            break;
        }
        chain.push(parent);
    }
    chain.reverse();
    chain
}

/// The branch stacked directly on `branch`, if any.
///
/// A stack is linear: the weave replays the feature branches one after
/// another, so a branch built on another branch's tip either continues that
/// stack or is rebased off it. Nothing ever sits beside a layer.
fn stack_child(info: &RepoInfo, branch: &str) -> Option<String> {
    let canonical = canonical_name(info, branch);
    info.branches
        .iter()
        .find(|b| stack_parent(info, &b.name).as_deref() == Some(canonical))
        .map(|b| canonical_branch_name(info, b.tip_oid).to_string())
}

/// The branches stacked on top of `branch`, nearest first. Co-located names
/// are represented once, by their canonical name.
pub fn upstack(info: &RepoInfo, branch: &str) -> Vec<String> {
    let mut above: Vec<String> = Vec::new();
    let mut current = branch.to_string();
    while let Some(child) = stack_child(info, &current) {
        if above.contains(&child) {
            break;
        }
        above.push(child.clone());
        current = child;
    }
    above
}

/// Group commits into sections: working changes, feature branches, loose
/// commits, and the upstream marker.
pub(crate) fn build_sections(info: RepoInfo) -> Vec<Section> {
    let commit_to_branch = assign_commits_to_branches(&info);

    // Group branches by tip OID to handle co-located branches (multiple
    // branch names pointing to the same commit).
    let mut tip_to_names: HashMap<git2::Oid, Vec<(String, Option<RemoteStatus>)>> = HashMap::new();
    for b in &info.branches {
        tip_to_names
            .entry(b.tip_oid)
            .or_default()
            .push((b.name.clone(), b.remote.clone()));
    }

    // Map canonical name → all names for that branch group.
    // Reverse so the newest (alphabetically last) branch appears on top.
    let mut canonical_to_names: HashMap<String, Vec<(String, Option<RemoteStatus>)>> =
        HashMap::new();
    for branches in tip_to_names.values() {
        let mut reversed = branches.clone();
        reversed.reverse();
        canonical_to_names.insert(branches[0].0.clone(), reversed);
    }

    let mut sections: Vec<Section> = Vec::new();

    sections.push(Section::WorkingChanges(info.working_changes));

    // Separate commits into loose and branch groups, preserving topo order within each.
    let mut loose_commits: Vec<CommitInfo> = Vec::new();
    let mut branch_sections: Vec<Section> = Vec::new();

    let mut commits = info.commits.into_iter().peekable();
    while let Some(commit) = commits.next() {
        if let Some(branch_name) = commit_to_branch.get(&commit.oid) {
            let name = branch_name.clone();
            let names = canonical_to_names
                .get(&name)
                .cloned()
                .unwrap_or_else(|| vec![(name.clone(), None)]);
            let mut branch_commits = vec![commit];

            // Collect subsequent commits that belong to the same branch.
            while let Some(next) = commits.peek() {
                if commit_to_branch.get(&next.oid) == Some(&name) {
                    branch_commits.push(commits.next().unwrap());
                } else {
                    break;
                }
            }
            branch_sections.push(Section::Branch {
                names,
                commits: branch_commits,
            });
        } else {
            loose_commits.push(commit);
            while let Some(next) = commits.peek() {
                if commit_to_branch.contains_key(&next.oid) {
                    break;
                }
                loose_commits.push(commits.next().unwrap());
            }
        }
    }

    // Branches at the merge-base own no commits: they render as empty
    // sections, above the branches that own commits.
    let represented: HashSet<&String> = commit_to_branch.values().collect();
    let mut empty_sections: Vec<Section> = Vec::new();
    for branches in canonical_to_names.values() {
        // canonical key is the pre-reversal first name; check if any name is represented
        if !branches.iter().any(|(n, _)| represented.contains(n)) {
            empty_sections.push(Section::Branch {
                names: branches.clone(),
                commits: vec![],
            });
        }
    }
    // `canonical_to_names` is a HashMap: order them alphabetically last first,
    // as co-located names are, so the tree is stable across rebuilds.
    empty_sections.sort_by(|a, b| match (a, b) {
        (Section::Branch { names: a, .. }, Section::Branch { names: b, .. }) => b[0].0.cmp(&a[0].0),
        _ => Ordering::Equal,
    });

    // Loose commits first, then empty branches, then the ones owning commits.
    if !loose_commits.is_empty() {
        sections.push(Section::Loose(loose_commits));
    }
    sections.extend(empty_sections);
    sections.extend(branch_sections);

    sections.push(Section::Upstream(info.upstream));

    if !info.context_commits.is_empty() {
        sections.push(Section::Context(info.context_commits));
    }

    sections
}

/// Check if the next branch section is stacked on top of the current one.
/// Two branches are stacked if the first commit of the next branch is a parent
/// of the last commit of the current branch.
pub(crate) fn is_stacked_with_next(sections: &[Section], idx: usize) -> bool {
    let Section::Branch { commits, .. } = &sections[idx] else {
        return false;
    };
    let Some(Section::Branch {
        commits: next_commits,
        ..
    }) = sections.get(idx + 1)
    else {
        return false;
    };
    let Some(last) = commits.last() else {
        return false;
    };
    let Some(next_first) = next_commits.first() else {
        return false;
    };
    last.parent_oid == Some(next_first.oid)
}

// ── Rendering ───────────────────────────────────────────────────────────

/// Columns reserved for a commit short ID, so the subject column stays put
/// across invocations instead of reflowing when an ID grows (Spec 002). A
/// longer ID (five letters, or a numeric-suffix fallback) pushes its own line
/// right rather than the whole tree.
const COMMIT_ID_SLOT: usize = 4;

/// Spaces between a commit short ID and the hash that follows it: always at
/// least one.
pub(crate) fn id_pad(sid: &str) -> String {
    " ".repeat(COMMIT_ID_SLOT.saturating_sub(sid.chars().count()) + 1)
}

/// Render sections as a UTF-8 graph. Stacked branches (where the last commit
/// of a branch is a parent of the first commit of the next) are connected
/// with `││` and `│├─`, while independent branches get `├╯` then `│╭─`.
pub(crate) fn render_sections(
    sections: &[Section],
    ids: &IdAllocator,
    opts: &RenderOpts,
) -> String {
    let mut out = String::new();
    let last_idx = sections.len() - 1;
    let mut branch_color_idx: usize = 0;

    for (idx, section) in sections.iter().enumerate() {
        match section {
            Section::WorkingChanges(changes) => {
                render_working_changes(&mut out, changes, ids, opts);
            }
            Section::Branch { names, commits } => {
                let dot_color =
                    opts.theme.branch_dots[branch_color_idx % opts.theme.branch_dots.len()];
                branch_color_idx += 1;

                let prev_stacked = idx > 0 && is_stacked_with_next(sections, idx - 1);
                let next_stacked = is_stacked_with_next(sections, idx);

                render_branch(
                    &mut out,
                    names,
                    commits,
                    dot_color,
                    prev_stacked,
                    next_stacked,
                    idx < last_idx,
                    ids,
                    &opts.theme,
                    &opts.cwd_prefix,
                );
            }
            Section::Loose(commits) => {
                render_loose(
                    &mut out,
                    commits,
                    idx < last_idx,
                    ids,
                    &opts.theme,
                    &opts.cwd_prefix,
                );
            }
            Section::Upstream(info) => {
                render_upstream(&mut out, info, &opts.theme);
            }
            Section::Context(commits) => {
                render_context(&mut out, commits, &opts.theme);
            }
        }
    }

    out
}

fn render_working_changes(
    out: &mut String,
    changes: &[FileChange],
    ids: &IdAllocator,
    opts: &RenderOpts,
) {
    let theme = &opts.theme;
    writeln!(
        out,
        "{} {} {}{}{}",
        "╭─".color(theme.graph),
        ids.get_unstaged().color(theme.shortid).underline(),
        "[".color(theme.dim),
        "local changes".color(theme.label),
        "]".color(theme.dim)
    )
    .unwrap();

    let group_of = |g: FileGroup| -> Vec<&FileChange> {
        changes
            .iter()
            .filter(|f| file_group(f.index, f.worktree) == g)
            .collect()
    };
    let conflicted = group_of(FileGroup::Conflicted);
    let tracked = group_of(FileGroup::Tracked);
    let untracked = group_of(FileGroup::Untracked);

    if conflicted.is_empty() && tracked.is_empty() && untracked.is_empty() {
        writeln!(
            out,
            "{}   {}",
            "│".color(theme.graph),
            "no changes".color(theme.dim)
        )
        .unwrap();
    } else {
        for change in &conflicted {
            writeln!(
                out,
                "{}   {} {} {}",
                "│".color(theme.graph),
                ids.get_file(&change.path).color(theme.shortid).underline(),
                "!!".color(theme.conflict).bold(),
                display_path(&change.path, &opts.cwd_prefix)
                    .color(theme.conflict)
                    .bold()
            )
            .unwrap();
        }
        for change in &tracked {
            writeln!(
                out,
                "{}   {} {}{} {}",
                "│".color(theme.graph),
                ids.get_file(&change.path).color(theme.shortid).underline(),
                change.index.to_string().color(theme.staged),
                change.worktree.to_string().color(theme.unstaged),
                display_path(&change.path, &opts.cwd_prefix)
            )
            .unwrap();
        }
        if !untracked.is_empty() {
            render_untracked(out, &untracked, ids, opts);
        }
    }

    writeln!(out, "{}", "│".color(theme.graph)).unwrap();
}

fn render_untracked(
    out: &mut String,
    untracked: &[&FileChange],
    ids: &IdAllocator,
    opts: &RenderOpts,
) {
    if untracked.len() > UNTRACKED_MULTICOLUMN_THRESHOLD
        && let Some(width) = opts.terminal_width
    {
        render_untracked_multicolumn(out, untracked, ids, width, &opts.theme, &opts.cwd_prefix);
        return;
    }
    render_untracked_single_column(out, untracked, ids, &opts.theme, &opts.cwd_prefix);
}

fn render_untracked_single_column(
    out: &mut String,
    untracked: &[&FileChange],
    ids: &IdAllocator,
    theme: &Theme,
    cwd_prefix: &str,
) {
    for change in untracked {
        writeln!(
            out,
            "{}   {} {} {}",
            "│".color(theme.graph),
            ids.get_file(&change.path).color(theme.shortid).underline(),
            " ⁕".color(theme.untracked),
            display_path(&change.path, cwd_prefix)
        )
        .unwrap();
    }
}

/// Render untracked files in a multi-column grid (top-to-bottom, left-to-right).
fn render_untracked_multicolumn(
    out: &mut String,
    untracked: &[&FileChange],
    ids: &IdAllocator,
    term_width: u16,
    theme: &Theme,
    cwd_prefix: &str,
) {
    let available = (term_width as usize).saturating_sub(GRAPH_PREFIX_WIDTH);
    let separator = "   │ "; // 5 display columns
    let separator_width: usize = 5;

    // Compute plain-text width of each entry: "{sid}  ⁕ {path}"
    let entry_widths: Vec<usize> = untracked
        .iter()
        .map(|f| {
            let sid = ids.get_file(&f.path);
            let disp = display_path(&f.path, cwd_prefix);
            sid.len() + 1 + 2 + 1 + disp.len()
        })
        .collect();

    let max_entry_width = entry_widths.iter().copied().max().unwrap_or(1);
    let col_slot = max_entry_width + separator_width;

    let num_cols = (available / col_slot).max(1).min(untracked.len());
    let num_rows = untracked.len().div_ceil(num_cols);

    for row in 0..num_rows {
        write!(out, "{}   ", "│".color(theme.graph)).unwrap();
        for col in 0..num_cols {
            let idx = col * num_rows + row;
            if idx >= untracked.len() {
                break;
            }
            let f = untracked[idx];
            let sid = ids.get_file(&f.path);
            let disp = display_path(&f.path, cwd_prefix);

            write!(
                out,
                "{} {} {}",
                sid.color(theme.shortid).underline(),
                " ⁕".color(theme.untracked),
                disp
            )
            .unwrap();

            // Pad entry to max_entry_width, then add pipe separator
            let next_idx = (col + 1) * num_rows + row;
            if col + 1 < num_cols && next_idx < untracked.len() {
                let padding = max_entry_width.saturating_sub(entry_widths[idx]);
                write!(out, "{}{}", " ".repeat(padding), separator.color(theme.dim)).unwrap();
            }
        }
        writeln!(out).unwrap();
    }
}

#[allow(clippy::too_many_arguments)]
fn render_branch(
    out: &mut String,
    names: &[(String, Option<RemoteStatus>)],
    commits: &[CommitInfo],
    dot_color: Color,
    prev_stacked: bool,
    next_stacked: bool,
    more_sections: bool,
    ids: &IdAllocator,
    theme: &Theme,
    cwd_prefix: &str,
) {
    for (i, (name, remote)) in names.iter().enumerate() {
        let branch_id = ids.get_branch(name);
        let connector = if i == 0 && !prev_stacked {
            "│╭─"
        } else {
            "│├─"
        };
        let remote_indicator = match remote {
            Some(RemoteStatus::Synced) => format!(" {}", "✓".color(theme.remote_synced)),
            Some(RemoteStatus::Different) => format!(" {}", "↑".color(theme.remote_ahead)),
            Some(RemoteStatus::Gone) => format!(" {}", "✗".color(theme.remote_gone)),
            None => String::new(),
        };
        writeln!(
            out,
            "{} {} {}{}{}{}",
            connector.color(theme.graph),
            branch_id.color(theme.shortid).underline(),
            "[".color(theme.dim),
            name.color(theme.branch).bold(),
            "]".color(theme.dim),
            remote_indicator,
        )
        .unwrap();
    }

    for commit in commits {
        let sid = ids.get_commit(commit.oid);
        writeln!(
            out,
            "{}{}    {}{}{} {}",
            "│".color(theme.graph),
            "●".color(dot_color),
            sid.color(theme.shortid).underline(),
            id_pad(sid),
            commit.short_id.color(theme.dim),
            commit.message,
        )
        .unwrap();
        for (i, file) in commit.files.iter().enumerate() {
            let file_sid = shortid::commit_file_id(sid, i);
            writeln!(
                out,
                "{}{}      {} {}{} {}",
                "│".color(theme.graph),
                "┊".color(dot_color),
                file_sid.color(theme.shortid).underline(),
                file.index.to_string().color(theme.staged),
                file.worktree.to_string().color(theme.unstaged),
                display_path(&file.path, cwd_prefix)
            )
            .unwrap();
        }
    }
    if next_stacked {
        writeln!(out, "{}", "││".color(theme.graph)).unwrap();
    } else {
        writeln!(out, "{}", "├╯".color(theme.graph)).unwrap();
        if more_sections {
            writeln!(out, "{}", "│".color(theme.graph)).unwrap();
        }
    }
}

fn render_loose(
    out: &mut String,
    commits: &[CommitInfo],
    more_sections: bool,
    ids: &IdAllocator,
    theme: &Theme,
    cwd_prefix: &str,
) {
    for commit in commits {
        let sid = ids.get_commit(commit.oid);
        writeln!(
            out,
            "{}    {}{}{} {}",
            "●".color(theme.graph),
            sid.color(theme.shortid).underline(),
            id_pad(sid),
            commit.short_id.color(theme.dim),
            commit.message,
        )
        .unwrap();
        for (i, file) in commit.files.iter().enumerate() {
            let file_sid = shortid::commit_file_id(sid, i);
            writeln!(
                out,
                "{}       {} {}{} {}",
                "┊".color(theme.graph),
                file_sid.color(theme.shortid).underline(),
                file.index.to_string().color(theme.staged),
                file.worktree.to_string().color(theme.unstaged),
                display_path(&file.path, cwd_prefix)
            )
            .unwrap();
        }
    }
    if more_sections {
        writeln!(out, "{}", "│".color(theme.graph)).unwrap();
    }
}

fn render_upstream(out: &mut String, info: &UpstreamInfo, theme: &Theme) {
    if info.commits_ahead > 0 {
        let count_text = format!(
            "\u{23EB} {} new commit{}",
            info.commits_ahead,
            if info.commits_ahead == 1 { "" } else { "s" }
        )
        .color(theme.message);
        writeln!(
            out,
            "{}{}  {}{}{} {}",
            "│".color(theme.graph),
            "●".color(theme.graph),
            "[".color(theme.dim),
            info.label.color(theme.branch).bold(),
            "]".color(theme.dim),
            count_text
        )
        .unwrap();
        writeln!(
            out,
            "{} {} {} {} {}",
            "├╯".color(theme.graph),
            info.base_short_id.color(theme.dim),
            "(common base)".color(theme.label),
            info.base_date.color(theme.dim),
            info.base_message.color(theme.message)
        )
        .unwrap();
    } else {
        writeln!(
            out,
            "{} {} {} {}{}{} {}",
            "●".color(theme.graph),
            info.base_short_id.color(theme.dim),
            "(upstream)".color(theme.label),
            "[".color(theme.dim),
            info.label.color(theme.branch).bold(),
            "]".color(theme.dim),
            info.base_message.color(theme.message)
        )
        .unwrap();
    }
}

fn render_context(out: &mut String, commits: &[ContextCommit], theme: &Theme) {
    for commit in commits {
        writeln!(
            out,
            "{} {} {} {}",
            "·".color(theme.dim),
            commit.short_hash.color(theme.dim),
            commit.date.color(theme.dim),
            commit.message.color(theme.message),
        )
        .unwrap();
    }
}

#[cfg(test)]
#[path = "graph_test.rs"]
mod tests;