gitpane 0.9.1

Multi-repo Git workspace dashboard 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
use git2::{Oid, Repository, Sort};
use std::collections::{BTreeSet, HashSet};
use std::path::Path;

use crate::config::BranchFilter;

mod refs;
mod segments;
#[cfg(test)]
mod tests;

use refs::{merge_stash_labels, resolve_refs};

pub(crate) use segments::{BranchSegment, compute_branch_segments};

const MAX_COMMITS: usize = 200;
const PALETTE_SIZE: usize = 6;

#[derive(Clone, Debug)]
pub(crate) struct BranchLabel {
    pub name: String,
    pub is_head: bool,
    pub is_remote: bool,
    pub is_worktree: bool,
    pub is_tag: bool,
    /// Label points at a commit that is the parent of a stash entry
    /// (`stash@{n}`). Rendered with the stash theme color.
    pub is_stash: bool,
}

#[derive(Clone, Debug)]
pub(crate) struct GraphOptions {
    pub branch_filter: BranchFilter,
    pub label_max_len: usize,
    pub first_parent: bool,
    pub show_stats: bool,
    pub filters: GraphFilters,
}

impl Default for GraphOptions {
    fn default() -> Self {
        Self {
            branch_filter: BranchFilter::All,
            label_max_len: 24,
            first_parent: false,
            show_stats: true,
            filters: GraphFilters::default(),
        }
    }
}

/// Optional include lists for the graph. `None` means every value in the
/// category is included; an empty set deliberately produces an empty graph.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct GraphFilters {
    pub branches: Option<BTreeSet<String>>,
    pub authors: Option<BTreeSet<String>>,
    pub refs: GraphRefFilters,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct GraphRefFilters {
    pub local: bool,
    pub remote: bool,
    pub tags: bool,
    pub stashes: bool,
}

impl Default for GraphRefFilters {
    fn default() -> Self {
        Self {
            local: true,
            remote: true,
            tags: true,
            stashes: true,
        }
    }
}

impl GraphRefFilters {
    fn includes(&self, label: &BranchLabel) -> bool {
        if label.is_stash {
            self.stashes
        } else if label.is_tag {
            self.tags
        } else if label.is_remote {
            self.remote
        } else {
            self.local
        }
    }
}

#[derive(Clone, Debug)]
pub(crate) struct DiffStat {
    pub additions: usize,
    pub deletions: usize,
}

#[derive(Clone, Debug)]
#[allow(dead_code)]
pub(crate) struct GraphRow {
    pub commit_col: usize,
    pub lanes: Vec<LaneSegment>,
    pub oid: Oid,
    pub short_id: String,
    pub message: String,
    pub author: String,
    pub time: i64,
    pub labels: Vec<BranchLabel>,
    pub is_merge: bool,
    pub horizontal_spans: Vec<(usize, usize, usize)>,
    pub parent_oids: Vec<Oid>,
    pub diff_stat: Option<DiffStat>,
    /// If set, this row is a collapsed-branch placeholder: (branch_name, hidden_count).
    pub collapsed: Option<(String, usize)>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum LaneSegment {
    Empty,
    Straight,
    Commit,
    MergeLeft,
    MergeRight,
    ForkLeft,
    ForkRight,
    Horizontal,
    CrossHorizontal,
    RightTee,
    LeftTee,
}

#[derive(Clone, Debug)]
pub(crate) struct GraphBuilder {
    active_lanes: Vec<Option<Oid>>,
}

impl GraphBuilder {
    pub fn new() -> Self {
        Self {
            active_lanes: Vec::new(),
        }
    }

