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