brain: Show relative commit time

18fe832088eb038dce5dfefbab51ea51256abf18
Use the newer author or committer timestamp so rewritten commits display their
latest meaningful activity.

Assisted-by: Codex:gpt-5.6-sol
Alexis Sellier committed ago 1 parent 8f4aebdc
crates/brain/src/backend.rs +18 -8
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 +
    /// Newest author or committer timestamp.
51 +
    pub recency: CommitTime,
50 52
    /// Aggregated diff size, shown in the commit list.
51 53
    pub stats: DiffStat,
52 54
}
53 55
54 56
impl Commit {
58 60
            OsString::from(format!("{}^", self.id)),
59 61
            OsString::from(self.id.to_string()),
60 62
        ]
61 63
    }
62 64
63 -
    /// Joins `(id, summary)` pairs with their bulk-fetched diff stats.
65 +
    /// Joins commit metadata with bulk-fetched diff stats and recency.
64 66
    fn with_stats(
65 -
        repository: &impl ReadRepository,
66 -
        pairs: Vec<(Oid, String)>,
67 +
        repository: &git::Repository,
68 +
        commits: Vec<(Oid, String)>,
67 69
    ) -> Result<Vec<Self>, Error> {
68 -
        let ids = pairs.iter().map(|(id, _)| *id).collect::<Vec<_>>();
70 +
        let ids = commits.iter().map(|(id, _)| *id).collect::<Vec<_>>();
69 71
        let stats = repository.commit_stats(&ids)?;
72 +
        let recencies = repository.commit_recencies(&ids)?;
70 73
71 -
        Ok(pairs
74 +
        Ok(commits
72 75
            .into_iter()
73 76
            .zip(stats)
74 -
            .map(|((id, summary), stats)| Self { id, summary, stats })
77 +
            .zip(recencies)
78 +
            .map(|(((id, summary), stats), recency)| Self {
79 +
                id,
80 +
                summary,
81 +
                recency,
82 +
                stats,
83 +
            })
75 84
            .collect())
76 85
    }
77 86
}
78 87
79 88
/// Exact identity of one accepted hunk.
762 771
            .commits(base, target)?
763 772
            .into_iter()
764 773
            .map(|(id, summary)| Commit {
765 774
                id,
766 775
                summary,
776 +
                recency: CommitTime::default(),
767 777
                stats: DiffStat::default(),
768 778
            });
769 779
        let mut summaries = Vec::with_capacity(commits.len());
770 780
771 781
        for commit in commits {
1276 1286
            deletions: stats.deletions,
1277 1287
        })
1278 1288
    }
1279 1289
1280 1290
    fn commits(&self) -> Result<Vec<Commit>, Error> {
1281 -
        let pairs = self.jj.commits(&self.review.base, &self.review.target)?;
1282 -
        Commit::with_stats(&self.repository, pairs)
1291 +
        let commits = self.jj.commits(&self.review.base, &self.review.target)?;
1292 +
        Commit::with_stats(&self.repository, commits)
1283 1293
    }
1284 1294
1285 1295
    fn commit_header(&self, commit: Oid) -> Result<CommitHeader, Error> {
1286 1296
        let bytes = self.repository.commit_header(commit)?;
1287 1297
        let document = DiffDocument::decode_bytes(&bytes)?;
f +0 -0
crates/brain/src/session.rs +5 -3
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, viewer_area,
34 +
    ActionContext, Chrome, SELECTED_COMMIT_BG, Status, StatusContext, commit_row, current_timestamp,
35 +
    viewer_area,
35 36
};
36 37
37 38
pub(crate) use status::{BRAIN_BADGE_BG, progress_bar};
38 39
39 40
/// Terminal backend used by the interactive viewer.
1013 1014
                    frame.render_widget(&mut chrome, chrome_area);
1014 1015
                })?;
1015 1016
            }
