brain: Show history authors when space permits

1f98c19f14332f0fbc099b58f32e9afa311e7d10
Hide the author column when its natural table width would crowd the history
view.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 18fe8320
crates/brain/src/backend.rs +7 -3
45 45
pub struct Commit {
46 46
    /// Full Git commit hash.
47 47
    pub id: Oid,
48 48
    /// First line of the commit message.
49 49
    pub summary: String,
50 +
    /// Author name without an email address.
51 +
    pub author: String,
50 52
    /// Newest author or committer timestamp.
51 53
    pub recency: CommitTime,
52 54
    /// Aggregated diff size, shown in the commit list.
53 55
    pub stats: DiffStat,
54 56
}
67 69
        repository: &git::Repository,
68 70
        commits: Vec<(Oid, String)>,
69 71
    ) -> Result<Vec<Self>, Error> {
70 72
        let ids = commits.iter().map(|(id, _)| *id).collect::<Vec<_>>();
71 73
        let stats = repository.commit_stats(&ids)?;
72 -
        let recencies = repository.commit_recencies(&ids)?;
74 +
        let metadata = repository.commit_metadata(&ids)?;
73 75
74 76
        Ok(commits
75 77
            .into_iter()
76 78
            .zip(stats)
77 -
            .zip(recencies)
78 -
            .map(|(((id, summary), stats), recency)| Self {
79 +
            .zip(metadata)
80 +
            .map(|(((id, summary), stats), (author, recency))| Self {
79 81
                id,
80 82
                summary,
83 +
                author,
81 84
                recency,
82 85
                stats,
83 86
            })
84 87
            .collect())
85 88
    }
771 774
            .commits(base, target)?
772 775
            .into_iter()
773 776
            .map(|(id, summary)| Commit {
774 777
                id,
775 778
                summary,
779 +
                author: String::new(),
776 780
                recency: CommitTime::default(),
777 781
                stats: DiffStat::default(),
778 782
            });
779 783
        let mut summaries = Vec::with_capacity(commits.len());
780 784
f +0 -0
crates/brain/src/session.rs +38 -18
10 10
    FileTreeMode, HighlightOutput, HighlightRequest, Highlighter, ReviewProgress, ViewChange,
11 11
    spawn_highlighter,
12 12
};
13 13
use rustik_repo::DiffStat;
14 14
use rustik_tui::{
15 -
    Constraint, Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, Size, Style,
16 -
    Table, TableOptions, Terminal,
15 +
    Constraint, Control, Event, Key, Line, List, ListState, Mouse, MouseButton, Rect, ScrollView,
16 +
    Size, Style, Table, TableOptions, Terminal,
17 17
};
18 18
use rustik_tui_termion as tui_termion;
19 19
20 20
use crate::backend::{Backend, Brain, Commit, CommitHunks, FilePatches};
21 21
use crate::comments::ReviewComments;
29 29
30 30
use commit::{CommitReview, CommitSlot};
31 31
use event::{ContextFetch, Resize, TerminalEvent, Update, context_change};
32 32
use hunk::{CommentEdit, HunkView};
33 33
use status::{
34 -
    ActionContext, Chrome, SELECTED_COMMIT_BG, Status, StatusContext, commit_row, current_timestamp,
35 -
    viewer_area,
34 +
    ActionContext, Chrome, SELECTED_COMMIT_BG, Status, StatusContext, commit_row,
35 +
    commit_row_with_author, current_timestamp, viewer_area,
36 36
};
37 37
38 38
pub(crate) use status::{BRAIN_BADGE_BG, progress_bar};
39 39
40 40
/// Terminal backend used by the interactive viewer.
1015 1015
                })?;
1016 1016
            }
