crates/brain/src/main.rs 29.2 KiB raw
1
//! Binary entry point for the `brain` code-review TUI.
2
//!
3
//! `brain diff <target>` opens an interactive review of the changes from the
4
//! target branch's base commit. An explicit base can be supplied as
5
//! `brain diff <base> <target>`. `brain comments` accepts the same revisions
6
//! and prints the review's comments as JSONL.
7
//! `brain status <base> <target>` prints the same commit history without
8
//! opening the interactive viewer.
9
10
// `serde` is the local alias for the `microserde` crate; the derive macro
11
// emits `microserde::*` paths so the original crate name must remain in scope.
12
extern crate serde as microserde;
13
14
mod backend;
15
mod comments;
16
mod decorate;
17
mod error;
18
mod review;
19
mod session;
20
21
use std::collections::BTreeMap;
22
use std::env;
23
use std::ffi::{OsStr, OsString};
24
use std::io::{self, Write as _};
25
use std::process::ExitCode;
26
use std::sync::mpsc::{self, RecvTimeoutError};
27
use std::thread;
28
use std::time::Duration;
29
30
use lexopt::prelude::*;
31
use rustik_diff::{Builtins, DiffOptions, DiffPalette, FileTreeMode, HunkFocus, progress_bar};
32
use rustik_repo::{AheadBehind, MergeStatus, Rev};
33
use rustik_tui::{
34
    ActionList, Border, Color, Constraint, Dialog, Event, Key, Label, Line, Rect, Size, Style,
35
    Table, TableOptions, Terminal, colors,
36
};
37
use rustik_tui_termion as tui_termion;
38
39
use backend::{
40
    BrainStatus, BrainStatusBaseState, BrainStatusHead, BrainStatusState, CommentStatus,
41
};
42
use comments::ReviewComments;
43
use error::Error;
44
45
/// Terminal backend used by the interactive viewer.
46
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
47
48
/// Startup spinner repaint interval.
49
const STARTUP_SPINNER_INTERVAL: Duration = Duration::from_millis(80);
50
/// Startup spinner animation frames.
51
const STARTUP_SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\'];
52
53
/// Command-line usage text.
54
const USAGE: &str = "usage: brain [status [--all]]\n       brain status <base> <target>\n       brain comments [<base>] <target>\n       brain [--reset|--rebase] diff [<base>] <target>";
55
/// Default output width used when terminal width is unknown.
56
const DEFAULT_STATUS_WIDTH: usize = 140;
57
/// Marker shown for approved review state: ✔.
58
const APPROVED_STATUS_ICON: char = '✔';
59
/// Marker shown for in-review state: ●.
60
const IN_REVIEW_STATUS_ICON: char = '●';
61
/// Marker shown when no brain state exists: ●.
62
const NO_STATE_STATUS_ICON: char = '●';
63
/// Marker shown as the review-state table heading.
64
const STATUS_HEADING_ICON: char = '○';
65
/// Thin neutral indicator shown when stored progress is stale.
66
const STALE_PROGRESS_BAR: &str = "────────";
67
68
/// Parsed command-line arguments.
69
#[derive(Debug, Eq, PartialEq)]
70
struct Args {
71
    /// How persisted review state should be loaded.
72
    state: ReviewStateLoad,
73
    /// Command requested by the user.
74
    command: Command,
75
}
76
77
impl Args {
78
    /// Parses command-line arguments.
79
    fn parse(args: Vec<OsString>) -> Result<Self, Error> {
80
        let mut parser =
81
            lexopt::Parser::from_iter([OsString::from("brain")].into_iter().chain(args));
82
        let mut state = ReviewStateLoad::Existing;
83
        let mut command = None;
84
85
        while let Some(arg) = parser.next()? {
86
            if command.is_some() {
87
                return Err(Error::Usage(format!(
88
                    "unexpected argument: {arg:?}\n{USAGE}"
89
                )));
90
            }
91
            match arg {
92
                Long("reset") => state = ReviewStateLoad::Fresh,
93
                Long("rebase") => state = ReviewStateLoad::Rebase,
94
                Value(command_name) if command_name == "status" => {
95
                    command = match parser.next()? {
96
                        Some(Long("all")) => Some(Command::Status {
97
                            scope: StatusScope::All,
98
                        }),
99
                        Some(Value(base)) => {
100
                            let base = parse_revision("base", base)?;
101
                            let target = parse_revision("target", parser.value()?)?;
102
                            Some(Command::RangeStatus { base, target })
103
                        }
104
                        Some(_) => return Err(Error::Usage(USAGE.to_owned())),
105
                        None => Some(Command::Status {
106
                            scope: StatusScope::Reviews,
107
                        }),
108
                    };
109
                }
110
                Value(command_name) if command_name == "comments" || command_name == "diff" => {
111
                    let first = parse_revision("target", parser.value()?)?;
112
                    let (base, target) = match parser.next()? {
113
                        Some(Value(target)) => {
114
                            let target = parse_revision("target", target)?;
115
                            (Some(first), target)
116
                        }
117
                        Some(_) => return Err(Error::Usage(USAGE.to_owned())),
118
                        None => (None, first),
119
                    };
120
121
                    command = Some(if command_name == "comments" {
122
                        Command::Comments { base, target }
123
                    } else {
124
                        Command::Diff { base, target }
125
                    });
126
                }
127
                Value(value) => {
128
                    let value = value.to_string_lossy();
129
                    return Err(Error::Usage(format!("unknown command: {value}\n{USAGE}")));
130
                }
131
                _ => return Err(Error::Usage(USAGE.to_owned())),
132
            }
133
        }
134
        if state != ReviewStateLoad::Existing && !matches!(command, Some(Command::Diff { .. })) {
135
            return Err(Error::Usage(USAGE.to_owned()));
136
        }
137
138
        Ok(Self {
139
            state,
140
            command: command.unwrap_or(Command::Status {
141
                scope: StatusScope::Reviews,
142
            }),
143
        })
144
    }
145
}
146
147
/// Review command requested by the user.
148
#[derive(Debug, Eq, PartialEq)]
149
enum Command {
150
    /// Show review status for the selected branch scope.
151
    Status {
152
        /// Branch scope included in status output.
153
        scope: StatusScope,
154
    },
155
    /// Print the commit history status for `base..target`.
156
    RangeStatus {
157
        /// Exclusive lower bound of the reviewed range.
158
        base: Rev,
159
        /// Inclusive upper bound of the reviewed range.
160
        target: Rev,
161
    },
162
    /// Print the comments for the review of `base..target`.
163
    Comments {
164
        /// Exclusive lower bound of the reviewed range, when supplied.
165
        base: Option<Rev>,
166
        /// Inclusive upper bound of the reviewed range.
167
        target: Rev,
168
    },
169
    /// Review the commits in `base..target`.
170
    Diff {
171
        /// Exclusive lower bound of the reviewed range, when supplied.
172
        base: Option<Rev>,
173
        /// Inclusive upper bound of the reviewed range.
174
        target: Rev,
175
    },
176
}
177
178
/// Branch scope included in status output.
179
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
180
enum StatusScope {
181
    /// Branches with stored review state.
182
    Reviews,
183
    /// Every branch, including branches without stored review state.
184
    All,
185
}
186
187
/// How the persisted review state should be loaded.
188
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
189
enum ReviewStateLoad {
190
    /// Load existing state, prompting if it is stale.
191
    Existing,
192
    /// Replace existing state before starting the review.
193
    Fresh,
194
    /// Carry accepted hunks from stale state onto the current review base.
195
    Rebase,
196
}
197
198
/// Reviewer choice after stale state is found.
199
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
200
enum StaleReviewStateAction {
201
    /// Carry accepted hunks onto the current review base.
202
    Rebase,
203
    /// Replace the stored state with empty state at the current base.
204
    Reset,
205
    /// Exit without changing stored state.
206
    Quit,
207
}
208
209
/// Dialog state shown before the review session can load.
210
#[derive(Clone, Copy, Debug)]
211
struct StaleReviewStatePrompt;
212
213
impl StaleReviewStatePrompt {
214
    /// Creates the dialog widget for the current frame.
215
    fn dialog(self) -> Dialog {
216
        Dialog::error()
217
            .body([
218
                Line::new("The existing review is stale."),
219
                Line::new("Its resolved commits no longer match this branch."),
220
                Line::blank(),
221
                Line::new("Rebasing carries matching accepted hunks forward."),
222
                Line::new("Changed or new hunks are left for review."),
223
            ])
224
            .actions(
225
                ActionList::new()
226
                    .action("↵", "rebase")
227
                    .action("x", "reset")
228
                    .action("esc", "quit"),
229
            )
230
            .max_size(Size::new(78, 10))
231
    }
232
}
233
234
/// Repository initialization command executed before the session starts.
235
enum StartupCommand {
236
    /// Opens the requested review and loads existing state.
237
    Open {
238
        /// Working directory used for repository discovery.
239
        cwd: std::path::PathBuf,
240
        /// Explicit review base, when supplied.
241
        base: Option<Rev>,
242
        /// Inclusive review target.
243
        target: Rev,
244
        /// Requested persisted-state policy.
245
        state: ReviewStateLoad,
246
    },
247
    /// Resolves stale persisted state using the selected action.
248
    Resolve {
249
        /// Already-open revision backend.
250
        backend: Box<dyn backend::Backend>,
251
        /// Stale-state resolution.
252
        action: StaleReviewStateAction,
253
    },
254
}
255
256
/// Fully loaded inputs for the interactive review session.
257
struct LoadedReview {
258
    /// Revision backend transferred to the session worker.
259
    backend: Box<dyn backend::Backend>,
260
    /// Loaded hidden review state.
261
    brain: backend::Brain,
262
    /// Parsed review-wide comments.
263
    comments: ReviewComments,
264
    /// Commits in the reviewed range, oldest first.
265
    commits: Vec<backend::Commit>,
266
}
267
268
/// Result of one startup repository command.
269
enum StartupOutput {
270
    /// Existing state is stale and requires a user decision.
271
    Stale(Box<dyn backend::Backend>),
272
    /// Fully loaded inputs for the interactive session.
273
    Loaded(Box<LoadedReview>),
274
}
275
276
/// Executes one blocking startup command on a worker thread.
277
fn execute_startup(command: StartupCommand) -> Result<StartupOutput, Error> {
278
    let (backend, brain) = match command {
279
        StartupCommand::Open {
280
            cwd,
281
            base,
282
            target,
283
            state,
284
        } => {
285
            let base = match base {
286
                Some(base) => base,
287
                None => backend::branch_base(&cwd, &target)?,
288
            };
289
            let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
290
            let brain = match state {
291
                ReviewStateLoad::Existing => match backend.brain() {
292
                    Ok(brain) => brain,
293
                    Err(Error::StaleReviewState) => return Ok(StartupOutput::Stale(backend)),
294
                    Err(error) => return Err(error),
295
                },
296
                ReviewStateLoad::Fresh => backend.reset_brain()?,
297
                ReviewStateLoad::Rebase => backend.rebase_brain()?,
298
            };
299
            (backend, brain)
300
        }
301
        StartupCommand::Resolve { backend, action } => {
302
            let brain = match action {
303
                StaleReviewStateAction::Rebase => backend.rebase_brain()?,
304
                StaleReviewStateAction::Reset => backend.reset_brain()?,
305
                StaleReviewStateAction::Quit => return Ok(StartupOutput::Stale(backend)),
306
            };
307
            (backend, brain)
308
        }
309
    };
310
    let persisted = brain.read_comments()?;
311
    let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
312
    let commits = backend.commits()?;
313
    if commits.is_empty() {
314
        return Err(Error::Empty);
315
    }
316
    Ok(StartupOutput::Loaded(Box::new(LoadedReview {
317
        backend,
318
        brain,
319
        comments,
320
        commits,
321
    })))
322
}
323
324
/// Runs one startup command while animating the terminal status row.
325
fn wait_for_startup(
326
    terminal: &mut BrainTerminal,
327
    command: StartupCommand,
328
) -> Result<StartupOutput, Error> {
329
    let (sender, receiver) = mpsc::channel();
330
    let worker = thread::spawn(move || {
331
        let _ = sender.send(execute_startup(command));
332
    });
333
    let mut frame = 0usize;
334
    loop {
335
        match receiver.recv_timeout(STARTUP_SPINNER_INTERVAL) {
336
            Ok(result) => {
337
                let _ = worker.join();
338
                return result;
339
            }
340
            Err(RecvTimeoutError::Disconnected) => {
341
                let _ = worker.join();
342
                return Err(Error::Git(
343
                    "repository worker stopped unexpectedly".to_owned(),
344
                ));
345
            }
346
            Err(RecvTimeoutError::Timeout) => {
347
                let spinner = STARTUP_SPINNER_FRAMES[frame % STARTUP_SPINNER_FRAMES.len()];
348
                if let Err(error) = terminal.draw(|terminal_frame| {
349
                    let area = terminal_frame.area;
350
                    let status = Rect::new(0, area.rows.saturating_sub(1), area.cols, 1);
351
                    let line = Line::blank()
352
                        .item(Label::from_char(spinner))
353
                        .item(Label::space())
354
                        .item(Label::new("loading review"));
355
                    terminal_frame.render_widget(line, status);
356
                }) {
357
                    let _ = worker.join();
358
                    return Err(error.into());
359
                }
360
                frame = frame.wrapping_add(1);
361
            }
362
        }
363
    }
364
}
365
366
impl StaleReviewStatePrompt {
367
    /// Draws the prompt.
368
    fn draw(self, terminal: &mut BrainTerminal) -> Result<(), Error> {
369
        terminal.draw(|frame| {
370
            frame.render_widget(self.dialog(), frame.area);
371
        })?;
372
        Ok(())
373
    }
374
}
375
376
/// Program entry point.
377
fn main() -> ExitCode {
378
    match run(env::args_os().skip(1).collect()) {
379
        Ok(()) => ExitCode::SUCCESS,
380
        Err(error) => {
381
            let _ = writeln!(io::stderr(), "brain: {error}");
382
            ExitCode::FAILURE
383
        }
384
    }
385
}
386
387
/// Parses arguments and dispatches the requested command.
388
fn run(args: Vec<OsString>) -> Result<(), Error> {
389
    let args = Args::parse(args)?;
390
    match args.command {
391
        Command::Status { scope } => run_status(scope),
392
        Command::RangeStatus { base, target } => run_range_status(base, target),
393
        Command::Comments { base, target } => run_comments(base, target),
394
        Command::Diff { base, target } => run_diff(args.state, base, target),
395
    }
396
}
397
398
/// Prints the selected review's comments as JSONL.
399
fn run_comments(base: Option<Rev>, target: Rev) -> Result<(), Error> {
400
    let cwd = env::current_dir()?;
401
    let base = match base {
402
        Some(base) => base,
403
        None => backend::branch_base(&cwd, &target)?,
404
    };
405
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
406
    let brain = backend.brain()?;
407
    let persisted = brain.read_comments()?;
408
    let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?;
409
    if comments.len() == 0 {
410
        return Ok(());
411
    }
412
413
    let mut lines = BTreeMap::new();
414
    for commit in backend.commits()? {
415
        let document = backend.diff_document(commit.id)?.split_hunks();
416
        let identities = brain.hunk_identities(&document, commit.id)?;
417
        for file in &document.files {
418
            for hunk in &file.hunks {
419
                let identity = identities
420
                    .get(&hunk.id)
421
                    .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?;
422
                lines
423
                    .entry(identity.patch_id.clone())
424
                    .or_insert_with(BTreeMap::new)
425
                    .insert(identity.ordinal, hunk.header.new_line_no);
426
            }
427
        }
428
    }
429
430
    let stdout = io::stdout();
431
    comments.write_jsonl(stdout.lock(), |patch_id, ordinal| {
432
        lines
433
            .get(patch_id)
434
            .and_then(|occurrences| occurrences.get(&ordinal))
435
            .copied()
436
    })?;
437
438
    Ok(())
439
}
440
441
/// Loads the review range and runs the interactive diff session.
442
fn run_diff(state: ReviewStateLoad, base: Option<Rev>, target: Rev) -> Result<(), Error> {
443
    let cwd = env::current_dir()?;
444
    let mut terminal = open_terminal()?;
445
    terminal.clear()?;
446
    terminal.set_cursor_visible(false)?;
447
448
    let result: Result<(), Error> = (|| {
449
        let command = StartupCommand::Open {
450
            cwd: cwd.clone(),
451
            base,
452
            target,
453
            state,
454
        };
455
        let events = session::Events::spawn();
456
        let mut output = wait_for_startup(&mut terminal, command)?;
457
        events.discard_pending();
458
        let (backend, brain, comments, commits) = loop {
459
            match output {
460
                StartupOutput::Loaded(loaded) => {
461
                    let LoadedReview {
462
                        backend,
463
                        brain,
464
                        comments,
465
                        commits,
466
                    } = *loaded;
467
                    break (backend, brain, comments, commits);
468
                }
469
                StartupOutput::Stale(backend) => {
470
                    let action = prompt_stale_review_state(&mut terminal, &events)?;
471
                    if action == StaleReviewStateAction::Quit {
472
                        return Ok(());
473
                    }
474
                    terminal.clear()?;
475
                    output = wait_for_startup(
476
                        &mut terminal,
477
                        StartupCommand::Resolve { backend, action },
478
                    )?;
479
                    events.discard_pending();
480
                }
481
            }
482
        };
483
484
        let assets = Builtins::load().map_err(|error| Error::Highlight(error.to_string()))?;
485
        let root = cwd
486
            .file_name()
487
            .and_then(OsStr::to_str)
488
            .filter(|name| !name.is_empty())
489
            .map(str::to_owned)
490
            .unwrap_or_else(|| cwd.display().to_string());
491
        let options = DiffOptions {
492
            diff_palette: assets.palette,
493
            file_tree: FileTreeMode::Auto,
494
            file_tree_root: root,
495
            hunk_focus: HunkFocus::DimUnfocused,
496
            ..DiffOptions::default()
497
        };
498
        events.discard_pending();
499
500
        terminal.clear()?;
501
        session::run(
502
            &mut terminal,
503
            events,
504
            commits,
505
            backend,
506
            brain,
507
            comments,
508
            options,
509
        )
510
    })();
511
    let cursor = terminal.set_cursor_visible(true);
512
    result?;
513
    cursor.map_err(Error::Io)
514
}
515
516
/// Prints the history view for the commits in `base..target`.
517
fn run_range_status(base: Rev, target: Rev) -> Result<(), Error> {
518
    let cwd = env::current_dir()?;
519
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
520
    let brain = backend.brain()?;
521
    let commits = backend.commits()?;
522
    if commits.is_empty() {
523
        return Err(Error::Empty);
524
    }
525
    let comments = ReviewComments::parse(brain.read_comments()?.as_deref().unwrap_or_default())?;
526
    let width = status_width();
527
    let table = session::history_output_table(
528
        commits,
529
        &*backend,
530
        &brain,
531
        &comments,
532
        DiffPalette::default(),
533
        width,
534
    )?;
535
    let mut stdout = io::stdout().lock();
536
    for line in table.lines(Constraint::tight(width)) {
537
        writeln!(stdout, "{}", line.styled())?;
538
    }
539
    Ok(())
540
}
541
542
/// Prints the stored review status table.
543
fn run_status(scope: StatusScope) -> Result<(), Error> {
544
    let cwd = env::current_dir()?;
545
    let mut statuses = backend::statuses(&cwd)?;
546
    if scope == StatusScope::Reviews {
547
        statuses.retain(|status| status.state != BrainStatusState::NoState);
548
    }
549
    let mut stdout = io::stdout().lock();
550
551
    for line in status_lines(&statuses, scope, status_width()) {
552
        writeln!(stdout, "{}", line.styled())?;
553
    }
554
    Ok(())
555
}
556
557
/// Returns styled status output lines.
558
fn status_lines(statuses: &[BrainStatus], scope: StatusScope, width: usize) -> Vec<Line> {
559
    if statuses.is_empty() {
560
        let empty = match scope {
561
            StatusScope::Reviews => "No reviews.",
562
            StatusScope::All => "No branches.",
563
        };
564
        return vec![Line::new(Label::new(empty).fg(colors::fixed::DIM))];
565
    }
566
567
    let palette = DiffPalette::default();
568
    let mut table = Table::<6, Line>::new(TableOptions {
569
        border: Some(Border::new(colors::fixed::DIM)),
570
        ..TableOptions::bordered()
571
    });
572
    table.header([
573
        Line::new(Label::from_char(STATUS_HEADING_ICON).fg(colors::fixed::DIM)),
574
        status_heading("head"),
575
        status_heading("status"),
576
        status_heading("↖↘"),
577
        status_heading("comments"),
578
        status_heading("progress"),
579
    ]);
580
    table.divider();
581
582
    for status in statuses {
583
        table.push([
584
            brain_state(status.state),
585
            status_head(status),
586
            review_status(status),
587
            ahead_behind(status.relation),
588
            comment_status(status.comments),
589
            match (status.state, status.base_state) {
590
                (BrainStatusState::NoState, _) => Line::blank(),
591
                (_, BrainStatusBaseState::Stale) => {
592
                    Line::new(Label::new(STALE_PROGRESS_BAR).fg(colors::fixed::DIM))
593
                }
594
                _ => progress_bar(status.progress, palette, colors::fixed::DIM),
595
            },
596
        ]);
597
    }
598
    table.lines(Constraint::max(Size::new(width, usize::MAX)))
599
}
600
601
/// Returns a styled review status cell.
602
fn review_status(status: &BrainStatus) -> Line {
603
    match (status.base_state, status.merge) {
604
        (BrainStatusBaseState::Stale, _) => Line::new(Label::new("stale").fg(colors::fixed::DIM)),
605
        (_, MergeStatus::Conflicts) => {
606
            Line::new(Label::new("conflict").fg(colors::rgb::GREY_LIGHT))
607
        }
608
        (_, MergeStatus::Clean) => Line::new(Label::new("ok").fg(colors::rgb::GREEN)),
609
    }
610
}
611
612
/// Returns a styled status head cell.
613
fn status_head(status: &BrainStatus) -> Line {
614
    let color = match status.head_kind {
615
        BrainStatusHead::Branch => Color::Yellow,
616
        BrainStatusHead::Stored => Color::White,
617
    };
618
    Line::new(Label::new(&status.head).fg(color))
619
}
620
621
/// Returns a styled table heading cell.
622
fn status_heading(text: &str) -> Line {
623
    Line::new(Label::new(text).style(Style::default().fg(colors::rgb::GREY_LIGHT).bold()))
624
}
625
626
/// Returns a styled brain state glyph cell.
627
fn brain_state(state: BrainStatusState) -> Line {
628
    match state {
629
        BrainStatusState::Approved => {
630
            Line::new(Label::from_char(APPROVED_STATUS_ICON).fg(session::BRAIN_BADGE_BG))
631
        }
632
        BrainStatusState::InReview => {
633
            Line::new(Label::from_char(IN_REVIEW_STATUS_ICON).fg(session::BRAIN_BADGE_BG))
634
        }
635
        BrainStatusState::NoState => {
636
            Line::new(Label::from_char(NO_STATE_STATUS_ICON).fg(colors::fixed::DIM))
637
        }
638
    }
639
}
640
641
/// Returns a styled ahead/behind cell.
642
fn ahead_behind(relation: AheadBehind) -> Line {
643
    let ahead_color = if relation.ahead > 0 {
644
        colors::rgb::GREEN
645
    } else {
646
        colors::fixed::DIM
647
    };
648
    let behind_color = if relation.behind > 0 {
649
        colors::rgb::RED
650
    } else {
651
        colors::fixed::DIM
652
    };
653
654
    Line::new(Label::new("↖").fg(colors::fixed::DIM))
655
        .item(Label::new(&format!("{:<2}", relation.ahead)).fg(ahead_color))
656
        .item(Label::space())
657
        .item(Label::new("↘").fg(colors::fixed::DIM))
658
        .item(Label::new(&format!("{:<2}", relation.behind)).fg(behind_color))
659
}
660
661
/// Returns a styled comment status cell.
662
fn comment_status(status: CommentStatus) -> Line {
663
    match status {
664
        CommentStatus::None => Line::new(Label::new("-").fg(colors::fixed::DIM)),
665
        CommentStatus::Count(0) => Line::new(Label::new("0").fg(colors::fixed::DIM)),
666
        CommentStatus::Count(count) => {
667
            Line::new(Label::new(&count.to_string()).fg(colors::rgb::TEAL))
668
        }
669
        CommentStatus::Invalid => Line::new(Label::new("invalid").fg(colors::rgb::RED)),
670
    }
671
}
672
673
/// Returns the target status table width.
674
///
675
/// Falls back to `COLUMNS`, then a fixed width, when stdout is not a terminal.
676
fn status_width() -> usize {
677
    tui_termion::term::viewport()
678
        .map(|size| size.cols)
679
        .or_else(|| {
680
            env::var("COLUMNS")
681
                .ok()
682
                .and_then(|value| value.parse().ok())
683
        })
684
        .filter(|width| *width > 0)
685
        .unwrap_or(DEFAULT_STATUS_WIDTH)
686
}
687
688
/// Parses one revision argument for the `diff` command.
689
fn parse_revision(name: &str, value: OsString) -> Result<Rev, Error> {
690
    let value = value
691
        .to_str()
692
        .ok_or_else(|| Error::Usage(format!("{name} revision must be valid UTF-8")))?;
693
    Rev::try_from(value)
694
        .map_err(|error| Error::Usage(format!("{name} revision is invalid: {error}")))
695
}
696
697
/// Opens the raw alternate-screen terminal.
698
fn open_terminal() -> Result<BrainTerminal, Error> {
699
    let screen = tui_termion::term::screen()?;
700
    let terminal = Terminal::new(screen)?;
701
    Ok(terminal)
702
}
703
704
/// Prompts for how to handle stale hidden review state.
705
fn prompt_stale_review_state(
706
    terminal: &mut BrainTerminal,
707
    events: &session::Events,
708
) -> Result<StaleReviewStateAction, Error> {
709
    let prompt = StaleReviewStatePrompt;
710
711
    terminal.clear()?;
712
    terminal.set_cursor_visible(false)?;
713
    prompt.draw(terminal)?;
714
715
    while let Some(event) = events.next_input() {
716
        match event? {
717
            Event::Key(Key::Enter) => return Ok(StaleReviewStateAction::Rebase),
718
            Event::Key(Key::Char('x')) => return Ok(StaleReviewStateAction::Reset),
719
            Event::Key(Key::Esc | Key::Ctrl('c')) => {
720
                return Ok(StaleReviewStateAction::Quit);
721
            }
722
            Event::Resize(_) => prompt.draw(terminal)?,
723
            _ => {}
724
        }
725
    }
726
    Ok(StaleReviewStateAction::Quit)
727
}
728
729
#[cfg(test)]
730
mod tests {
731
    use super::*;
732
733
    /// Returns a command-line argument vector.
734
    fn args(input: &[&str]) -> Vec<OsString> {
735
        input.iter().map(OsString::from).collect()
736
    }
737
738
    #[test]
739
    fn parses_diff_command() {
740
        let parsed = Args::parse(args(&["diff", "main", "HEAD"])).unwrap();
741
742
        assert_eq!(
743
            parsed,
744
            Args {
745
                state: ReviewStateLoad::Existing,
746
                command: Command::Diff {
747
                    base: Some(Rev::try_from("main").unwrap()),
748
                    target: Rev::try_from("HEAD").unwrap(),
749
                },
750
            }
751
        );
752
    }
753
754
    #[test]
755
    fn parses_single_revision_as_diff_target() {
756
        let parsed = Args::parse(args(&["diff", "feature"])).unwrap();
757
758
        assert_eq!(
759
            parsed,
760
            Args {
761
                state: ReviewStateLoad::Existing,
762
                command: Command::Diff {
763
                    base: None,
764
                    target: Rev::try_from("feature").unwrap(),
765
                },
766
            }
767
        );
768
    }
769
    #[test]
770
    fn parses_comments_command_like_diff() {
771
        let parsed = Args::parse(args(&["comments", "feature"])).unwrap();
772
773
        assert_eq!(
774
            parsed,
775
            Args {
776
                state: ReviewStateLoad::Existing,
777
                command: Command::Comments {
778
                    base: None,
779
                    target: Rev::try_from("feature").unwrap(),
780
                },
781
            }
782
        );
783
784
        let parsed = Args::parse(args(&["comments", "main", "HEAD"])).unwrap();
785
        assert_eq!(
786
            parsed.command,
787
            Command::Comments {
788
                base: Some(Rev::try_from("main").unwrap()),
789
                target: Rev::try_from("HEAD").unwrap(),
790
            }
791
        );
792
    }
793
794
    #[test]
795
    fn parses_range_status_command() {
796
        let parsed = Args::parse(args(&["status", "main", "HEAD"])).unwrap();
797
798
        assert_eq!(
799
            parsed.command,
800
            Command::RangeStatus {
801
                base: Rev::try_from("main").unwrap(),
802
                target: Rev::try_from("HEAD").unwrap(),
803
            }
804
        );
805
    }
806
807
    #[test]
808
    fn parses_reset_flag_before_diff_command() {
809
        let parsed = Args::parse(args(&["--reset", "diff", "main", "HEAD"])).unwrap();
810
811
        assert_eq!(parsed.state, ReviewStateLoad::Fresh);
812
    }
813
814
    #[test]
815
    fn parses_rebase_flag_before_diff_command() {
816
        let parsed = Args::parse(args(&["--rebase", "diff", "main", "HEAD"])).unwrap();
817
818
        assert_eq!(parsed.state, ReviewStateLoad::Rebase);
819
    }
820
821
    #[test]
822
    fn parses_status_command() {
823
        let parsed = Args::parse(args(&["status"])).unwrap();
824
        assert_eq!(
825
            parsed.command,
826
            Command::Status {
827
                scope: StatusScope::Reviews
828
            }
829
        );
830
    }
831
832
    #[test]
833
    fn defaults_to_status_command() {
834
        let parsed = Args::parse(args(&[])).unwrap();
835
        assert_eq!(
836
            parsed.command,
837
            Command::Status {
838
                scope: StatusScope::Reviews
839
            }
840
        );
841
    }
842
843
    #[test]
844
    fn parses_all_status_command() {
845
        let parsed = Args::parse(args(&["status", "--all"])).unwrap();
846
847
        assert_eq!(
848
            parsed.command,
849
            Command::Status {
850
                scope: StatusScope::All
851
            }
852
        );
853
    }
854
855
    #[test]
856
    fn rejects_reset_without_diff_command() {
857
        let error = Args::parse(args(&["--reset"])).unwrap_err();
858
859
        assert!(error.to_string().contains("usage: brain"));
860
    }
861
862
    #[test]
863
    fn rejects_rebase_without_diff_command() {
864
        let error = Args::parse(args(&["--rebase"])).unwrap_err();
865
866
        assert!(error.to_string().contains("usage: brain"));
867
    }
868
869
    #[test]
870
    fn empty_status_reports_no_reviews() {
871
        assert_eq!(
872
            status_lines(&[], StatusScope::Reviews, 80)[0].to_string(),
873
            "No reviews."
874
        );
875
        assert_eq!(
876
            status_lines(&[], StatusScope::All, 80)[0].to_string(),
877
            "No branches."
878
        );
879
    }
880
}