//! Binary entry point for the `brain` code-review TUI. //! //! `brain diff ` opens an interactive review of the changes from the //! target branch's base commit. An explicit base can be supplied as //! `brain diff `. `brain comments` accepts the same revisions //! and prints the review's comments as JSONL. //! `brain status ` prints the same commit history without //! opening the interactive viewer. // `serde` is the local alias for the `microserde` crate; the derive macro // emits `microserde::*` paths so the original crate name must remain in scope. extern crate serde as microserde; mod backend; mod comments; mod decorate; mod error; mod review; mod session; use std::collections::BTreeMap; use std::env; use std::ffi::{OsStr, OsString}; use std::io::{self, Write as _}; use std::process::ExitCode; use std::sync::mpsc::{self, RecvTimeoutError}; use std::thread; use std::time::Duration; use lexopt::prelude::*; use rustik_diff::{Builtins, DiffOptions, DiffPalette, FileTreeMode, HunkFocus, progress_bar}; use rustik_repo::{AheadBehind, MergeStatus, Rev}; use rustik_tui::{ ActionList, Border, Color, Constraint, Dialog, Event, Key, Label, Line, Rect, Size, Style, Table, TableOptions, Terminal, colors, }; use rustik_tui_termion as tui_termion; use backend::{ BrainStatus, BrainStatusBaseState, BrainStatusHead, BrainStatusState, CommentStatus, }; use comments::{CommentId, CommentState, ReviewComments}; use error::Error; /// Terminal backend used by the interactive viewer. type BrainTerminal = Terminal>; /// Startup spinner repaint interval. const STARTUP_SPINNER_INTERVAL: Duration = Duration::from_millis(80); /// Startup spinner animation frames. const STARTUP_SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\']; /// Command-line usage text. const USAGE: &str = "usage: brain [status [--all]]\n brain status \n brain comments [--resolved] [] \n brain resolve [] \n brain [--reset|--rebase] diff [] "; /// Default output width used when terminal width is unknown. const DEFAULT_STATUS_WIDTH: usize = 140; /// Marker shown for approved review state: ✔. const APPROVED_STATUS_ICON: char = '✔'; /// Marker shown for in-review state: ●. const IN_REVIEW_STATUS_ICON: char = '●'; /// Marker shown when no brain state exists: ●. const NO_STATE_STATUS_ICON: char = '●'; /// Marker shown as the review-state table heading. const STATUS_HEADING_ICON: char = '○'; /// Thin neutral indicator shown when stored progress is stale. const STALE_PROGRESS_BAR: &str = "────────"; /// Parsed command-line arguments. #[derive(Debug, Eq, PartialEq)] struct Args { /// How persisted review state should be loaded. state: ReviewStateLoad, /// Command requested by the user. command: Command, } impl Args { /// Parses command-line arguments. fn parse(args: Vec) -> Result { let mut parser = lexopt::Parser::from_iter([OsString::from("brain")].into_iter().chain(args)); let mut state = ReviewStateLoad::Existing; let mut command = None; while let Some(arg) = parser.next()? { if command.is_some() { return Err(Error::Usage(format!( "unexpected argument: {arg:?}\n{USAGE}" ))); } match arg { Long("reset") => state = ReviewStateLoad::Fresh, Long("rebase") => state = ReviewStateLoad::Rebase, Value(command_name) if command_name == "status" => { command = match parser.next()? { Some(Long("all")) => Some(Command::Status { scope: StatusScope::All, }), Some(Value(base)) => { let base = parse_revision("base", base)?; let target = parse_revision("target", parser.value()?)?; Some(Command::RangeStatus { base, target }) } Some(_) => return Err(Error::Usage(USAGE.to_owned())), None => Some(Command::Status { scope: StatusScope::Reviews, }), }; } Value(command_name) if command_name == "comments" => { let state = match parser.next()? { Some(Long("resolved")) => CommentState::Resolved, Some(Value(first)) => { let (base, target) = parse_range(first, &mut parser)?; command = Some(Command::Comments { base, target, state: CommentState::Unresolved, }); continue; } _ => return Err(Error::Usage(USAGE.to_owned())), }; let first = parser.value()?; let (base, target) = parse_range(first, &mut parser)?; command = Some(Command::Comments { base, target, state, }); } Value(command_name) if command_name == "resolve" => { let id = parser .value()? .to_str() .and_then(|value| value.parse::().ok()) .map(CommentId::from) .ok_or_else(|| Error::Usage(USAGE.to_owned()))?; let first = parser.value()?; let (base, target) = parse_range(first, &mut parser)?; command = Some(Command::Resolve { id, base, target }); } Value(command_name) if command_name == "diff" => { let first = parser.value()?; let (base, target) = parse_range(first, &mut parser)?; command = Some(Command::Diff { base, target }); } Value(value) => { let value = value.to_string_lossy(); return Err(Error::Usage(format!("unknown command: {value}\n{USAGE}"))); } _ => return Err(Error::Usage(USAGE.to_owned())), } } if state != ReviewStateLoad::Existing && !matches!(command, Some(Command::Diff { .. })) { return Err(Error::Usage(USAGE.to_owned())); } Ok(Self { state, command: command.unwrap_or(Command::Status { scope: StatusScope::Reviews, }), }) } } /// Review command requested by the user. #[derive(Debug, Eq, PartialEq)] enum Command { /// Show review status for the selected branch scope. Status { /// Branch scope included in status output. scope: StatusScope, }, /// Print the commit history status for `base..target`. RangeStatus { /// Exclusive lower bound of the reviewed range. base: Rev, /// Inclusive upper bound of the reviewed range. target: Rev, }, /// Print comments with the selected resolution state for `base..target`. Comments { /// Exclusive lower bound of the reviewed range, when supplied. base: Option, /// Inclusive upper bound of the reviewed range. target: Rev, /// Resolution state included in the output. state: CommentState, }, /// Resolve one comment in the review of `base..target`. Resolve { /// Stable local comment id. id: CommentId, /// Exclusive lower bound of the reviewed range, when supplied. base: Option, /// Inclusive upper bound of the reviewed range. target: Rev, }, /// Review the commits in `base..target`. Diff { /// Exclusive lower bound of the reviewed range, when supplied. base: Option, /// Inclusive upper bound of the reviewed range. target: Rev, }, } /// Branch scope included in status output. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum StatusScope { /// Branches with stored review state. Reviews, /// Every branch, including branches without stored review state. All, } /// How the persisted review state should be loaded. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum ReviewStateLoad { /// Load existing state, prompting if it is stale. Existing, /// Replace existing state before starting the review. Fresh, /// Carry accepted hunks from stale state onto the current review base. Rebase, } /// Reviewer choice after stale state is found. #[derive(Clone, Copy, Debug, Eq, PartialEq)] enum StaleReviewStateAction { /// Carry accepted hunks onto the current review base. Rebase, /// Replace the stored state with empty state at the current base. Reset, /// Exit without changing stored state. Quit, } /// Dialog state shown before the review session can load. #[derive(Clone, Copy, Debug)] struct StaleReviewStatePrompt; impl StaleReviewStatePrompt { /// Creates the dialog widget for the current frame. fn dialog(self) -> Dialog { Dialog::error() .body([ Line::new("The existing review is stale."), Line::new("Its resolved commits no longer match this branch."), Line::blank(), Line::new("Rebasing carries matching accepted hunks forward."), Line::new("Changed or new hunks are left for review."), ]) .actions( ActionList::new() .action("↵", "rebase") .action("x", "reset") .action("esc", "quit"), ) .max_size(Size::new(78, 10)) } } /// Repository initialization command executed before the session starts. enum StartupCommand { /// Opens the requested review and loads existing state. Open { /// Working directory used for repository discovery. cwd: std::path::PathBuf, /// Explicit review base, when supplied. base: Option, /// Inclusive review target. target: Rev, /// Requested persisted-state policy. state: ReviewStateLoad, }, /// Resolves stale persisted state using the selected action. Resolve { /// Already-open revision backend. backend: Box, /// Stale-state resolution. action: StaleReviewStateAction, }, } /// Fully loaded inputs for the interactive review session. struct LoadedReview { /// Revision backend transferred to the session worker. backend: Box, /// Loaded hidden review state. brain: backend::Brain, /// Parsed review-wide comments. comments: ReviewComments, /// Commits in the reviewed range, oldest first. commits: Vec, } /// Result of one startup repository command. enum StartupOutput { /// Existing state is stale and requires a user decision. Stale(Box), /// Fully loaded inputs for the interactive session. Loaded(Box), } /// Executes one blocking startup command on a worker thread. fn execute_startup(command: StartupCommand) -> Result { let (backend, brain, commits) = match command { StartupCommand::Open { cwd, base, target, state, } => { let base = match base { Some(base) => base, None => backend::branch_base(&cwd, &target)?, }; let backend = ::from_path(&cwd, base, target)?; let commits = backend.commits()?; if commits.is_empty() { return Err(Error::Empty); } let brain = match state { ReviewStateLoad::Existing => match backend.brain() { Ok(brain) => brain, Err(Error::StaleReviewState) => return Ok(StartupOutput::Stale(backend)), Err(error) => return Err(error), }, ReviewStateLoad::Fresh => backend.reset_brain()?, ReviewStateLoad::Rebase => backend.rebase_brain()?, }; (backend, brain, commits) } StartupCommand::Resolve { backend, action } => { let commits = backend.commits()?; if commits.is_empty() { return Err(Error::Empty); } let brain = match action { StaleReviewStateAction::Rebase => backend.rebase_brain()?, StaleReviewStateAction::Reset => backend.reset_brain()?, StaleReviewStateAction::Quit => return Ok(StartupOutput::Stale(backend)), }; (backend, brain, commits) } }; let persisted = brain.read_comments()?; let mut comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?; if let Some(author) = brain.comment_author()? { comments.set_author(author); } Ok(StartupOutput::Loaded(Box::new(LoadedReview { backend, brain, comments, commits, }))) } /// Runs one startup command while animating the terminal status row. fn wait_for_startup( terminal: &mut BrainTerminal, command: StartupCommand, ) -> Result { let (sender, receiver) = mpsc::channel(); let worker = thread::spawn(move || { let _ = sender.send(execute_startup(command)); }); let mut frame = 0usize; loop { match receiver.recv_timeout(STARTUP_SPINNER_INTERVAL) { Ok(result) => { let _ = worker.join(); return result; } Err(RecvTimeoutError::Disconnected) => { let _ = worker.join(); return Err(Error::Git( "repository worker stopped unexpectedly".to_owned(), )); } Err(RecvTimeoutError::Timeout) => { let spinner = STARTUP_SPINNER_FRAMES[frame % STARTUP_SPINNER_FRAMES.len()]; if let Err(error) = terminal.draw(|terminal_frame| { let area = terminal_frame.area; let status = Rect::new(0, area.rows.saturating_sub(1), area.cols, 1); let line = Line::blank() .item(Label::from_char(spinner)) .item(Label::space()) .item(Label::new("loading review")); terminal_frame.render_widget(line, status); }) { let _ = worker.join(); return Err(error.into()); } frame = frame.wrapping_add(1); } } } } impl StaleReviewStatePrompt { /// Draws the prompt. fn draw(self, terminal: &mut BrainTerminal) -> Result<(), Error> { terminal.draw(|frame| { frame.render_widget(self.dialog(), frame.area); })?; Ok(()) } } /// Program entry point. fn main() -> ExitCode { match run(env::args_os().skip(1).collect()) { Ok(()) => ExitCode::SUCCESS, Err(error) => { let _ = writeln!(io::stderr(), "brain: {error}"); ExitCode::FAILURE } } } /// Parses arguments and dispatches the requested command. fn run(args: Vec) -> Result<(), Error> { let args = Args::parse(args)?; match args.command { Command::Status { scope } => run_status(scope), Command::RangeStatus { base, target } => run_range_status(base, target), Command::Comments { base, target, state, } => run_comments(base, target, state), Command::Resolve { id, base, target } => run_resolve(id, base, target), Command::Diff { base, target } => run_diff(args.state, base, target), } } /// Prints comments with the selected resolution state as JSONL. fn run_comments(base: Option, target: Rev, state: CommentState) -> Result<(), Error> { let cwd = env::current_dir()?; let base = match base { Some(base) => base, None => backend::branch_base(&cwd, &target)?, }; let backend = ::from_path(&cwd, base, target)?; let brain = backend.brain()?; let persisted = brain.read_comments()?; let comments = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?; if comments.len() == 0 { return Ok(()); } let mut lines = BTreeMap::new(); for commit in backend.commits()? { let document = backend.diff_document(commit.id)?.split_hunks(); let identities = brain.hunk_identities(&document, commit.id)?; for file in &document.files { for hunk in &file.hunks { let identity = identities .get(&hunk.id) .ok_or_else(|| Error::Git(format!("hunk {:?} has no identity", hunk.id)))?; lines .entry(identity.patch_id.clone()) .or_insert_with(BTreeMap::new) .insert(identity.ordinal, hunk.header.new_line_no); } } } let stdout = io::stdout(); comments.write_jsonl(stdout.lock(), state, |patch_id, ordinal| { lines .get(patch_id) .and_then(|occurrences| occurrences.get(&ordinal)) .copied() })?; Ok(()) } /// Resolves one comment in the selected review. fn run_resolve(id: CommentId, base: Option, target: Rev) -> Result<(), Error> { let cwd = env::current_dir()?; let base = match base { Some(base) => base, None => backend::branch_base(&cwd, &target)?, }; let backend = ::from_path(&cwd, base, target)?; let brain = backend.brain()?; let persisted = brain.read_comments()?; let previous = ReviewComments::parse(persisted.as_deref().unwrap_or_default())?; let mut updated = previous.clone(); if !updated.resolve(&id) { return Err(Error::CommentNotFound(id.as_u64())); } brain.merge_comments(&previous, &updated)?; Ok(()) } /// Loads the review range and runs the interactive diff session. fn run_diff(state: ReviewStateLoad, base: Option, target: Rev) -> Result<(), Error> { let cwd = env::current_dir()?; let mut terminal = open_terminal()?; terminal.clear()?; terminal.set_cursor_visible(false)?; let result: Result<(), Error> = (|| { let command = StartupCommand::Open { cwd: cwd.clone(), base, target, state, }; let events = session::Events::spawn(); let mut output = wait_for_startup(&mut terminal, command)?; events.discard_pending(); let (backend, brain, comments, commits) = loop { match output { StartupOutput::Loaded(loaded) => { let LoadedReview { backend, brain, comments, commits, } = *loaded; break (backend, brain, comments, commits); } StartupOutput::Stale(backend) => { let action = prompt_stale_review_state(&mut terminal, &events)?; if action == StaleReviewStateAction::Quit { return Ok(()); } terminal.clear()?; output = wait_for_startup( &mut terminal, StartupCommand::Resolve { backend, action }, )?; events.discard_pending(); } } }; let assets = Builtins::load().map_err(|error| Error::Highlight(error.to_string()))?; let root = cwd .file_name() .and_then(OsStr::to_str) .filter(|name| !name.is_empty()) .map(str::to_owned) .unwrap_or_else(|| cwd.display().to_string()); let options = DiffOptions { diff_palette: assets.palette, file_tree: FileTreeMode::Auto, file_tree_root: root, hunk_focus: HunkFocus::DimUnfocused, ..DiffOptions::default() }; events.discard_pending(); terminal.clear()?; session::run( &mut terminal, events, commits, backend, brain, comments, options, ) })(); let cursor = terminal.set_cursor_visible(true); result?; cursor.map_err(Error::Io) } /// Prints the history view for the commits in `base..target`. fn run_range_status(base: Rev, target: Rev) -> Result<(), Error> { let cwd = env::current_dir()?; let backend = ::from_path(&cwd, base, target)?; let commits = backend.commits()?; if commits.is_empty() { return Err(Error::Empty); } let brain = backend.brain()?; let comments = ReviewComments::parse(brain.read_comments()?.as_deref().unwrap_or_default())?; let width = status_width(); let table = session::history_output_table( commits, &*backend, &brain, &comments, DiffPalette::default(), width, )?; let mut stdout = io::stdout().lock(); for line in table.lines(Constraint::tight(width)) { writeln!(stdout, "{}", line.styled())?; } Ok(()) } /// Prints the stored review status table. fn run_status(scope: StatusScope) -> Result<(), Error> { let cwd = env::current_dir()?; let mut statuses = backend::statuses(&cwd)?; if scope == StatusScope::Reviews { statuses.retain(|status| status.state != BrainStatusState::NoState); } let mut stdout = io::stdout().lock(); for line in status_lines(&statuses, scope, status_width()) { writeln!(stdout, "{}", line.styled())?; } Ok(()) } /// Returns styled status output lines. fn status_lines(statuses: &[BrainStatus], scope: StatusScope, width: usize) -> Vec { if statuses.is_empty() { let empty = match scope { StatusScope::Reviews => "No reviews.", StatusScope::All => "No branches.", }; return vec![Line::new(Label::new(empty).fg(colors::fixed::DIM))]; } let palette = DiffPalette::default(); let mut table = Table::<6, Line>::new(TableOptions { border: Some(Border::new(colors::fixed::DIM)), ..TableOptions::bordered() }); table.header([ Line::new(Label::from_char(STATUS_HEADING_ICON).fg(colors::fixed::DIM)), status_heading("head"), status_heading("status"), status_heading("↖↘"), status_heading("comments"), status_heading("progress"), ]); table.divider(); for status in statuses { table.push([ brain_state(status.state), status_head(status), review_status(status), ahead_behind(status.relation), comment_status(status.comments), match (status.state, status.base_state) { (BrainStatusState::NoState, _) => Line::blank(), (_, BrainStatusBaseState::Stale) => { Line::new(Label::new(STALE_PROGRESS_BAR).fg(colors::fixed::DIM)) } _ => progress_bar(status.progress, palette, colors::fixed::DIM), }, ]); } table.lines(Constraint::max(Size::new(width, usize::MAX))) } /// Returns a styled review status cell. fn review_status(status: &BrainStatus) -> Line { match (status.base_state, status.merge) { (BrainStatusBaseState::Stale, _) => Line::new(Label::new("stale").fg(colors::fixed::DIM)), (_, MergeStatus::Conflicts) => { Line::new(Label::new("conflict").fg(colors::rgb::GREY_LIGHT)) } (_, MergeStatus::Clean) => Line::new(Label::new("ok").fg(colors::rgb::GREEN)), } } /// Returns a styled status head cell. fn status_head(status: &BrainStatus) -> Line { let color = match status.head_kind { BrainStatusHead::Branch => Color::Yellow, BrainStatusHead::Stored => Color::White, }; Line::new(Label::new(&status.head).fg(color)) } /// Returns a styled table heading cell. fn status_heading(text: &str) -> Line { Line::new(Label::new(text).style(Style::default().fg(colors::rgb::GREY_LIGHT).bold())) } /// Returns a styled brain state glyph cell. fn brain_state(state: BrainStatusState) -> Line { match state { BrainStatusState::Approved => { Line::new(Label::from_char(APPROVED_STATUS_ICON).fg(session::BRAIN_BADGE_BG)) } BrainStatusState::InReview => { Line::new(Label::from_char(IN_REVIEW_STATUS_ICON).fg(session::BRAIN_BADGE_BG)) } BrainStatusState::NoState => { Line::new(Label::from_char(NO_STATE_STATUS_ICON).fg(colors::fixed::DIM)) } } } /// Returns a styled ahead/behind cell. fn ahead_behind(relation: AheadBehind) -> Line { let ahead_color = if relation.ahead > 0 { colors::rgb::GREEN } else { colors::fixed::DIM }; let behind_color = if relation.behind > 0 { colors::rgb::RED } else { colors::fixed::DIM }; Line::new(Label::new("↖").fg(colors::fixed::DIM)) .item(Label::new(&format!("{:<2}", relation.ahead)).fg(ahead_color)) .item(Label::space()) .item(Label::new("↘").fg(colors::fixed::DIM)) .item(Label::new(&format!("{:<2}", relation.behind)).fg(behind_color)) } /// Returns a styled comment status cell. fn comment_status(status: CommentStatus) -> Line { match status { CommentStatus::None => Line::new(Label::new("-").fg(colors::fixed::DIM)), CommentStatus::Count(0) => Line::new(Label::new("0").fg(colors::fixed::DIM)), CommentStatus::Count(count) => { Line::new(Label::new(&count.to_string()).fg(colors::rgb::TEAL)) } CommentStatus::Invalid => Line::new(Label::new("invalid").fg(colors::rgb::RED)), } } /// Returns the target status table width. /// /// Falls back to `COLUMNS`, then a fixed width, when stdout is not a terminal. fn status_width() -> usize { tui_termion::term::viewport() .map(|size| size.cols) .or_else(|| { env::var("COLUMNS") .ok() .and_then(|value| value.parse().ok()) }) .filter(|width| *width > 0) .unwrap_or(DEFAULT_STATUS_WIDTH) } /// Parses the optional base and required target revisions following a command. fn parse_range(first: OsString, parser: &mut lexopt::Parser) -> Result<(Option, Rev), Error> { let first = parse_revision("target", first)?; match parser.next()? { Some(Value(target)) => { let target = parse_revision("target", target)?; Ok((Some(first), target)) } Some(_) => Err(Error::Usage(USAGE.to_owned())), None => Ok((None, first)), } } /// Parses one revision argument for the `diff` command. fn parse_revision(name: &str, value: OsString) -> Result { let value = value .to_str() .ok_or_else(|| Error::Usage(format!("{name} revision must be valid UTF-8")))?; Rev::try_from(value) .map_err(|error| Error::Usage(format!("{name} revision is invalid: {error}"))) } /// Opens the raw alternate-screen terminal. fn open_terminal() -> Result { let screen = tui_termion::term::screen()?; let terminal = Terminal::new(screen)?; Ok(terminal) } /// Prompts for how to handle stale hidden review state. fn prompt_stale_review_state( terminal: &mut BrainTerminal, events: &session::Events, ) -> Result { let prompt = StaleReviewStatePrompt; terminal.clear()?; terminal.set_cursor_visible(false)?; prompt.draw(terminal)?; while let Some(event) = events.next_input() { match event? { Event::Key(Key::Enter) => return Ok(StaleReviewStateAction::Rebase), Event::Key(Key::Char('x')) => return Ok(StaleReviewStateAction::Reset), Event::Key(Key::Esc | Key::Ctrl('c')) => { return Ok(StaleReviewStateAction::Quit); } Event::Resize(_) => prompt.draw(terminal)?, _ => {} } } Ok(StaleReviewStateAction::Quit) } #[cfg(test)] mod tests { use super::*; /// Returns a command-line argument vector. fn args(input: &[&str]) -> Vec { input.iter().map(OsString::from).collect() } #[test] fn parses_diff_command() { let parsed = Args::parse(args(&["diff", "main", "HEAD"])).unwrap(); assert_eq!( parsed, Args { state: ReviewStateLoad::Existing, command: Command::Diff { base: Some(Rev::try_from("main").unwrap()), target: Rev::try_from("HEAD").unwrap(), }, } ); } #[test] fn parses_single_revision_as_diff_target() { let parsed = Args::parse(args(&["diff", "feature"])).unwrap(); assert_eq!( parsed, Args { state: ReviewStateLoad::Existing, command: Command::Diff { base: None, target: Rev::try_from("feature").unwrap(), }, } ); } #[test] fn parses_comments_command_like_diff() { let parsed = Args::parse(args(&["comments", "feature"])).unwrap(); assert_eq!( parsed, Args { state: ReviewStateLoad::Existing, command: Command::Comments { base: None, target: Rev::try_from("feature").unwrap(), state: CommentState::Unresolved, }, } ); let parsed = Args::parse(args(&["comments", "main", "HEAD"])).unwrap(); assert_eq!( parsed.command, Command::Comments { base: Some(Rev::try_from("main").unwrap()), target: Rev::try_from("HEAD").unwrap(), state: CommentState::Unresolved, } ); } #[test] fn parses_resolved_comments_command() { let parsed = Args::parse(args(&["comments", "--resolved", "main", "HEAD"])).unwrap(); assert_eq!( parsed.command, Command::Comments { base: Some(Rev::try_from("main").unwrap()), target: Rev::try_from("HEAD").unwrap(), state: CommentState::Resolved, } ); } #[test] fn parses_resolve_command() { let parsed = Args::parse(args(&["resolve", "7", "main", "HEAD"])).unwrap(); assert_eq!( parsed.command, Command::Resolve { id: CommentId::from(7), base: Some(Rev::try_from("main").unwrap()), target: Rev::try_from("HEAD").unwrap(), } ); } #[test] fn parses_range_status_command() { let parsed = Args::parse(args(&["status", "main", "HEAD"])).unwrap(); assert_eq!( parsed.command, Command::RangeStatus { base: Rev::try_from("main").unwrap(), target: Rev::try_from("HEAD").unwrap(), } ); } #[test] fn parses_reset_flag_before_diff_command() { let parsed = Args::parse(args(&["--reset", "diff", "main", "HEAD"])).unwrap(); assert_eq!(parsed.state, ReviewStateLoad::Fresh); } #[test] fn parses_rebase_flag_before_diff_command() { let parsed = Args::parse(args(&["--rebase", "diff", "main", "HEAD"])).unwrap(); assert_eq!(parsed.state, ReviewStateLoad::Rebase); } #[test] fn parses_status_command() { let parsed = Args::parse(args(&["status"])).unwrap(); assert_eq!( parsed.command, Command::Status { scope: StatusScope::Reviews } ); } #[test] fn defaults_to_status_command() { let parsed = Args::parse(args(&[])).unwrap(); assert_eq!( parsed.command, Command::Status { scope: StatusScope::Reviews } ); } #[test] fn parses_all_status_command() { let parsed = Args::parse(args(&["status", "--all"])).unwrap(); assert_eq!( parsed.command, Command::Status { scope: StatusScope::All } ); } #[test] fn rejects_reset_without_diff_command() { let error = Args::parse(args(&["--reset"])).unwrap_err(); assert!(error.to_string().contains("usage: brain")); } #[test] fn rejects_rebase_without_diff_command() { let error = Args::parse(args(&["--rebase"])).unwrap_err(); assert!(error.to_string().contains("usage: brain")); } #[test] fn empty_status_reports_no_reviews() { assert_eq!( status_lines(&[], StatusScope::Reviews, 80)[0].to_string(), "No reviews." ); assert_eq!( status_lines(&[], StatusScope::All, 80)[0].to_string(), "No branches." ); } }