1016 1017
            Mode::Commits => {
1017 1018
                let palette = self.options.diff_palette;
1018 -
                let mut table = Table::<8, Line>::new(TableOptions {
1019 +
                let now = current_timestamp();
1020 +
                let mut table = Table::<9, Line>::new(TableOptions {
1019 1021
                    spacing: 2,
1020 1022
                    ..TableOptions::default()
1021 1023
                });
1022 1024
                let last = self.commits.len() - 1;
1023 1025
                for (index, slot) in self.commits.iter().enumerate() {
1025 1027
                        (0, 0) => "──●",
1026 1028
                        (0, _) => "╭─●",
1027 1029
                        (index, last) if index == last => "╰─●",
1028 1030
                        _ => "├─●",
1029 1031
                    };
1030 -
                    table.push(commit_row(slot, palette, graph));
1032 +
                    table.push(commit_row(slot, palette, graph, now));
1031 1033
                }
1032 1034
                self.terminal.draw(|frame| {
1033 1035
                    let (body, chrome_area) = Chrome::areas(frame.area);
1034 1036
                    let rows = table.lines(Constraint::max(Size::new(body.cols, usize::MAX)));
1035 1037
                    let selected = Style::default().bg(SELECTED_COMMIT_BG);
crates/brain/src/session/status.rs +88 -12
1 1
//! Status and chrome rendering for the review session.
2 2
3 +
use std::cmp::Ordering;
3 4
use std::time::{SystemTime, UNIX_EPOCH};
4 5
5 6
use rustik_diff::{DiffPalette, ReviewProgress};
6 7
use rustik_repo::DiffStat;
7 8
use rustik_tui::{
349 350
/// Returns the viewer area above the footer chrome.
350 351
pub(super) fn viewer_area(area: Rect) -> Rect {
351 352
    Chrome::areas(area).0
352 353
}
353 354
354 -
/// Returns one commit-table row with its graph lane, metadata, statistics, and progress.
355 -
pub(super) fn commit_row(slot: &CommitSlot, palette: DiffPalette, graph: &str) -> [Line; 8] {
355 +
/// Returns one commit-table row ending with truncatable relative-time metadata.
356 +
pub(super) fn commit_row(
357 +
    slot: &CommitSlot,
358 +
    palette: DiffPalette,
359 +
    graph: &str,
360 +
    now: u64,
361 +
) -> [Line; 9] {
356 362
    let stats = slot.commit.stats;
357 363
    let short = slot.commit.id.short();
358 364
    let status = if slot.progress.is_complete() {
359 365
        Label::from_char(REVIEWED_MARK).fg(palette.positive_fg)
360 366
    } else {
367 373
        Line::new(Label::new(&format!("+{}", stats.insertions)).fg(palette.positive_fg)),
368 374
        Line::new(Label::new(&format!("-{}", stats.deletions)).fg(palette.negative_fg)),
369 375
        Line::new(Label::new(&file_count(stats.files_changed)).fg(FOOTER_FG)),
370 376
        Line::new(status),
371 377
        progress_bar(slot.progress, palette, FOOTER_FG),
378 +
        Line::new(
379 +
            Label::from(relative_time(
380 +
                slot.commit.recency.seconds.into(),
381 +
                now.into(),
382 +
            ))
383 +
            .fg(colors::fixed::DIM),
384 +
        ),
372 385
    ]
373 386
}
374 387
375 388
/// Renders one stored comment as a bordered card.
376 389
pub(super) fn comment_card_lines(comment: &Comment, selected: bool, cols: usize) -> Vec<Line> {
412 425
    table.lines(Constraint::tight(cols))
413 426
}
414 427
415 428
/// Returns a comment's age as a human relative timestamp.
416 429
pub(super) fn comment_age(comment: &Comment) -> String {
417 -
    relative_time(comment.timestamp, current_timestamp())
430 +
    relative_time(comment.timestamp.into(), current_timestamp().into())
418 431
}
419 432
420 433
/// Returns the comment-card content width: the rendered width minus the
421 434
/// border and padding columns on both sides.
422 435
fn comment_table_content_width(cols: usize) -> usize {
431 444
    ])
432 445
    .padded(body_width)
433 446
}
434 447
435 448
/// Returns a human relative timestamp in the largest whole unit.
436 -
fn relative_time(timestamp: u64, now: u64) -> String {
449 +
fn relative_time(timestamp: i128, now: i128) -> String {
437 450
    /// Time units from largest to smallest, as seconds and unit name.
438 -
    const UNITS: [(u64, &str); 5] = [
451 +
    const UNITS: [(u128, &str); 5] = [
439 452
        (31_536_000, "year"),
440 453
        (2_592_000, "month"),
441 454
        (86_400, "day"),
442 455
        (3_600, "hour"),
443 456
        (60, "minute"),
444 457
    ];
445 -
    let elapsed = now.saturating_sub(timestamp);
458 +
    let direction = timestamp.cmp(&now);
459 +
    let elapsed = timestamp.abs_diff(now);
460 +
446 461
    for (seconds, unit) in UNITS {
447 -
        match elapsed / seconds {
448 -
            0 => continue,
449 -
            1 => return format!("1 {unit} ago"),
450 -
            count => return format!("{count} {unit}s ago"),
462 +
        match (direction, elapsed / seconds) {
463 +
            (_, 0) => continue,
464 +
            (Ordering::Greater, 1) => return format!("in 1 {unit}"),
465 +
            (Ordering::Greater, count) => return format!("in {count} {unit}s"),
466 +
            (_, 1) => return format!("1 {unit} ago"),
467 +
            (_, count) => return format!("{count} {unit}s ago"),
451 468
        }
452 469
    }
453 -
    "just now".to_owned()
470 +
    if direction == Ordering::Greater {
471 +
        "in less than a minute".to_owned()
472 +
    } else {
473 +
        "just now".to_owned()
474 +
    }
454 475
}
455 476
456 477
/// Returns the current Unix timestamp.
457 -
fn current_timestamp() -> u64 {
478 +
pub(super) fn current_timestamp() -> u64 {
458 479
    SystemTime::now()
459 480
        .duration_since(UNIX_EPOCH)
460 481
        .unwrap_or_default()
461 482
        .as_secs()
462 483
}
463 484
464 485
#[cfg(test)]
465 486
mod tests {
466 487
    use super::*;
467 488
489 +
    use crate::backend::Commit;
490 +
    use rustik_repo::CommitTime;
491 +
468 492
    #[test]
469 493
    fn viewer_area_reserves_footer() {
470 494
        assert_eq!(
471 495
            viewer_area(Rect::new(0, 0, 80, 20)),
472 496
            Rect::new(0, 0, 80, 18)
553 577
        assert_eq!(buffer.get(78, 0).unwrap().glyph(), FULL_FILE_MODE_ICON);
554 578
        assert_eq!(buffer.get(79, 0).unwrap().glyph(), " ");
555 579
        assert_eq!(buffer.get(79, 0).unwrap().style().bg_color(), FOOTER_BG);
556 580
    }
557 581
582 +
    #[test]
583 +
    fn commit_row_keeps_review_status_at_pre_age_width() {
584 +
        let now = 2_000_000_000;
585 +
        let recency = CommitTime {
586 +
            seconds: now - 3_600,
587 +
        };
588 +
        let slot = CommitSlot {
589 +
            commit: Commit {
590 +
                id: "0123456789abcdef0123456789abcdef01234567"
591 +
                    .parse()
592 +
                    .unwrap(),
593 +
                summary: "A commit summary".to_owned(),
594 +
                recency,
595 +
                stats: DiffStat {
596 +
                    files_changed: 1,
597 +
                    insertions: 2,
598 +
                    deletions: 3,
599 +
                },
600 +
            },
601 +
            progress: ReviewProgress {
602 +
                accepted: 1,
603 +
                total: 1,
604 +
            },
605 +
            loaded: None,
606 +
        };
607 +
        let age = relative_time(recency.seconds.into(), now.into());
608 +
        let mut table = Table::<9, Line>::new(TableOptions {
609 +
            spacing: 2,
610 +
            ..TableOptions::default()
611 +
        });
612 +
        table.push(commit_row(&slot, DiffPalette::default(), "──●", now as u64));
613 +
        let pre_age_cols =
614 +
            table.size(Constraint::UNBOUNDED).cols - age.chars().count() - 2;
615 +
616 +
        let line = table
617 +
            .lines(Constraint::tight(pre_age_cols))
618 +
            .pop()
619 +
            .unwrap()
620 +
            .to_string();
621 +
622 +
        assert!(line.contains(REVIEWED_MARK), "line: {line:?}");
623 +
    }
624 +
558 625
    #[test]
559 626
    fn comment_card_lines_render_a_bordered_comment_card() {
560 627
        let comment = Comment {
561 628
            id: 1.into(),
562 629
            author: "alice".to_owned(),
604 671
        assert_eq!(relative_time(now - 3_600, now), "1 hour ago");
605 672
        assert_eq!(relative_time(now - 86_400, now), "1 day ago");
606 673
        assert_eq!(relative_time(now - 2_592_000, now), "1 month ago");
607 674
        assert_eq!(relative_time(now - 31_536_000, now), "1 year ago");
608 675
    }
676 +
677 +
    #[test]
678 +
    fn relative_time_preserves_future_direction() {
679 +
        let now = 2_000_000_000;
680 +
681 +
        assert_eq!(relative_time(now + 1, now), "in less than a minute");
682 +
        assert_eq!(relative_time(now + 60, now), "in 1 minute");
683 +
        assert_eq!(relative_time(now + 7_200, now), "in 2 hours");
684 +
    }
609 685
}
crates/repo/src/git.rs +98 -0
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> {
199 +
        if commits.is_empty() {
200 +
            return Ok(Vec::new());
201 +
        }
202 +
        let mut args = vec![
203 +
            "--no-walk=unsorted".to_owned(),
204 +
            "--format=%H%x00%at%x00%ct".to_owned(),
205 +
        ];
206 +
        args.extend(commits.iter().map(Oid::to_string));
207 +
        let args = args.iter().map(String::as_str).collect::<Vec<_>>();
208 +
        let text = self.git("log", &args).and_then(utf8)?;
209 +
        let mut recencies = BTreeMap::new();
210 +
211 +
        for line in text.lines() {
212 +
            let (id, recency) = Self::parse_commit_recency(line)?;
213 +
            recencies.insert(id, recency);
214 +
        }
215 +
        commits
216 +
            .iter()
217 +
            .map(|commit| {
218 +
                recencies.get(commit).copied().ok_or_else(|| {
219 +
                    RepoError::Git(format!("git log omitted commit time for {commit}"))
220 +
                })
221 +
            })
222 +
            .collect()
223 +
    }
224 +
225 +
    /// Parses one fixed three-field commit timestamp record from `git log`.
226 +
    fn parse_commit_recency(line: &str) -> Result<(Oid, CommitTime), RepoError> {
227 +
        let mut fields = line.split('\0');
228 +
        let (Some(id), Some(authored), Some(committed), None) = (
229 +
            fields.next(),
230 +
            fields.next(),
231 +
            fields.next(),
232 +
            fields.next(),
233 +
        ) else {
234 +
            return Err(RepoError::Git(
235 +
                "malformed commit time line from git log".to_owned(),
236 +
            ));
237 +
        };
238 +
        let id = id
239 +
            .parse::<Oid>()
240 +
            .map_err(|_| RepoError::Git("invalid oid from git log".to_owned()))?;
241 +
        let authored = authored
242 +
            .parse::<i64>()
243 +
            .map_err(|_| RepoError::Git("invalid author timestamp from git log".to_owned()))?;
244 +
        let committed = committed
245 +
            .parse::<i64>()
246 +
            .map_err(|_| RepoError::Git("invalid commit timestamp from git log".to_owned()))?;
247 +
248 +
        Ok((
249 +
            id,
250 +
            CommitTime {
251 +
                seconds: authored.max(committed),
252 +
            },
253 +
        ))
254 +
    }
255 +
197 256
    /// Runs a Git subcommand with optional stdin, index, and environment overrides.
198 257
    fn run(&self, subcommand: &str, args: &[&str], opts: Opts<'_>) -> Result<Output, RepoError> {
199 258
        let mut command = self.command(subcommand);
200 259
        command.args(args);
201 260
835 894
    if bytes.last() == Some(&b'\r') {
836 895
        bytes.pop();
837 896
    }
838 897
    Ok(Some(String::from_utf8_lossy(&bytes).into_owned()))
839 898
}
899 +
900 +
#[cfg(test)]
901 +
mod tests {
902 +
    use super::*;
903 +
904 +
    #[test]
905 +
    fn commit_recency_parses_three_fields() {
906 +
        let record = [
907 +
            "0123456789abcdef0123456789abcdef01234567",
908 +
            "-10",
909 +
            "20",
910 +
        ]
911 +
        .join("\0");
912 +
        let (id, recency) = Repository::parse_commit_recency(&record).unwrap();
913 +
914 +
        assert_eq!(
915 +
            id,
916 +
            "0123456789abcdef0123456789abcdef01234567".parse().unwrap()
917 +
        );
918 +
        assert_eq!(recency, CommitTime { seconds: 20 });
919 +
    }
920 +
921 +
    #[test]
922 +
    fn commit_recency_rejects_extra_fields() {
923 +
        let record = [
924 +
            "0123456789abcdef0123456789abcdef01234567",
925 +
            "10",
926 +
            "20",
927 +
            "extra",
928 +
        ]
929 +
        .join("\0");
930 +
        let error = Repository::parse_commit_recency(&record).unwrap_err();
931 +
932 +
        assert_eq!(
933 +
            error.to_string(),
934 +
            "malformed commit time line from git log"
935 +
        );
936 +
    }
937 +
}