//! Review comments attached to hunks. //! //! A review has one JSONL-encoded [`ReviewComments`] store, persisted as a //! blob in the hidden review ref (see [`crate::backend::Brain`]). Each //! reviewed commit owns a [`Comments`] view that maps the store's rows back //! to the commit's hunk ids using the hunk's stable patch id, so comments //! survive rebases that keep a hunk's content intact. use std::collections::BTreeMap; use std::fmt::Write as _; use std::io; use std::path::PathBuf; use std::time::{SystemTime, UNIX_EPOCH}; use rustik_diff::HunkId; use rustik_repo::{Oid, PatchId}; use serde::de::{Deserialize as DeserializeTrait, Scalar, Visitor}; use serde::ser::{Fragment, Serialize as SerializeTrait}; use serde::{Deserialize, Error, Result, Serialize, json}; /// Marker drawn beside comment counts: 🗩. pub(crate) const COMMENT_MARK: char = '🗩'; /// A single review comment authored on a hunk. #[derive(Clone, Debug, Eq, PartialEq)] pub struct Comment { /// Stable local comment id. pub id: CommentId, /// Author shown for this comment. pub author: String, /// Unix timestamp when the comment was authored. pub timestamp: u64, /// Comment body entered by the reviewer. pub body: String, } /// Stable local identifier for one review comment. #[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)] pub struct CommentId( /// Numeric component assigned within one persisted comment store. u64, ); impl CommentId { /// Returns the local numeric comment id. pub fn as_u64(&self) -> u64 { self.0 } } impl From for CommentId { fn from(value: u64) -> Self { Self(value) } } impl SerializeTrait for CommentId { fn begin(&self) -> Fragment<'_> { Fragment::U64(self.0) } } /// Deserializes persisted comment ids. pub struct CommentIdVisitor<'a> { /// Output slot receiving the parsed comment id. out: &'a mut Option, } impl Visitor for CommentIdVisitor<'_> { fn scalar(&mut self, scalar: &Scalar) -> Result<()> { let Scalar::Nonnegative(id) = scalar else { return Err(Error); }; let id = *id; *self.out = Some(CommentId(id)); Ok(()) } } impl DeserializeTrait for CommentId { type Visitor<'a> = CommentIdVisitor<'a>; fn begin(out: &mut Option) -> Self::Visitor<'_> { CommentIdVisitor { out } } } /// Target metadata for one commentable hunk. #[derive(Clone, Debug, Eq, PartialEq)] pub struct CommentTarget { /// Commit containing the reviewed hunk. pub commit: Oid, /// Heading identifying the reviewed item. pub heading: String, /// Optional file path associated with the hunk. pub path: Option, /// Stable patch id of the hunk the comment is attached to. pub patch_id: PatchId, /// Occurrence of this patch id within the commit. pub ordinal: u32, } /// Persistent comment store for one review identity. #[derive(Clone, Debug)] pub struct ReviewComments { /// Stored comment rows in JSONL order. records: Vec, /// Author name used for newly authored comments. author: String, } /// Resolution state selected by the comments command. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum CommentState { /// Comments that still require action. Unresolved, /// Comments that have been resolved. Resolved, } /// One persisted comment row. #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] struct CommentRecord { /// Commit containing the hunk, when recorded by a commit-aware version. commit: Option, /// Stable local comment id. id: CommentId, /// Author shown for this comment. author: String, /// Unix timestamp when the comment was authored. timestamp: u64, /// Heading identifying the reviewed item. heading: String, /// Optional file path associated with the hunk. path: Option, /// Stable patch id of the hunk the comment is attached to. patch_id: PatchId, /// Occurrence of this patch id within the commit. ordinal: u32, /// Comment body. body: String, /// Unix timestamp when the comment was resolved. resolved: Option, } /// One comment row emitted by the non-interactive comments command. #[derive(Serialize)] struct CommentOutput<'a> { /// Stable local comment id. id: &'a CommentId, /// Author shown for this comment. author: &'a str, /// Unix timestamp when the comment was authored. timestamp: u64, /// Heading identifying the reviewed item. heading: &'a str, /// Optional file path associated with the hunk. path: &'a Option, /// Current new-side line where the hunk starts. line: Option, /// Stable patch id of the hunk the comment is attached to. #[serde(rename = "patchId")] patch_id: &'a PatchId, /// Occurrence of this patch id within the commit. ordinal: u32, /// Comment body. body: &'a str, } /// Per-commit comment view keyed by the commit's hunk ids. #[derive(Clone, Debug)] pub struct Comments { /// Comments keyed by the hunk they were authored on. by_hunk: BTreeMap>, /// Hunk metadata used to persist newly authored comments. targets: BTreeMap, } impl ReviewComments { /// Parses persisted JSONL text; empty text yields an empty store. pub fn parse(text: &str) -> io::Result { let mut records = Vec::new(); for line in text.lines().filter(|line| !line.trim().is_empty()) { let record = json::from_str(line) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "malformed comment"))?; records.push(record); } Ok(Self { records, author: default_author(), }) } /// Encodes all comment rows as JSONL text for persistence. pub fn encode(&self) -> String { let mut rows = String::new(); for record in &self.records { rows.push_str(&json::to_string(record)); rows.push('\n'); } rows } /// Writes public comment rows in `state` as JSONL, resolving each hunk's current line. pub fn write_jsonl( &self, mut writer: impl io::Write, state: CommentState, line_for: impl Fn(&PatchId, u32) -> Option, ) -> io::Result<()> { for record in self.records.iter().filter(|record| { matches!( (state, record.resolved), (CommentState::Unresolved, None) | (CommentState::Resolved, Some(_)) ) }) { let output = CommentOutput { id: &record.id, author: &record.author, timestamp: record.timestamp, heading: &record.heading, path: &record.path, line: line_for(&record.patch_id, record.ordinal), patch_id: &record.patch_id, ordinal: record.ordinal, body: &record.body, }; writeln!(writer, "{}", json::to_string(&output))?; } Ok(()) } /// Returns the author name used for newly authored comments. pub fn author(&self) -> &str { &self.author } /// Selects the author name used for newly authored comments. pub(crate) fn set_author(&mut self, author: String) { if !author.trim().is_empty() { self.author = author; } } /// Returns the number of stored comment rows. pub fn len(&self) -> usize { self.records.len() } /// Returns the number of comments attached to one patch occurrence. pub fn matching_count(&self, commit: Oid, patch_id: &PatchId, ordinal: u32) -> usize { self.records .iter() .filter(|record| { record.resolved.is_none() && record.patch_id == *patch_id && record.ordinal == ordinal && record.commit.is_none_or(|stored| stored == commit) }) .count() } /// Returns comments attached exactly to `target`, in storage order. fn matching(&self, target: &CommentTarget) -> Vec { self.records .iter() .filter(|record| { record.resolved.is_none() && record.patch_id == target.patch_id && record.ordinal == target.ordinal && record.commit.is_none_or(|commit| commit == target.commit) }) .map(Comment::from) .collect() } /// Rewrites persisted commit anchors using range-diff correspondence. /// /// Older rows recover their commit from the abbreviated object id at the /// start of the persisted heading when it identifies exactly one pair. pub fn remap_commits(&mut self, commits: &BTreeMap) { for record in &mut self.records { if let Some(commit) = record.commit { if let Some(mapped) = commits.get(&commit) { record.commit = Some(*mapped); } continue; } let Some(prefix) = record.heading.split_whitespace().next() else { continue; }; let mut matches = commits .iter() .filter(|(old, _)| old.to_string().starts_with(prefix)); let Some((_, mapped)) = matches.next() else { continue; }; if matches.next().is_none() { record.commit = Some(*mapped); } } } /// Adds one comment row for `target` and returns its view. fn add(&mut self, target: &CommentTarget, body: String) -> Comment { let timestamp = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs(); let record = CommentRecord { id: self.next_id(), author: self.author.clone(), timestamp, heading: target.heading.clone(), commit: Some(target.commit), path: target.path.clone(), patch_id: target.patch_id.clone(), ordinal: target.ordinal, body, resolved: None, }; let comment = Comment::from(&record); self.records.push(record); comment } /// Replaces the body of the comment with `id`. fn edit(&mut self, id: &CommentId, body: String) -> bool { let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else { return false; }; record.body = body; true } /// Resolves the comment with `id`. pub fn resolve(&mut self, id: &CommentId) -> bool { let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else { return false; }; if record.resolved.is_some() { return true; } record.resolved = Some( SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap_or_default() .as_secs(), ); true } /// Deletes the comment with `id`. fn delete(&mut self, id: &CommentId) -> bool { let Some(index) = self.records.iter().position(|record| record.id == *id) else { return false; }; self.records.remove(index); true } /// Returns the next stable local comment id. fn next_id(&self) -> CommentId { let next = self .records .iter() .map(|record| record.id.as_u64()) .max() .unwrap_or_default() .saturating_add(1); CommentId::from(next) } /// Applies the difference between two snapshots without replacing unrelated rows. pub(crate) fn merge(&mut self, previous: &Self, updated: &Self) { for record in &previous.records { if !updated .records .iter() .any(|candidate| candidate.id == record.id) { self.delete(&record.id); } } for record in &updated.records { match previous .records .iter() .find(|candidate| candidate.id == record.id) { Some(previous) if previous != record => { if let Some(current) = self .records .iter_mut() .find(|candidate| candidate.id == record.id) { *current = record.clone(); } } None => { let mut added = record.clone(); added.id = self.next_id(); self.records.push(added); } _ => {} } } } } impl From<&CommentRecord> for Comment { fn from(record: &CommentRecord) -> Self { Self { id: record.id.clone(), author: record.author.clone(), timestamp: record.timestamp, body: record.body.clone(), } } } impl Comments { /// Creates a comment view for a commit's hunk targets. pub fn new(store: &ReviewComments, targets: BTreeMap) -> Self { let mut by_hunk = targets .iter() .filter_map(|(hunk, target)| { let comments = store.matching(target); (!comments.is_empty()).then_some((*hunk, comments)) }) .collect::>(); for record in &store.records { let Some(commit) = record.commit else { continue; }; let exact = targets.values().any(|target| { target.commit == commit && target.patch_id == record.patch_id && target.ordinal == record.ordinal }); if exact { continue; } let mut candidates = targets .iter() .filter(|(_, target)| target.commit == commit && target.path == record.path); let Some((hunk, _)) = candidates.next() else { continue; }; if candidates.next().is_none() { by_hunk .entry(*hunk) .or_default() .push(Comment::from(record)); } } Self { by_hunk, targets } } /// Applies one comment mutation and returns the encoded updated store. /// /// The caller must persist the returned text through the session command /// worker and restore its snapshot if that command fails. pub fn transact( &mut self, store: &mut ReviewComments, update: impl FnOnce(&mut Self, &mut ReviewComments) -> bool, ) -> Option { let mut updated_store = store.clone(); let mut updated_view = self.clone(); if !update(&mut updated_view, &mut updated_store) { return None; } let encoded = updated_store.encode(); *store = updated_store; *self = updated_view; Some(encoded) } /// Authors a comment on `hunk` into `store`, returning whether one was /// added. The caller is responsible for persisting the updated store. pub fn author(&mut self, store: &mut ReviewComments, hunk: HunkId, body: String) -> bool { let Some(target) = self.targets.get(&hunk) else { return false; }; let comment = store.add(target, body); self.by_hunk.entry(hunk).or_default().push(comment); true } /// Edits one comment on `hunk`. pub fn edit( &mut self, store: &mut ReviewComments, hunk: HunkId, id: &CommentId, body: String, ) -> bool { let Some(comments) = self.by_hunk.get_mut(&hunk) else { return false; }; let Some(comment) = comments.iter_mut().find(|comment| comment.id == *id) else { return false; }; if !store.edit(id, body.clone()) { return false; } comment.body = body; true } /// Deletes one comment from `hunk`. pub fn delete(&mut self, store: &mut ReviewComments, hunk: HunkId, id: &CommentId) -> bool { let Some(comments) = self.by_hunk.get_mut(&hunk) else { return false; }; let Some(index) = comments.iter().position(|comment| comment.id == *id) else { return false; }; if !store.delete(id) { return false; } comments.remove(index); if comments.is_empty() { self.by_hunk.remove(&hunk); } true } /// Returns the comments authored on `hunk`. pub fn for_hunk(&self, hunk: HunkId) -> &[Comment] { self.by_hunk.get(&hunk).map_or(&[], Vec::as_slice) } /// Returns the total number of comments in this commit view. pub fn len(&self) -> usize { self.by_hunk.values().map(Vec::len).sum() } /// Returns per-hunk comment counts, for decoration snapshots. pub fn counts(&self) -> BTreeMap { self.by_hunk .iter() .map(|(hunk, comments)| (*hunk, comments.len())) .collect() } /// Rebuilds this per-hunk view from an updated review-wide store. pub fn refresh(&mut self, store: &ReviewComments) { *self = Self::new(store, self.targets.clone()); } } /// Encodes arbitrary review identity text as one path or refname component. pub(crate) fn encode_component(input: &str) -> String { let mut encoded = String::new(); for byte in input.bytes() { match byte { b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-' => { encoded.push(byte as char); } _ => { write!(encoded, "%{byte:02x}").ok(); } } } encoded } /// Decodes a review identity text from one encoded refname component. pub(crate) fn decode_component(input: &str) -> String { let mut decoded = Vec::with_capacity(input.len()); let mut bytes = input.as_bytes().iter().copied(); while let Some(byte) = bytes.next() { if byte != b'%' { decoded.push(byte); continue; } let Some(high) = bytes.next() else { decoded.push(byte); break; }; let Some(low) = bytes.next() else { decoded.extend([byte, high]); break; }; match (hex_value(high), hex_value(low)) { (Some(high), Some(low)) => decoded.push(high << 4 | low), _ => decoded.extend([byte, high, low]), } } String::from_utf8_lossy(&decoded).into_owned() } /// Returns the numeric value of one hexadecimal digit. fn hex_value(byte: u8) -> Option { match byte { b'0'..=b'9' => Some(byte - b'0'), b'a'..=b'f' => Some(byte - b'a' + 10), b'A'..=b'F' => Some(byte - b'A' + 10), _ => None, } } /// Returns the author name used for newly authored comments. fn default_author() -> String { std::env::var("GIT_AUTHOR_NAME") .ok() .filter(|name| !name.trim().is_empty()) .or_else(|| { std::env::var("USER") .ok() .filter(|name| !name.trim().is_empty()) }) .unwrap_or_else(|| "You".to_owned()) } #[cfg(test)] mod tests { use super::*; /// Hunk used by comment view tests. const HUNK: HunkId = HunkId::new(0); /// Second hunk used by comment view tests. const OTHER_HUNK: HunkId = HunkId::new(1); /// Builds an empty comment store and matching hunk view. fn empty_comments() -> (ReviewComments, Comments) { let target = CommentTarget { commit: "1111111111111111111111111111111111111111".parse().unwrap(), heading: "h".to_owned(), path: None, patch_id: PatchId::from("p".to_owned()), ordinal: 0, }; let mut targets = BTreeMap::new(); targets.insert(HUNK, target); let store = ReviewComments::parse("").unwrap(); let comments = Comments::new(&store, targets); (store, comments) } #[test] fn output_selects_comment_resolution_state() { let mut store = ReviewComments::parse( "{\"id\":1,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":null,\"patch_id\":\"p\",\"ordinal\":0,\"body\":\"open\"}\n{\"id\":2,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":null,\"patch_id\":\"p\",\"ordinal\":0,\"body\":\"done\",\"resolved\":2}", ) .unwrap(); let mut output = Vec::new(); store .write_jsonl(&mut output, CommentState::Unresolved, |_, _| None) .unwrap(); assert!( String::from_utf8(output) .unwrap() .contains(r#""body":"open""#) ); let mut output = Vec::new(); store .write_jsonl(&mut output, CommentState::Resolved, |_, _| None) .unwrap(); assert!( String::from_utf8(output) .unwrap() .contains(r#""body":"done""#) ); assert!(store.resolve(&CommentId::from(1))); assert_eq!( store.matching_count( "1111111111111111111111111111111111111111".parse().unwrap(), &PatchId::from("p".to_owned()), 0, ), 0 ); } #[test] fn comment_id_serializes_as_number() { let id = CommentId::from(7); assert_eq!(json::to_string(&id), "7"); assert_eq!(json::from_str::("7").unwrap(), id); } #[test] fn next_id_continues_above_stored_ids() { let store = ReviewComments::parse( r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"old"}"#, ) .unwrap(); assert_eq!(store.next_id(), CommentId::from(8)); } #[test] fn output_uses_public_schema() { let store = ReviewComments::parse( r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":"src/main.rs","patch_id":"p","ordinal":0,"body":"old"}"#, ) .unwrap(); let mut output = Vec::new(); store .write_jsonl( &mut output, CommentState::Unresolved, |patch_id, ordinal| (patch_id.as_str() == "p" && ordinal == 0).then_some(12), ) .unwrap(); assert_eq!( String::from_utf8(output).unwrap(), "{\"id\":7,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":\"src/main.rs\",\"line\":12,\"patchId\":\"p\",\"ordinal\":0,\"body\":\"old\"}\n" ); } #[test] fn comments_edit_updates_store_and_view() { let (mut store, mut comments) = empty_comments(); assert!(comments.author(&mut store, HUNK, "old".to_owned())); let id = comments.for_hunk(HUNK)[0].id.clone(); assert!(comments.edit(&mut store, HUNK, &id, "new".to_owned())); assert_eq!(comments.for_hunk(HUNK)[0].body, "new"); assert!(store.encode().contains(r#""body":"new""#)); } #[test] fn comments_delete_updates_store_and_view() { let (mut store, mut comments) = empty_comments(); assert!(comments.author(&mut store, HUNK, "body".to_owned())); let id = comments.for_hunk(HUNK)[0].id.clone(); assert!(comments.delete(&mut store, HUNK, &id)); assert!(comments.for_hunk(HUNK).is_empty()); assert!(store.encode().is_empty()); } #[test] fn identical_patch_occurrences_keep_comments_separate() { let first = CommentTarget { commit: "1111111111111111111111111111111111111111".parse().unwrap(), heading: "h".to_owned(), path: Some(PathBuf::from("file")), patch_id: PatchId::from("same".to_owned()), ordinal: 0, }; let second = CommentTarget { ordinal: 1, ..first.clone() }; let targets = BTreeMap::from([(HUNK, first), (OTHER_HUNK, second)]); let mut store = ReviewComments::parse("").unwrap(); let mut comments = Comments::new(&store, targets.clone()); assert!(comments.author(&mut store, HUNK, "first occurrence".to_owned())); let mut reopened = Comments::new(&store, targets.clone()); assert_eq!(reopened.for_hunk(HUNK)[0].body, "first occurrence"); assert!(reopened.for_hunk(OTHER_HUNK).is_empty()); assert!(reopened.author(&mut store, OTHER_HUNK, "second occurrence".to_owned())); let first_id = reopened.for_hunk(HUNK)[0].id.clone(); let second_id = reopened.for_hunk(OTHER_HUNK)[0].id.clone(); assert!(reopened.edit( &mut store, OTHER_HUNK, &second_id, "edited second".to_owned(), )); assert!(reopened.delete(&mut store, HUNK, &first_id)); let reopened = Comments::new(&store, targets); assert!(reopened.for_hunk(HUNK).is_empty()); assert_eq!(reopened.for_hunk(OTHER_HUNK)[0].body, "edited second"); } #[test] fn range_diff_commit_match_recovers_unique_changed_hunk() { let old_commit: Oid = "1111111111111111111111111111111111111111".parse().unwrap(); let new_commit: Oid = "2222222222222222222222222222222222222222".parse().unwrap(); let mut store = ReviewComments::parse( r#"{"id":1,"author":"A","timestamp":1,"heading":"1111111 old","path":"file","patch_id":"old","ordinal":0,"body":"retained"}"#, ) .unwrap(); store.remap_commits(&BTreeMap::from([(old_commit, new_commit)])); let targets = BTreeMap::from([( HUNK, CommentTarget { commit: new_commit, heading: "new".to_owned(), path: Some(PathBuf::from("file")), patch_id: PatchId::from("changed".to_owned()), ordinal: 0, }, )]); let comments = Comments::new(&store, targets); assert_eq!(comments.for_hunk(HUNK)[0].body, "retained"); assert!(store.encode().contains(&new_commit.to_string())); } }