    pub fn build(
        mut self,
        path: &Path,
        options: &GraphOptions,
    ) -> color_eyre::Result<Vec<GraphRow>> {
        let mut repo = Repository::open(path)?;
        let mut ref_map = resolve_refs(&repo, &options.branch_filter);
        merge_stash_labels(&mut repo, &mut ref_map);

        // A branch selection is the graph's root set. Keep this separate from
        // label visibility: tags/stashes may decorate selected commits, but
        // must not keep an otherwise empty branch selection alive.
        let selected_branch_oids = options.filters.branches.as_ref().map(|branches| {
            ref_map
                .iter()
                .filter(|(_, labels)| {
                    labels.iter().any(|label| {
                        !label.is_tag
                            && !label.is_stash
                            && options.filters.refs.includes(label)
                            && branches.contains(&label.name)
                    })
                })
                .map(|(oid, _)| *oid)
                .collect::<HashSet<_>>()
        });
        if selected_branch_oids.as_ref().is_some_and(HashSet::is_empty) {
            return Ok(Vec::new());
        }

        for labels in ref_map.values_mut() {
            labels.retain(|label| options.filters.refs.includes(label));
        }
        ref_map.retain(|_, labels| !labels.is_empty());

        if let Some(branches) = &options.filters.branches {
            for labels in ref_map.values_mut() {
                labels.retain(|label| {
                    label.is_tag || label.is_stash || branches.contains(&label.name)
                });
            }
            ref_map.retain(|_, labels| !labels.is_empty());
        }

        let mut revwalk = repo.revwalk()?;
        // An explicit branch selection owns the walk roots. Otherwise retain
        // the usual HEAD root so detached HEAD and unborn repositories behave
        // exactly as before.
        if options.filters.branches.is_none() && options.filters.refs.local {
            revwalk.push_head().ok(); // ok: handles unborn HEAD
        }
        if let Some(oids) = &selected_branch_oids {
            for &oid in oids {
                revwalk.push(oid).ok(); // git2 deduplicates
            }
        } else {
            for &oid in ref_map.keys() {
                revwalk.push(oid).ok(); // git2 deduplicates
            }
        }
        revwalk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;
        if options.first_parent {
            revwalk.simplify_first_parent()?;
        }

        let mut rows = Vec::new();

        for oid_result in revwalk.take(MAX_COMMITS) {
            let oid = oid_result?;
            let commit = repo.find_commit(oid)?;

            let parent_oids: Vec<Oid> = commit.parent_ids().collect();
            let is_merge = commit.parent_count() > 1;
            let labels = ref_map.remove(&oid).unwrap_or_default();
            let (commit_col, lanes, horizontal_spans) = self.process_commit(oid, &parent_oids);

            let short_id = oid.to_string()[..7].to_string();
            let message = commit.summary().ok().flatten().unwrap_or("").to_string();
            let author = commit.author().name().unwrap_or("").to_string();
            let time = commit.time().seconds();

            // Still process excluded commits above so the lane state for later
            // visible commits remains consistent with the repository DAG.
            if options
                .filters
                .authors
                .as_ref()
                .is_some_and(|authors| !authors.contains(&author))
            {
                continue;
            }

            rows.push(GraphRow {
                commit_col,
                lanes,
                oid,
                short_id,
                message,
                author,
                time,
                labels,
                is_merge,
                horizontal_spans,
                parent_oids,
                diff_stat: None,
                collapsed: None,
            });
        }

        Ok(rows)
    }

    /// Branch names available to the filter picker, independent of the active
    /// graph filters. A filtered walk must not make deselected branches vanish
    /// from the picker.
    pub fn branch_names(
        path: &Path,
        branch_filter: &BranchFilter,
    ) -> color_eyre::Result<Vec<String>> {
        let repo = Repository::open(path)?;
        let refs = resolve_refs(&repo, branch_filter);
        let names = refs
            .values()
            .flat_map(|labels| labels.iter())
            .filter(|label| !label.is_tag && !label.is_stash)
            .map(|label| label.name.clone())
            .collect::<BTreeSet<_>>();
        Ok(names.into_iter().collect())
    }

