brain: Infer base for single diff target

59aef797feff847b3f9fff616dd0c75fc2384326
Treat a single diff argument as the target revision and derive its
branch point from the configured upstream or trunk.

Assisted-by: Codex:gpt-5.6
Alexis Sellier committed ago 1 parent 4b4a734b
crates/brain/src/backend.rs +15 -0
576 576
            Ok(Box::new(backend))
577 577
        }
578 578
    }
579 579
}
580 580
581 +
/// Returns the branch point for the branch containing `target`.
582 +
pub fn branch_base(cwd: &Path, target: &Rev) -> Result<Rev, Error> {
583 +
    if is_jj_workspace(cwd) {
584 +
        let base = jj::Repository::new(cwd).branch_base(target)?;
585 +
        return Ok(Rev::from(base));
586 +
    }
587 +
    let repository = open_repository(cwd)?;
588 +
    let base = repository.branch_base(target)?.ok_or_else(|| {
589 +
        Error::Git(
590 +
            "could not infer a base for the target; supply an explicit base revision".to_owned(),
591 +
        )
592 +
    })?;
593 +
    Ok(Rev::from(base))
594 +
}
595 +
581 596
/// Returns stored review statuses for the repository containing `cwd`.
582 597
pub fn statuses(cwd: &Path) -> Result<Vec<BrainStatus>, Error> {
583 598
    let repository = open_repository(cwd)?;
584 599
    Brain::statuses(&repository)
585 600
}
f +0 -0
new.rs +0 -0
image.png +0 -0
crates/brain/src/main.rs +29 -23
1 1
//! Binary entry point for the `brain` code-review TUI.
2 2
//!
3 -
//! `brain diff <from> [<to>]` opens an interactive review of the changes between
4 -
//! two revisions. The upper revision defaults to `HEAD`. The reviewer accepts
5 -
//! hunks one by one; accepted hunks are hidden by default and can be revealed
6 -
//! for inspection.
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>`.
7 6
8 7
// `serde` is the local alias for the `microserde` crate; the derive macro
9 8
// emits `microserde::*` paths so the original crate name must remain in scope.
10 9
extern crate serde as microserde;
11 10
38 37
39 38
/// Terminal backend used by the interactive viewer.
40 39
type BrainTerminal = Terminal<tui_termion::TermionBackend<tui_termion::term::TerminalScreen>>;
41 40
42 41
/// Command-line usage text.
43 -
const USAGE: &str = "usage: brain [status]\n       brain [--reset|--rebase] diff <from> [<to>]";
42 +
const USAGE: &str = "usage: brain [status]\n       brain [--reset|--rebase] diff [<base>] <target>";
44 43
/// Default output width used when terminal width is unknown.
45 44
const DEFAULT_STATUS_WIDTH: usize = 140;
46 45
/// Marker shown for approved review state: โœ”.
47 46
const APPROVED_STATUS_ICON: char = 'โœ”';
48 47
/// Marker shown for in-review state: โ—.
80 79
                Long("rebase") => state = ReviewStateLoad::Rebase,
81 80
                Value(command_name) if command_name == "status" => {
82 81
                    command = Some(Command::Status);
83 82
                }
84 83
                Value(command_name) if command_name == "diff" => {
85 -
                    let from = parse_revision("from", parser.value()?)?;
86 -
                    let to = match parser.next()? {
87 -
                        Some(Value(to)) => parse_revision("to", to)?,
84 +
                    let first = parse_revision("target", parser.value()?)?;
85 +
                    let (base, target) = match parser.next()? {
86 +
                        Some(Value(target)) => {
87 +
                            let target = parse_revision("target", target)?;
88 +
                            (Some(first), target)
89 +
                        }
88 90
                        Some(_) => return Err(Error::Usage(USAGE.to_owned())),
89 -
                        None => parse_revision("to", OsString::from("HEAD"))?,
91 +
                        None => (None, first),
90 92
                    };
91 93
92 -
                    command = Some(Command::Diff { from, to });
94 +
                    command = Some(Command::Diff { base, target });
93 95
                }
94 96
                Value(value) => {
95 97
                    let value = value.to_string_lossy();
96 98
                    return Err(Error::Usage(format!("unknown command: {value}\n{USAGE}")));
97 99
                }
112 114
/// Review command requested by the user.
113 115
#[derive(Debug, Eq, PartialEq)]
114 116
enum Command {
115 117
    /// Show stored review state.
116 118
    Status,
117 -
    /// Review the commits in `from..to`.
119 +
    /// Review the commits in `base..target`.
118 120
    Diff {
119 -
        /// Exclusive lower bound of the reviewed range.
120 -
        from: Rev,
121 +
        /// Exclusive lower bound of the reviewed range, when supplied.
122 +
        base: Option<Rev>,
121 123
        /// Inclusive upper bound of the reviewed range.
122 -
        to: Rev,
124 +
        target: Rev,
123 125
    },
124 126
}
125 127
126 128
/// How the persisted review state should be loaded.
127 129
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
192 194
/// Parses arguments and dispatches the requested command.
193 195
fn run(args: Vec<OsString>) -> Result<(), Error> {
194 196
    let args = Args::parse(args)?;
195 197
    match args.command {
196 198
        Command::Status => run_status(),
197 -
        Command::Diff { from, to } => run_diff(args.state, from, to),
199 +
        Command::Diff { base, target } => run_diff(args.state, base, target),
198 200
    }
199 201
}
200 202
201 203
/// Loads the review range and runs the interactive diff session.
202 -
fn run_diff(state: ReviewStateLoad, from: Rev, to: Rev) -> Result<(), Error> {
204 +
fn run_diff(state: ReviewStateLoad, base: Option<Rev>, target: Rev) -> Result<(), Error> {
203 205
    let cwd = env::current_dir()?;
204 -
    let backend = <dyn backend::Backend>::from_path(&cwd, from, to)?;
206 +
    let base = match base {
207 +
        Some(base) => base,
208 +
        None => backend::branch_base(&cwd, &target)?,
209 +
    };
210 +
    let backend = <dyn backend::Backend>::from_path(&cwd, base, target)?;
205 211
    let mut terminal = None;
206 212
    let mut events = None;
207 213
    let brain = match state {
208 214
        ReviewStateLoad::Existing => match backend.brain() {
209 215
            Ok(brain) => brain,
467 473
        assert_eq!(
468 474
            parsed,
469 475
            Args {
470 476
                state: ReviewStateLoad::Existing,
471 477
                command: Command::Diff {
472 -
                    from: Rev::try_from("main").unwrap(),
473 -
                    to: Rev::try_from("HEAD").unwrap(),
478 +
                    base: Some(Rev::try_from("main").unwrap()),
479 +
                    target: Rev::try_from("HEAD").unwrap(),
474 480
                },
475 481
            }
476 482
        );
477 483
    }
478 484
479 485
    #[test]
480 -
    fn defaults_diff_to_head() {
481 -
        let parsed = Args::parse(args(&["diff", "main"])).unwrap();
486 +
    fn parses_single_revision_as_diff_target() {
487 +
        let parsed = Args::parse(args(&["diff", "feature"])).unwrap();
482 488
483 489
        assert_eq!(
484 490
            parsed,
485 491
            Args {
486 492
                state: ReviewStateLoad::Existing,
487 493
                command: Command::Diff {
488 -
                    from: Rev::try_from("main").unwrap(),
489 -
                    to: Rev::try_from("HEAD").unwrap(),
494 +
                    base: None,
495 +
                    target: Rev::try_from("feature").unwrap(),
490 496
                },
491 497
            }
492 498
        );
493 499
    }
494 500
crates/repo/src/git.rs +109 -0
429 429
                    .find(|branch| branch.name == refs::name::str::MASTER)
430 430
            })
431 431
            .cloned())
432 432
    }
433 433
434 +
    /// Returns the best common ancestor of two revisions.
435 +
    fn merge_base(&self, left: &Rev, right: &Rev) -> Result<Oid, RepoError> {
436 +
        let bytes = self.git("merge-base", &[left.as_str(), right.as_str()])?;
437 +
        let text = utf8(bytes)?;
438 +
        text.trim()
439 +
            .parse()
440 +
            .map_err(|_| RepoError::Git("invalid merge base".to_owned()))
441 +
    }
442 +
443 +
    /// Returns the branch point for `target` and its upstream or the trunk.
444 +
    fn branch_base(&self, target: &Rev) -> Result<Option<Oid>, RepoError> {
445 +
        let target_id = self.commit_id(target)?;
446 +
        let contains = format!("--contains={target_id}");
447 +
        let bytes = self.git(
448 +
            "for-each-ref",
449 +
            &[
450 +
                &contains,
451 +
                "--format=%(objectname)%00%(upstream:short)",
452 +
                "refs/heads",
453 +
            ],
454 +
        )?;
455 +
        let text = utf8(bytes)?;
456 +
        let target_id = target_id.to_string();
457 +
        let upstream = text
458 +
            .lines()
459 +
            .filter_map(|line| line.split_once('\0'))
460 +
            .min_by_key(|(head, upstream)| (*head != target_id, upstream.is_empty()))
461 +
            .map(|(_, upstream)| upstream)
462 +
            .filter(|upstream| !upstream.is_empty());
463 +
        let base = if let Some(upstream) = upstream {
464 +
            Rev::try_from(upstream)
465 +
                .map_err(|error| RepoError::Git(format!("invalid branch upstream: {error}")))?
466 +
        } else {
467 +
            let branches = self.branches()?;
468 +
            let Some(trunk) = self.trunk(&branches)? else {
469 +
                return Ok(None);
470 +
            };
471 +
            Rev::from(trunk.head)
472 +
        };
473 +
        let base = self.merge_base(&base, target)?;
474 +
        Ok(Some(base))
475 +
    }
476 +
434 477
    /// Returns ahead and behind counts for `target` relative to `base`.
435 478
    fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result<AheadBehind, RepoError> {
436 479
        let range = format!("{}...{}", base.as_str(), target.as_str());
437 480
        let bytes = self.git("rev-list", &["--left-right", "--count", &range])?;
438 481
        let text = utf8(bytes)?;
941 984
942 985
#[cfg(test)]
943 986
mod tests {
944 987
    use super::*;
945 988
989 +
    /// Runs a Git subcommand in `repository` and requires success.
990 +
    fn git(repository: &Repository, subcommand: &str, args: &[&str]) {
991 +
        let output = repository
992 +
            .run(
993 +
                subcommand,
994 +
                args,
995 +
                Opts {
996 +
                    env: &[
997 +
                        ("GIT_AUTHOR_NAME", "Rustik Test"),
998 +
                        ("GIT_AUTHOR_EMAIL", "rustik@example.com"),
999 +
                        ("GIT_COMMITTER_NAME", "Rustik Test"),
1000 +
                        ("GIT_COMMITTER_EMAIL", "rustik@example.com"),
1001 +
                    ],
1002 +
                    ..Opts::default()
1003 +
                },
1004 +
            )
1005 +
            .unwrap();
1006 +
        assert!(output.status.success());
1007 +
    }
1008 +
1009 +
    #[test]
1010 +
    fn branch_base_prefers_non_trunk_upstream() {
1011 +
        let directory = TempIndex::new().unwrap();
1012 +
        let repository_path = directory.path().parent().unwrap();
1013 +
        let status = Command::new("git")
1014 +
            .args(["init", "-q", "-b", "main"])
1015 +
            .arg(repository_path)
1016 +
            .status()
1017 +
            .unwrap();
1018 +
        assert!(status.success());
1019 +
        let repository = Repository::discover(repository_path.to_owned()).unwrap();
1020 +
        git(
1021 +
            &repository,
1022 +
            "commit",
1023 +
            &["-q", "--allow-empty", "-m", "main"],
1024 +
        );
1025 +
        git(&repository, "switch", &["-q", "-c", "integration"]);
1026 +
        git(
1027 +
            &repository,
1028 +
            "commit",
1029 +
            &["-q", "--allow-empty", "-m", "integration"],
1030 +
        );
1031 +
        git(&repository, "switch", &["-q", "-c", "feature"]);
1032 +
        git(
1033 +
            &repository,
1034 +
            "branch",
1035 +
            &["--set-upstream-to=integration", "feature"],
1036 +
        );
1037 +
        git(
1038 +
            &repository,
1039 +
            "commit",
1040 +
            &["-q", "--allow-empty", "-m", "feature"],
1041 +
        );
1042 +
        git(&repository, "branch", &["aaa"]);
1043 +
        let feature = repository
1044 +
            .commit_id(&Rev::try_from("feature").unwrap())
1045 +
            .unwrap();
1046 +
        let target = Rev::from(feature);
1047 +
        let integration = Rev::try_from("integration").unwrap();
1048 +
1049 +
        assert_eq!(
1050 +
            repository.branch_base(&target).unwrap(),
1051 +
            Some(repository.commit_id(&integration).unwrap())
1052 +
        );
1053 +
    }
1054 +
946 1055
    #[test]
947 1056
    fn commit_metadata_parses_four_fields() {
948 1057
        let record = [
949 1058
            "0123456789abcdef0123456789abcdef01234567",
950 1059
            "Alice",
a\n--- a/a\n+++ b/a\n@@ -1 +1 @@\n-old\n+new\n".to_owned(), +0 -0
b\n--- a/b\n+++ b/b\n@@ -0,0 +1 @@\n+line\n".to_owned(), +0 -0
crates/repo/src/jj.rs +8 -0
44 44
            commits.push((id, summary.trim_start().to_owned()));
45 45
        }
46 46
        Ok(commits)
47 47
    }
48 48
49 +
    /// Returns the fork point between `target` and the configured trunk.
50 +
    pub fn branch_base(&self, target: &Rev) -> Result<Oid, RepoError> {
51 +
        let revset = format!("fork_point(({}) | trunk())", target.as_str());
52 +
        let revset = Rev::try_from(revset.as_str())
53 +
            .map_err(|error| RepoError::Git(format!("invalid branch base revset: {error}")))?;
54 +
        self.resolve(&revset)
55 +
    }
56 +
49 57
    /// Returns local bookmark names paired with their target commits.
50 58
    pub fn bookmarks(&self) -> Result<Vec<(Oid, String)>, RepoError> {
51 59
        let stdout = self.jj_bytes(&[
52 60
            "log",
53 61
            "--no-graph",
crates/repo/src/lib.rs +8 -0
188 188
    ///
189 189
    /// The trunk is the remote default branch when configured, the
190 190
    /// `init.defaultBranch` branch when configured, or `master` otherwise.
191 191
    fn trunk(&self, branches: &[Branch]) -> Result<Option<Branch>, RepoError>;
192 192
193 +
    /// Returns the best common ancestor of two revisions.
194 +
    fn merge_base(&self, left: &Rev, right: &Rev) -> Result<Oid, RepoError>;
195 +
196 +
    /// Returns the branch point between `target` and its configured upstream.
197 +
    ///
198 +
    /// The repository trunk is used when `target` has no upstream.
199 +
    fn branch_base(&self, target: &Rev) -> Result<Option<Oid>, RepoError>;
200 +
193 201
    /// Returns ahead and behind counts for `target` relative to `base`.
194 202
    fn ahead_behind(&self, base: &Rev, target: &Rev) -> Result<AheadBehind, RepoError>;
195 203
196 204
    /// Returns whether `target` would merge into `base` with conflicts.
197 205
    fn merge_status(&self, base: &Rev, target: &Rev) -> Result<MergeStatus, RepoError>;