1017 1017
            Mode::Commits => {
1018 1018
                let palette = self.options.diff_palette;
1019 1019
                let now = current_timestamp();
1020 -
                let mut table = Table::<9, Line>::new(TableOptions {
1021 -
                    spacing: 2,
1022 -
                    ..TableOptions::default()
1023 -
                });
1024 1020
                let last = self.commits.len() - 1;
1025 -
                for (index, slot) in self.commits.iter().enumerate() {
1026 -
                    let graph = match (index, last) {
1027 -
                        (0, 0) => "──●",
1028 -
                        (0, _) => "╭─●",
1029 -
                        (index, last) if index == last => "╰─●",
1030 -
                        _ => "├─●",
1031 -
                    };
1032 -
                    table.push(commit_row(slot, palette, graph, now));
1033 -
                }
1034 1021
                self.terminal.draw(|frame| {
1035 1022
                    let (body, chrome_area) = Chrome::areas(frame.area);
1036 -
                    let rows = table.lines(Constraint::max(Size::new(body.cols, usize::MAX)));
1023 +
                    let cols = ScrollView::body_cols(body);
1024 +
                    let mut author_table = Table::<10, Line>::new(TableOptions {
1025 +
                        spacing: 2,
1026 +
                        ..TableOptions::default()
1027 +
                    });
1028 +
                    for (index, slot) in self.commits.iter().enumerate() {
1029 +
                        let graph = match (index, last) {
1030 +
                            (0, 0) => "──●",
1031 +
                            (0, _) => "╭─●",
1032 +
                            (index, last) if index == last => "╰─●",
1033 +
                            _ => "├─●",
1034 +
                        };
1035 +
                        author_table.push(commit_row_with_author(
1036 +
                            slot, palette, graph, now,
1037 +
                        ));
1038 +
                    }
1039 +
                    let rows = if author_table.size(Constraint::UNBOUNDED).cols <= cols {
1040 +
                        author_table.lines(Constraint::max(Size::new(cols, usize::MAX)))
1041 +
                    } else {
1042 +
                        let mut table = Table::<9, Line>::new(TableOptions {
1043 +
                            spacing: 2,
1044 +
                            ..TableOptions::default()
1045 +
                        });
1046 +
                        for (index, slot) in self.commits.iter().enumerate() {
1047 +
                            let graph = match (index, last) {
1048 +
                                (0, 0) => "──●",
1049 +
                                (0, _) => "╭─●",
1050 +
                                (index, last) if index == last => "╰─●",
1051 +
                                _ => "├─●",
1052 +
                            };
1053 +
                            table.push(commit_row(slot, palette, graph, now));
1054 +
                        }
1055 +
                        table.lines(Constraint::max(Size::new(cols, usize::MAX)))
1056 +
                    };
1037 1057
                    let selected = Style::default().bg(SELECTED_COMMIT_BG);
1038 1058
                    let list = List::new(rows)
1039 1059
                        .selected_styles(selected, selected)
1040 1060
                        .scrollbar(DiffViewer::scrollbar_style());
1041 1061
                    frame.render_stateful_widget(list, body, &mut self.list);
crates/brain/src/session/status.rs +43 -3
350 350
/// Returns the viewer area above the footer chrome.
351 351
pub(super) fn viewer_area(area: Rect) -> Rect {
352 352
    Chrome::areas(area).0
353 353
}
354 354
355 -
/// Returns one commit-table row ending with truncatable relative-time metadata.
355 +
/// Returns one commit-table row without an author column.
356 356
pub(super) fn commit_row(
357 357
    slot: &CommitSlot,
358 358
    palette: DiffPalette,
359 359
    graph: &str,
360 360
    now: u64,
361 361
) -> [Line; 9] {
362 +
    let [graph, id, summary, insertions, deletions, files, status, progress, _, age] =
363 +
        commit_row_with_author(slot, palette, graph, now);
364 +
365 +
    [
366 +
        graph, id, summary, insertions, deletions, files, status, progress, age,
367 +
    ]
368 +
}
369 +
370 +
/// Returns one commit-table row including an author column.
371 +
pub(super) fn commit_row_with_author(
372 +
    slot: &CommitSlot,
373 +
    palette: DiffPalette,
374 +
    graph: &str,
375 +
    now: u64,
376 +
) -> [Line; 10] {
362 377
    let stats = slot.commit.stats;
363 378
    let short = slot.commit.id.short();
364 379
    let status = if slot.progress.is_complete() {
365 380
        Label::from_char(REVIEWED_MARK).fg(palette.positive_fg)
366 381
    } else {
373 388
        Line::new(Label::new(&format!("+{}", stats.insertions)).fg(palette.positive_fg)),
374 389
        Line::new(Label::new(&format!("-{}", stats.deletions)).fg(palette.negative_fg)),
375 390
        Line::new(Label::new(&file_count(stats.files_changed)).fg(FOOTER_FG)),
376 391
        Line::new(status),
377 392
        progress_bar(slot.progress, palette, FOOTER_FG),
393 +
        Line::new(Label::new(slot.commit.author.as_str()).fg(colors::fixed::MUTED)),
378 394
        Line::new(
379 395
            Label::from(relative_time(
380 396
                slot.commit.recency.seconds.into(),
381 397
                now.into(),
382 398
            ))
589 605
            commit: Commit {
590 606
                id: "0123456789abcdef0123456789abcdef01234567"
591 607
                    .parse()
592 608
                    .unwrap(),
593 609
                summary: "A commit summary".to_owned(),
610 +
                author: "Alice".to_owned(),
594 611
                recency,
595 612
                stats: DiffStat {
596 613
                    files_changed: 1,
597 614
                    insertions: 2,
598 615
                    deletions: 3,
603 620
                total: 1,
604 621
            },
605 622
            loaded: None,
606 623
        };
607 624
        let age = relative_time(recency.seconds.into(), now.into());
608 -
        let mut table = Table::<9, Line>::new(TableOptions {
625 +
        let mut table = Table::<10, Line>::new(TableOptions {
609 626
            spacing: 2,
610 627
            ..TableOptions::default()
611 628
        });
612 -
        table.push(commit_row(&slot, DiffPalette::default(), "──●", now as u64));
629 +
        table.push(commit_row_with_author(
630 +
            &slot,
631 +
            DiffPalette::default(),
632 +
            "──●",
633 +
            now as u64,
634 +
        ));
613 635
        let pre_age_cols =
614 636
            table.size(Constraint::UNBOUNDED).cols - age.chars().count() - 2;
615 637
616 638
        let line = table
617 639
            .lines(Constraint::tight(pre_age_cols))
618 640
            .pop()
619 641
            .unwrap()
620 642
            .to_string();
621 643
622 644
        assert!(line.contains(REVIEWED_MARK), "line: {line:?}");
645 +
646 +
        let mut hidden = Table::<9, Line>::new(TableOptions {
647 +
            spacing: 2,
648 +
            ..TableOptions::default()
649 +
        });
650 +
        hidden.push(commit_row(&slot, DiffPalette::default(), "──●", now as u64));
651 +
        assert_eq!(
652 +
            table.size(Constraint::UNBOUNDED).cols,
653 +
            hidden.size(Constraint::UNBOUNDED).cols + "Alice".len() + 2
654 +
        );
655 +
        assert!(
656 +
            !hidden
657 +
                .lines(Constraint::UNBOUNDED)
658 +
                .pop()
659 +
                .unwrap()
660 +
                .to_string()
661 +
                .contains("Alice")
662 +
        );
623 663
    }
624 664
625 665
    #[test]
626 666
    fn comment_card_lines_render_a_bordered_comment_card() {
627 667
        let comment = Comment {
crates/repo/src/git.rs +24 -18
192 192
    pub fn commit_header(&self, commit: Oid) -> Result<Vec<u8>, RepoError> {
193 193
        let commit = commit.to_string();
194 194
        self.git("show", &["-s", "--format=medium", &commit])
195 195
    }
196 196
197 -
    /// Returns the newer author or committer timestamp for each commit.
198 -
    pub fn commit_recencies(&self, commits: &[Oid]) -> Result<Vec<CommitTime>, RepoError> {
197 +
    /// Returns each commit's author name and newest author or committer timestamp.
198 +
    pub fn commit_metadata(&self, commits: &[Oid]) -> Result<Vec<(String, CommitTime)>, RepoError> {
199 199
        if commits.is_empty() {
200 200
            return Ok(Vec::new());
201 201
        }
202 202
        let mut args = vec![
203 203
            "--no-walk=unsorted".to_owned(),
204 -
            "--format=%H%x00%at%x00%ct".to_owned(),
204 +
            "--format=%H%x00%an%x00%at%x00%ct".to_owned(),
205 205
        ];
206 206
        args.extend(commits.iter().map(Oid::to_string));
207 207
        let args = args.iter().map(String::as_str).collect::<Vec<_>>();
208 208
        let text = self.git("log", &args).and_then(utf8)?;
209 -
        let mut recencies = BTreeMap::new();
209 +
        let mut metadata = BTreeMap::new();
210 210
211 211
        for line in text.lines() {
212 -
            let (id, recency) = Self::parse_commit_recency(line)?;
213 -
            recencies.insert(id, recency);
212 +
            let (id, author, recency) = Self::parse_commit_metadata(line)?;
213 +
            metadata.insert(id, (author, recency));
214 214
        }
215 215
        commits
216 216
            .iter()
217 217
            .map(|commit| {
218 -
                recencies.get(commit).copied().ok_or_else(|| {
219 -
                    RepoError::Git(format!("git log omitted commit time for {commit}"))
220 -
                })
218 +
                metadata
219 +
                    .get(commit)
220 +
                    .cloned()
221 +
                    .ok_or_else(|| RepoError::Git(format!("git log omitted metadata for {commit}")))
221 222
            })
222 223
            .collect()
223 224
    }
224 225
225 -
    /// Parses one fixed three-field commit timestamp record from `git log`.
226 -
    fn parse_commit_recency(line: &str) -> Result<(Oid, CommitTime), RepoError> {
226 +
    /// Parses one fixed four-field commit metadata record from `git log`.
227 +
    fn parse_commit_metadata(line: &str) -> Result<(Oid, String, CommitTime), RepoError> {
227 228
        let mut fields = line.split('\0');
228 -
        let (Some(id), Some(authored), Some(committed), None) = (
229 +
        let (Some(id), Some(author), Some(authored), Some(committed), None) = (
230 +
            fields.next(),
229 231
            fields.next(),
230 232
            fields.next(),
231 233
            fields.next(),
232 234
            fields.next(),
233 235
        ) else {
234 236
            return Err(RepoError::Git(
235 -
                "malformed commit time line from git log".to_owned(),
237 +
                "malformed commit metadata line from git log".to_owned(),
236 238
            ));
237 239
        };
238 240
        let id = id
239 241
            .parse::<Oid>()
240 242
            .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?;
245 247
            .parse::<i64>()
246 248
            .map_err(|_| RepoError::Git("invalid commit timestamp from git log".to_owned()))?;
247 249
248 250
        Ok((
249 251
            id,
252 +
            author.to_owned(),
250 253
            CommitTime {
251 254
                seconds: authored.max(committed),
252 255
            },
253 256
        ))
254 257
    }
900 903
#[cfg(test)]
901 904
mod tests {
902 905
    use super::*;
903 906
904 907
    #[test]
905 -
    fn commit_recency_parses_three_fields() {
908 +
    fn commit_metadata_parses_four_fields() {
906 909
        let record = [
907 910
            "0123456789abcdef0123456789abcdef01234567",
911 +
            "Alice",
908 912
            "-10",
909 913
            "20",
910 914
        ]
911 915
        .join("\0");
912 -
        let (id, recency) = Repository::parse_commit_recency(&record).unwrap();
916 +
        let (id, author, recency) = Repository::parse_commit_metadata(&record).unwrap();
913 917
914 918
        assert_eq!(
915 919
            id,
916 920
            "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
917 921
        );
922 +
        assert_eq!(author, "Alice");
918 923
        assert_eq!(recency, CommitTime { seconds: 20 });
919 924
    }
920 925
921 926
    #[test]
922 -
    fn commit_recency_rejects_extra_fields() {
927 +
    fn commit_metadata_rejects_extra_fields() {
923 928
        let record = [
924 929
            "0123456789abcdef0123456789abcdef01234567",
930 +
            "Alice",
925 931
            "10",
926 932
            "20",
927 933
            "extra",
928 934
        ]
929 935
        .join("\0");
930 -
        let error = Repository::parse_commit_recency(&record).unwrap_err();
936 +
        let error = Repository::parse_commit_metadata(&record).unwrap_err();
931 937
932 938
        assert_eq!(
933 939
            error.to_string(),
934 -
            "malformed commit time line from git log"
940 +
            "malformed commit metadata line from git log"
935 941
        );
936 942
    }
937 943
}