    fn process_commit(
        &mut self,
        oid: Oid,
        parent_oids: &[Oid],
    ) -> (usize, Vec<LaneSegment>, Vec<(usize, usize, usize)>) {
        // Find which lane this commit occupies
        let commit_col = self
            .active_lanes
            .iter()
            .position(|lane| *lane == Some(oid))
            .unwrap_or_else(|| {
                // Allocate a new lane
                let col = self.find_free_lane();
                if col < self.active_lanes.len() {
                    self.active_lanes[col] = Some(oid);
                } else {
                    self.active_lanes.push(Some(oid));
                }
                col
            });

        // Build lane segments for this row
        let lane_count = self.active_lanes.len().max(commit_col + 1);
        let mut lanes = vec![LaneSegment::Empty; lane_count];

        // Mark continuing lanes
        for (i, lane) in self.active_lanes.iter().enumerate() {
            if i < lanes.len() && lane.is_some() && i != commit_col {
                lanes[i] = LaneSegment::Straight;
            }
        }

        // Mark commit position
        lanes[commit_col] = LaneSegment::Commit;

        // Process parents
        // Clear this commit's lane first
        self.active_lanes[commit_col] = None;
        let mut spans: Vec<(usize, usize, usize)> = Vec::new();

        if !parent_oids.is_empty() {
            // First parent continues in same lane
            let first_parent = parent_oids[0];

            // Check if first parent is already in another lane
            let existing_lane = self
                .active_lanes
                .iter()
                .position(|lane| *lane == Some(first_parent));

            if let Some(existing) = existing_lane {
                // First parent already has a lane — merge to it
                if existing < commit_col {
                    lanes[commit_col] = LaneSegment::MergeLeft;
                    spans.push((existing, commit_col, lane_color(commit_col)));
                } else if existing > commit_col {
                    lanes[commit_col] = LaneSegment::MergeRight;
                    spans.push((commit_col, existing, lane_color(commit_col)));
                }
                // Don't re-assign; lane stays as is
            } else {
                // First parent takes over this lane
                self.active_lanes[commit_col] = Some(first_parent);
            }

            // Additional parents fork into new lanes
            for &parent_oid in &parent_oids[1..] {
                let existing = self
                    .active_lanes
                    .iter()
                    .position(|lane| *lane == Some(parent_oid));

                if existing.is_none() {
                    let new_col = self.find_free_lane();
                    if new_col < self.active_lanes.len() {
                        self.active_lanes[new_col] = Some(parent_oid);
                    } else {
                        self.active_lanes.push(Some(parent_oid));
                    }
                    // Extend lanes if needed
                    while lanes.len() <= new_col {
                        lanes.push(LaneSegment::Empty);
                    }
                    if new_col > commit_col {
                        lanes[new_col] = LaneSegment::ForkRight;
                        spans.push((commit_col, new_col, lane_color(new_col)));
                    } else {
                        lanes[new_col] = LaneSegment::ForkLeft;
                        spans.push((new_col, commit_col, lane_color(new_col)));
                    }
                }
            }
        }

        // Horizontal fill: connect merge/fork endpoints with ─ and ┼
        for &(left, right, _) in &spans {
            if lanes[left] == LaneSegment::Straight {
                lanes[left] = LaneSegment::RightTee;
            }
            if right < lanes.len() && lanes[right] == LaneSegment::Straight {
                lanes[right] = LaneSegment::LeftTee;
            }
            for col in (left + 1)..right {
                if col < lanes.len() {
                    if lanes[col] == LaneSegment::Straight {
                        lanes[col] = LaneSegment::CrossHorizontal;
                    } else if lanes[col] == LaneSegment::Empty {
                        lanes[col] = LaneSegment::Horizontal;
                    }
                }
            }
        }

        // Compact: remove trailing empty lanes
        while self.active_lanes.last() == Some(&None) {
            self.active_lanes.pop();
        }

        (commit_col, lanes, spans)
    }

    fn find_free_lane(&self) -> usize {
        self.active_lanes
            .iter()
            .position(|lane| lane.is_none())
            .unwrap_or(self.active_lanes.len())
    }
}

/// Assign a color index (0..PALETTE_SIZE) for a given lane column.
/// Adjacent lanes get different colors.
pub(crate) fn lane_color(col: usize) -> usize {
    col % PALETTE_SIZE
}