brain: Add `comments` command
e98281d3c662c78257c3b20af84fa0a0df648a1d
1 parent
573d38fa
crates/brain/src/backend.rs
+4 -2
| 302 | 302 | /// Commit whose hunks are being reconciled. |
|
| 303 | 303 | pub commit: Oid, |
|
| 304 | 304 | /// Exact identity per decoded hunk, when the commit's diff is loaded. |
|
| 305 | 305 | pub hunks: Option<&'a BTreeMap<HunkId, AcceptedHunk>>, |
|
| 306 | 306 | } |
|
| 307 | + | ||
| 307 | 308 | /// Final review state of one commit. |
|
| 308 | 309 | #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] |
|
| 309 | 310 | pub enum CommitReviewState { |
|
| 310 | 311 | /// The commit still needs a final decision. |
|
| 311 | 312 | #[default] |
| 447 | 448 | stats, |
|
| 448 | 449 | commits: statuses, |
|
| 449 | 450 | } |
|
| 450 | 451 | } |
|
| 451 | 452 | } |
|
| 453 | + | ||
| 452 | 454 | /// Stored status for one review identity. |
|
| 453 | 455 | #[derive(Clone, Debug, Eq, PartialEq)] |
|
| 454 | 456 | pub struct BrainStatus { |
|
| 455 | 457 | /// Head name displayed to the user. |
|
| 456 | 458 | pub head: String, |
| 1934 | 1936 | repository.git(&["switch", "-q", "-c", "topic"]); |
|
| 1935 | 1937 | repository.git(&["commit", "-q", "--allow-empty", "-m", "target"]); |
|
| 1936 | 1938 | let base = Rev::try_from("main").unwrap(); |
|
| 1937 | 1939 | let target = Rev::try_from("topic").unwrap(); |
|
| 1938 | 1940 | let backend = GitBackend::new(repository.path(), base, target).unwrap(); |
|
| 1939 | - | let comments = r#"{"id":1,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","body":"comment","pending_updates":null}"#; |
|
| 1941 | + | let comments = r#"{"id":1,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","body":"comment"}"#; |
|
| 1940 | 1942 | let brain = backend.reset_brain().unwrap(); |
|
| 1941 | 1943 | brain.write_comments(comments).unwrap(); |
|
| 1942 | 1944 | ||
| 1943 | 1945 | let loaded = backend.brain().unwrap(); |
|
| 1944 | 1946 | assert_eq!(loaded.read_comments().unwrap().as_deref(), Some(comments)); |
| 2283 | 2285 | let base = repository.commit_id(&identity.base).unwrap(); |
|
| 2284 | 2286 | let target = repository.commit_id(&identity.target).unwrap(); |
|
| 2285 | 2287 | let brain = Brain::reset(repository.clone(), base, target, &identity).unwrap(); |
|
| 2286 | 2288 | brain |
|
| 2287 | 2289 | .write_comments( |
|
| 2288 | - | r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"retained","pending_updates":null}"#, |
|
| 2290 | + | r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"retained"}"#, |
|
| 2289 | 2291 | ) |
|
| 2290 | 2292 | .unwrap(); |
|
| 2291 | 2293 | ||
| 2292 | 2294 | fixture.git(&["branch", "-m", "reviewed-feature"]); |
|
| 2293 | 2295 | let statuses = Brain::statuses(&repository).unwrap(); |
f
+0 -0
new.rs
+0 -0
image.png
+0 -0
new.txt
+0 -0
crates/brain/src/comments.rs
+64 -12
| 11 | 11 | use std::io; |
|
| 12 | 12 | use std::path::PathBuf; |
|
| 13 | 13 | use std::time::{SystemTime, UNIX_EPOCH}; |
|
| 14 | 14 | ||
| 15 | 15 | use rustik_diff::HunkId; |
|
| 16 | - | use rustik_repo::{Oid, PatchId}; |
|
| 16 | + | use rustik_repo::PatchId; |
|
| 17 | 17 | use serde::de::{Deserialize as DeserializeTrait, Scalar, Visitor}; |
|
| 18 | 18 | use serde::ser::{Fragment, Serialize as SerializeTrait}; |
|
| 19 | 19 | use serde::{Deserialize, Error, Result, Serialize, json}; |
|
| 20 | 20 | ||
| 21 | 21 | /// A single review comment authored on a hunk. |
| 121 | 121 | patch_id: PatchId, |
|
| 122 | 122 | /// Occurrence of this patch id within the commit. |
|
| 123 | 123 | ordinal: u32, |
|
| 124 | 124 | /// Comment body. |
|
| 125 | 125 | body: String, |
|
| 126 | - | /// Agent update waiting for reviewer re-review. |
|
| 127 | - | pending_updates: Option<PendingUpdates>, |
|
| 128 | 126 | } |
|
| 129 | 127 | ||
| 130 | - | /// Agent-authored update linked to a review comment. |
|
| 131 | - | #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] |
|
| 132 | - | struct PendingUpdates { |
|
| 133 | - | /// Agent identity that made the update. |
|
| 134 | - | by: String, |
|
| 135 | - | /// Commit containing the pending update. |
|
| 136 | - | commit: Oid, |
|
| 128 | + | /// One comment row emitted by the non-interactive comments command. |
|
| 129 | + | #[derive(Serialize)] |
|
| 130 | + | struct CommentOutput<'a> { |
|
| 131 | + | /// Stable local comment id. |
|
| 132 | + | id: &'a CommentId, |
|
| 133 | + | /// Author shown for this comment. |
|
| 134 | + | author: &'a str, |
|
| 135 | + | /// Unix timestamp when the comment was authored. |
|
| 136 | + | timestamp: u64, |
|
| 137 | + | /// Heading identifying the reviewed item. |
|
| 138 | + | heading: &'a str, |
|
| 139 | + | /// Optional file path associated with the hunk. |
|
| 140 | + | path: &'a Option<PathBuf>, |
|
| 141 | + | /// Current new-side line where the hunk starts. |
|
| 142 | + | line: Option<u32>, |
|
| 143 | + | /// Stable patch id of the hunk the comment is attached to. |
|
| 144 | + | #[serde(rename = "patchId")] |
|
| 145 | + | patch_id: &'a PatchId, |
|
| 146 | + | /// Occurrence of this patch id within the commit. |
|
| 147 | + | ordinal: u32, |
|
| 148 | + | /// Comment body. |
|
| 149 | + | body: &'a str, |
|
| 137 | 150 | } |
|
| 138 | 151 | ||
| 139 | 152 | /// Per-commit comment view keyed by the commit's hunk ids. |
|
| 140 | 153 | #[derive(Clone, Debug)] |
|
| 141 | 154 | pub struct Comments { |
| 167 | 180 | rows.push_str(&json::to_string(record)); |
|
| 168 | 181 | rows.push('\n'); |
|
| 169 | 182 | } |
|
| 170 | 183 | rows |
|
| 171 | 184 | } |
|
| 185 | + | /// Writes public comment rows as JSONL, resolving each hunk's current line. |
|
| 186 | + | pub fn write_jsonl( |
|
| 187 | + | &self, |
|
| 188 | + | mut writer: impl io::Write, |
|
| 189 | + | line_for: impl Fn(&PatchId, u32) -> Option<u32>, |
|
| 190 | + | ) -> io::Result<()> { |
|
| 191 | + | for record in &self.records { |
|
| 192 | + | let output = CommentOutput { |
|
| 193 | + | id: &record.id, |
|
| 194 | + | author: &record.author, |
|
| 195 | + | timestamp: record.timestamp, |
|
| 196 | + | heading: &record.heading, |
|
| 197 | + | path: &record.path, |
|
| 198 | + | line: line_for(&record.patch_id, record.ordinal), |
|
| 199 | + | patch_id: &record.patch_id, |
|
| 200 | + | ordinal: record.ordinal, |
|
| 201 | + | body: &record.body, |
|
| 202 | + | }; |
|
| 203 | + | writeln!(writer, "{}", json::to_string(&output))?; |
|
| 204 | + | } |
|
| 205 | + | Ok(()) |
|
| 206 | + | } |
|
| 172 | 207 | ||
| 173 | 208 | /// Returns the author name used for newly authored comments. |
|
| 174 | 209 | pub fn author(&self) -> &str { |
|
| 175 | 210 | &self.author |
|
| 176 | 211 | } |
| 202 | 237 | heading: target.heading.clone(), |
|
| 203 | 238 | path: target.path.clone(), |
|
| 204 | 239 | patch_id: target.patch_id.clone(), |
|
| 205 | 240 | ordinal: target.ordinal, |
|
| 206 | 241 | body, |
|
| 207 | - | pending_updates: None, |
|
| 208 | 242 | }; |
|
| 209 | 243 | let comment = Comment::from(&record); |
|
| 210 | 244 | self.records.push(record); |
|
| 211 | 245 | ||
| 212 | 246 | comment |
| 452 | 486 | } |
|
| 453 | 487 | ||
| 454 | 488 | #[test] |
|
| 455 | 489 | fn next_id_continues_above_stored_ids() { |
|
| 456 | 490 | let store = ReviewComments::parse( |
|
| 457 | - | r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"old","pending_updates":null}"#, |
|
| 491 | + | r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"old"}"#, |
|
| 458 | 492 | ) |
|
| 459 | 493 | .unwrap(); |
|
| 460 | 494 | ||
| 461 | 495 | assert_eq!(store.next_id(), CommentId::from(8)); |
|
| 462 | 496 | } |
|
| 497 | + | #[test] |
|
| 498 | + | fn output_uses_public_schema() { |
|
| 499 | + | let store = ReviewComments::parse( |
|
| 500 | + | r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":"src/main.rs","patch_id":"p","ordinal":0,"body":"old"}"#, |
|
| 501 | + | ) |
|
| 502 | + | .unwrap(); |
|
| 503 | + | ||
| 504 | + | let mut output = Vec::new(); |
|
| 505 | + | store |
|
| 506 | + | .write_jsonl(&mut output, |patch_id, ordinal| { |
|
| 507 | + | (patch_id.as_str() == "p" && ordinal == 0).then_some(12) |
|
| 508 | + | }) |
|
| 509 | + | .unwrap(); |
|
| 510 | + | assert_eq!( |
|
| 511 | + | String::from_utf8(output).unwrap(), |
|
| 512 | + | "{\"id\":7,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":\"src/main.rs\",\"line\":12,\"patchId\":\"p\",\"ordinal\":0,\"body\":\"old\"}\n" |
|
| 513 | + | ); |
|
| 514 | + | } |
|
| 463 | 515 | ||
| 464 | 516 | #[test] |
|
| 465 | 517 | fn comments_edit_updates_store_and_view() { |
|
| 466 | 518 | let (mut store, mut comments) = empty_comments(); |
|
| 467 | 519 |
crates/brain/src/main.rs
+85 -4
| 1 | 1 | //! Binary entry point for the `brain` code-review TUI. |
|
| 2 | 2 | //! |
|
| 3 | 3 | //! `brain diff <target>` opens an interactive review of the changes from the |
|
| 4 | 4 | //! target branch's base commit. An explicit base can be supplied as |
|
| 5 | - | //! `brain diff <base> <target>`. |
|
| 5 | + | //! `brain diff <base> <target>`. `brain comments` accepts the same revisions |
|
| 6 | + | //! and prints the review's comments as JSONL. |
|
| 6 | 7 | //! `brain status <base> <target>` prints the same commit history without |
|
| 7 | 8 | //! opening the interactive viewer. |
|
| 8 | 9 | ||
| 9 | 10 | // `serde` is the local alias for the `microserde` crate; the derive macro |
|
| 10 | 11 | // emits `microserde::*` paths so the original crate name must remain in scope. |
| 15 | 16 | mod decorate; |
|
| 16 | 17 | mod error; |
|
| 17 | 18 | mod review; |
|
| 18 | 19 | mod session; |
|
| 19 | 20 | ||
| 21 | + | use std::collections::BTreeMap; |
|
| 20 | 22 | use std::env; |
|
| 21 | 23 | use std::ffi::{OsStr, OsString}; |
|
| 22 | 24 | use std::io::{self, Write as _}; |
|
| 23 | 25 | use std::process::ExitCode; |
|
| 24 | 26 | use std::sync::mpsc::{self, RecvTimeoutError}; |
| 47 | 49 | const STARTUP_SPINNER_INTERVAL: Duration = Duration::from_millis(80); |
|
| 48 | 50 | /// Startup spinner animation frames. |
|
| 49 | 51 | const STARTUP_SPINNER_FRAMES: &[char] = &['|', '/', '-', '\\']; |
|
| 50 | 52 | ||
| 51 | 53 | /// Command-line usage text. |
|
| 52 | - | const USAGE: &str = "usage: brain [status [--all]]\n brain status <base> <target>\n brain [--reset|--rebase] diff [<base>] <target>"; |
|
| 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>"; |
|
| 53 | 55 | /// Default output width used when terminal width is unknown. |
|
| 54 | 56 | const DEFAULT_STATUS_WIDTH: usize = 140; |
|
| 55 | 57 | /// Marker shown for approved review state: โ. |
|
| 56 | 58 | const APPROVED_STATUS_ICON: char = 'โ'; |
|
| 57 | 59 | /// Marker shown for in-review state: โ. |
| 103 | 105 | None => Some(Command::Status { |
|
| 104 | 106 | scope: StatusScope::Reviews, |
|
| 105 | 107 | }), |
|
| 106 | 108 | }; |
|
| 107 | 109 | } |
|
| 108 | - | Value(command_name) if command_name == "diff" => { |
|
| 110 | + | Value(command_name) if command_name == "comments" || command_name == "diff" => { |
|
| 109 | 111 | let first = parse_revision("target", parser.value()?)?; |
|
| 110 | 112 | let (base, target) = match parser.next()? { |
|
| 111 | 113 | Some(Value(target)) => { |
|
| 112 | 114 | let target = parse_revision("target", target)?; |
|
| 113 | 115 | (Some(first), target) |
|
| 114 | 116 | } |
|
| 115 | 117 | Some(_) => return Err(Error::Usage(USAGE.to_owned())), |
|
| 116 | 118 | None => (None, first), |
|
| 117 | 119 | }; |
|
| 118 | 120 | ||
| 119 | - | command = Some(Command::Diff { base, target }); |
|
| 121 | + | command = Some(if command_name == "comments" { |
|
| 122 | + | Command::Comments { base, target } |
|
| 123 | + | } else { |
|
| 124 | + | Command::Diff { base, target } |
|
| 125 | + | }); |
|
| 120 | 126 | } |
|
| 121 | 127 | Value(value) => { |
|
| 122 | 128 | let value = value.to_string_lossy(); |
|
| 123 | 129 | return Err(Error::Usage(format!("unknown command: {value}\n{USAGE}"))); |
|
| 124 | 130 | } |
| 151 | 157 | /// Exclusive lower bound of the reviewed range. |
|
| 152 | 158 | base: Rev, |
|
| 153 | 159 | /// Inclusive upper bound of the reviewed range. |
|
| 154 | 160 | target: Rev, |
|
| 155 | 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 | + | }, |
|
| 156 | 169 | /// Review the commits in `base..target`. |
|
| 157 | 170 | Diff { |
|
| 158 | 171 | /// Exclusive lower bound of the reviewed range, when supplied. |
|
| 159 | 172 | base: Option<Rev>, |
|
| 160 | 173 | /// Inclusive upper bound of the reviewed range. |
| 375 | 388 | fn run(args: Vec<OsString>) -> Result<(), Error> { |
|
| 376 | 389 | let args = Args::parse(args)?; |
|
| 377 | 390 | match args.command { |
|
| 378 | 391 | Command::Status { scope } => run_status(scope), |
|
| 379 | 392 | Command::RangeStatus { base, target } => run_range_status(base, target), |
|
| 393 | + | Command::Comments { base, target } => run_comments(base, target), |
|
| 380 | 394 | Command::Diff { base, target } => run_diff(args.state, base, target), |
|
| 381 | 395 | } |
|
| 382 | 396 | } |
|
| 383 | 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 | + | ||
| 384 | 441 | /// Loads the review range and runs the interactive diff session. |
|
| 385 | 442 | fn run_diff(state: ReviewStateLoad, base: Option<Rev>, target: Rev) -> Result<(), Error> { |
|
| 386 | 443 | let cwd = env::current_dir()?; |
|
| 387 | 444 | let mut terminal = open_terminal()?; |
|
| 388 | 445 | terminal.clear()?; |
| 700 | 757 | target: Rev::try_from("feature").unwrap(), |
|
| 701 | 758 | }, |
|
| 702 | 759 | } |
|
| 703 | 760 | ); |
|
| 704 | 761 | } |
|
| 762 | + | #[test] |
|
| 763 | + | fn parses_comments_command_like_diff() { |
|
| 764 | + | let parsed = Args::parse(args(&["comments", "feature"])).unwrap(); |
|
| 765 | + | ||
| 766 | + | assert_eq!( |
|
| 767 | + | parsed, |
|
| 768 | + | Args { |
|
| 769 | + | state: ReviewStateLoad::Existing, |
|
| 770 | + | command: Command::Comments { |
|
| 771 | + | base: None, |
|
| 772 | + | target: Rev::try_from("feature").unwrap(), |
|
| 773 | + | }, |
|
| 774 | + | } |
|
| 775 | + | ); |
|
| 776 | + | ||
| 777 | + | let parsed = Args::parse(args(&["comments", "main", "HEAD"])).unwrap(); |
|
| 778 | + | assert_eq!( |
|
| 779 | + | parsed.command, |
|
| 780 | + | Command::Comments { |
|
| 781 | + | base: Some(Rev::try_from("main").unwrap()), |
|
| 782 | + | target: Rev::try_from("HEAD").unwrap(), |
|
| 783 | + | } |
|
| 784 | + | ); |
|
| 785 | + | } |
|
| 705 | 786 | ||
| 706 | 787 | #[test] |
|
| 707 | 788 | fn parses_range_status_command() { |
|
| 708 | 789 | let parsed = Args::parse(args(&["status", "main", "HEAD"])).unwrap(); |
|
| 709 | 790 |