crates/brain/src/comments.rs 22.1 KiB raw
1
//! Review comments attached to hunks.
2
//!
3
//! A review has one JSONL-encoded [`ReviewComments`] store, persisted as a
4
//! blob in the hidden review ref (see [`crate::backend::Brain`]). Each
5
//! reviewed commit owns a [`Comments`] view that maps the store's rows back
6
//! to the commit's hunk ids using the hunk's stable patch id, so comments
7
//! survive rebases that keep a hunk's content intact.
8
9
use std::collections::BTreeMap;
10
use std::fmt::Write as _;
11
use std::io;
12
use std::path::PathBuf;
13
use std::time::{SystemTime, UNIX_EPOCH};
14
15
use rustik_diff::HunkId;
16
use rustik_repo::{Oid, PatchId};
17
use serde::de::{Deserialize as DeserializeTrait, Scalar, Visitor};
18
use serde::ser::{Fragment, Serialize as SerializeTrait};
19
use serde::{Deserialize, Error, Result, Serialize, json};
20
/// Marker drawn beside comment counts: 🗩.
21
pub(crate) const COMMENT_MARK: char = '🗩';
22
23
/// A single review comment authored on a hunk.
24
#[derive(Clone, Debug, Eq, PartialEq)]
25
pub struct Comment {
26
    /// Stable local comment id.
27
    pub id: CommentId,
28
    /// Author shown for this comment.
29
    pub author: String,
30
    /// Unix timestamp when the comment was authored.
31
    pub timestamp: u64,
32
    /// Comment body entered by the reviewer.
33
    pub body: String,
34
}
35
36
/// Stable local identifier for one review comment.
37
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
38
pub struct CommentId(
39
    /// Numeric component assigned within one persisted comment store.
40
    u64,
41
);
42
43
impl CommentId {
44
    /// Returns the local numeric comment id.
45
    pub fn as_u64(&self) -> u64 {
46
        self.0
47
    }
48
}
49
50
impl From<u64> for CommentId {
51
    fn from(value: u64) -> Self {
52
        Self(value)
53
    }
54
}
55
56
impl SerializeTrait for CommentId {
57
    fn begin(&self) -> Fragment<'_> {
58
        Fragment::U64(self.0)
59
    }
60
}
61
62
/// Deserializes persisted comment ids.
63
pub struct CommentIdVisitor<'a> {
64
    /// Output slot receiving the parsed comment id.
65
    out: &'a mut Option<CommentId>,
66
}
67
68
impl Visitor for CommentIdVisitor<'_> {
69
    fn scalar(&mut self, scalar: &Scalar) -> Result<()> {
70
        let Scalar::Nonnegative(id) = scalar else {
71
            return Err(Error);
72
        };
73
        let id = *id;
74
        *self.out = Some(CommentId(id));
75
        Ok(())
76
    }
77
}
78
79
impl DeserializeTrait for CommentId {
80
    type Visitor<'a> = CommentIdVisitor<'a>;
81
82
    fn begin(out: &mut Option<Self>) -> Self::Visitor<'_> {
83
        CommentIdVisitor { out }
84
    }
85
}
86
87
/// Target metadata for one commentable hunk.
88
#[derive(Clone, Debug, Eq, PartialEq)]
89
pub struct CommentTarget {
90
    /// Commit containing the reviewed hunk.
91
    pub commit: Oid,
92
    /// Heading identifying the reviewed item.
93
    pub heading: String,
94
    /// Optional file path associated with the hunk.
95
    pub path: Option<PathBuf>,
96
    /// Stable patch id of the hunk the comment is attached to.
97
    pub patch_id: PatchId,
98
    /// Occurrence of this patch id within the commit.
99
    pub ordinal: u32,
100
}
101
102
/// Persistent comment store for one review identity.
103
#[derive(Clone, Debug)]
104
pub struct ReviewComments {
105
    /// Stored comment rows in JSONL order.
106
    records: Vec<CommentRecord>,
107
    /// Author name used for newly authored comments.
108
    author: String,
109
}
110
111
/// One persisted comment row.
112
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
113
struct CommentRecord {
114
    /// Commit containing the hunk, when recorded by a commit-aware version.
115
    commit: Option<Oid>,
116
    /// Stable local comment id.
117
    id: CommentId,
118
    /// Author shown for this comment.
119
    author: String,
120
    /// Unix timestamp when the comment was authored.
121
    timestamp: u64,
122
    /// Heading identifying the reviewed item.
123
    heading: String,
124
    /// Optional file path associated with the hunk.
125
    path: Option<PathBuf>,
126
    /// Stable patch id of the hunk the comment is attached to.
127
    patch_id: PatchId,
128
    /// Occurrence of this patch id within the commit.
129
    ordinal: u32,
130
    /// Comment body.
131
    body: String,
132
}
133
134
/// One comment row emitted by the non-interactive comments command.
135
#[derive(Serialize)]
136
struct CommentOutput<'a> {
137
    /// Stable local comment id.
138
    id: &'a CommentId,
139
    /// Author shown for this comment.
140
    author: &'a str,
141
    /// Unix timestamp when the comment was authored.
142
    timestamp: u64,
143
    /// Heading identifying the reviewed item.
144
    heading: &'a str,
145
    /// Optional file path associated with the hunk.
146
    path: &'a Option<PathBuf>,
147
    /// Current new-side line where the hunk starts.
148
    line: Option<u32>,
149
    /// Stable patch id of the hunk the comment is attached to.
150
    #[serde(rename = "patchId")]
151
    patch_id: &'a PatchId,
152
    /// Occurrence of this patch id within the commit.
153
    ordinal: u32,
154
    /// Comment body.
155
    body: &'a str,
156
}
157
158
/// Per-commit comment view keyed by the commit's hunk ids.
159
#[derive(Clone, Debug)]
160
pub struct Comments {
161
    /// Comments keyed by the hunk they were authored on.
162
    by_hunk: BTreeMap<HunkId, Vec<Comment>>,
163
    /// Hunk metadata used to persist newly authored comments.
164
    targets: BTreeMap<HunkId, CommentTarget>,
165
}
166
167
impl ReviewComments {
168
    /// Parses persisted JSONL text; empty text yields an empty store.
169
    pub fn parse(text: &str) -> io::Result<Self> {
170
        let mut records = Vec::new();
171
        for line in text.lines().filter(|line| !line.trim().is_empty()) {
172
            let record = json::from_str(line)
173
                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "malformed comment"))?;
174
            records.push(record);
175
        }
176
        Ok(Self {
177
            records,
178
            author: default_author(),
179
        })
180
    }
181
182
    /// Encodes all comment rows as JSONL text for persistence.
183
    pub fn encode(&self) -> String {
184
        let mut rows = String::new();
185
        for record in &self.records {
186
            rows.push_str(&json::to_string(record));
187
            rows.push('\n');
188
        }
189
        rows
190
    }
191
    /// Writes public comment rows as JSONL, resolving each hunk's current line.
192
    pub fn write_jsonl(
193
        &self,
194
        mut writer: impl io::Write,
195
        line_for: impl Fn(&PatchId, u32) -> Option<u32>,
196
    ) -> io::Result<()> {
197
        for record in &self.records {
198
            let output = CommentOutput {
199
                id: &record.id,
200
                author: &record.author,
201
                timestamp: record.timestamp,
202
                heading: &record.heading,
203
                path: &record.path,
204
                line: line_for(&record.patch_id, record.ordinal),
205
                patch_id: &record.patch_id,
206
                ordinal: record.ordinal,
207
                body: &record.body,
208
            };
209
            writeln!(writer, "{}", json::to_string(&output))?;
210
        }
211
        Ok(())
212
    }
213
214
    /// Returns the author name used for newly authored comments.
215
    pub fn author(&self) -> &str {
216
        &self.author
217
    }
218
219
    /// Returns the number of stored comment rows.
220
    pub fn len(&self) -> usize {
221
        self.records.len()
222
    }
223
224
    /// Returns the number of comments attached to one patch occurrence.
225
    pub fn matching_count(&self, commit: Oid, patch_id: &PatchId, ordinal: u32) -> usize {
226
        self.records
227
            .iter()
228
            .filter(|record| {
229
                record.patch_id == *patch_id
230
                    && record.ordinal == ordinal
231
                    && record.commit.is_none_or(|stored| stored == commit)
232
            })
233
            .count()
234
    }
235
236
    /// Returns comments attached exactly to `target`, in storage order.
237
    fn matching(&self, target: &CommentTarget) -> Vec<Comment> {
238
        self.records
239
            .iter()
240
            .filter(|record| {
241
                record.patch_id == target.patch_id
242
                    && record.ordinal == target.ordinal
243
                    && record.commit.is_none_or(|commit| commit == target.commit)
244
            })
245
            .map(Comment::from)
246
            .collect()
247
    }
248
249
    /// Rewrites persisted commit anchors using range-diff correspondence.
250
    ///
251
    /// Older rows recover their commit from the abbreviated object id at the
252
    /// start of the persisted heading when it identifies exactly one pair.
253
    pub fn remap_commits(&mut self, commits: &BTreeMap<Oid, Oid>) {
254
        for record in &mut self.records {
255
            if let Some(commit) = record.commit {
256
                if let Some(mapped) = commits.get(&commit) {
257
                    record.commit = Some(*mapped);
258
                }
259
                continue;
260
            }
261
            let Some(prefix) = record.heading.split_whitespace().next() else {
262
                continue;
263
            };
264
            let mut matches = commits
265
                .iter()
266
                .filter(|(old, _)| old.to_string().starts_with(prefix));
267
            let Some((_, mapped)) = matches.next() else {
268
                continue;
269
            };
270
            if matches.next().is_none() {
271
                record.commit = Some(*mapped);
272
            }
273
        }
274
    }
275
276
    /// Adds one comment row for `target` and returns its view.
277
    fn add(&mut self, target: &CommentTarget, body: String) -> Comment {
278
        let timestamp = SystemTime::now()
279
            .duration_since(UNIX_EPOCH)
280
            .unwrap_or_default()
281
            .as_secs();
282
        let record = CommentRecord {
283
            id: self.next_id(),
284
            author: self.author.clone(),
285
            timestamp,
286
            heading: target.heading.clone(),
287
            commit: Some(target.commit),
288
            path: target.path.clone(),
289
            patch_id: target.patch_id.clone(),
290
            ordinal: target.ordinal,
291
            body,
292
        };
293
        let comment = Comment::from(&record);
294
        self.records.push(record);
295
296
        comment
297
    }
298
299
    /// Replaces the body of the comment with `id`.
300
    fn edit(&mut self, id: &CommentId, body: String) -> bool {
301
        let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else {
302
            return false;
303
        };
304
        record.body = body;
305
        true
306
    }
307
308
    /// Deletes the comment with `id`.
309
    fn delete(&mut self, id: &CommentId) -> bool {
310
        let Some(index) = self.records.iter().position(|record| record.id == *id) else {
311
            return false;
312
        };
313
        self.records.remove(index);
314
        true
315
    }
316
317
    /// Returns the next stable local comment id.
318
    fn next_id(&self) -> CommentId {
319
        let next = self
320
            .records
321
            .iter()
322
            .map(|record| record.id.as_u64())
323
            .max()
324
            .unwrap_or_default()
325
            .saturating_add(1);
326
        CommentId::from(next)
327
    }
328
}
329
330
impl From<&CommentRecord> for Comment {
331
    fn from(record: &CommentRecord) -> Self {
332
        Self {
333
            id: record.id.clone(),
334
            author: record.author.clone(),
335
            timestamp: record.timestamp,
336
            body: record.body.clone(),
337
        }
338
    }
339
}
340
341
impl Comments {
342
    /// Creates a comment view for a commit's hunk targets.
343
    pub fn new(store: &ReviewComments, targets: BTreeMap<HunkId, CommentTarget>) -> Self {
344
        let mut by_hunk = targets
345
            .iter()
346
            .filter_map(|(hunk, target)| {
347
                let comments = store.matching(target);
348
                (!comments.is_empty()).then_some((*hunk, comments))
349
            })
350
            .collect::<BTreeMap<_, _>>();
351
        for record in &store.records {
352
            let Some(commit) = record.commit else {
353
                continue;
354
            };
355
            let exact = targets.values().any(|target| {
356
                target.commit == commit
357
                    && target.patch_id == record.patch_id
358
                    && target.ordinal == record.ordinal
359
            });
360
            if exact {
361
                continue;
362
            }
363
            let mut candidates = targets
364
                .iter()
365
                .filter(|(_, target)| target.commit == commit && target.path == record.path);
366
            let Some((hunk, _)) = candidates.next() else {
367
                continue;
368
            };
369
            if candidates.next().is_none() {
370
                by_hunk
371
                    .entry(*hunk)
372
                    .or_default()
373
                    .push(Comment::from(record));
374
            }
375
        }
376
377
        Self { by_hunk, targets }
378
    }
379
380
    /// Applies one comment mutation and returns the encoded updated store.
381
    ///
382
    /// The caller must persist the returned text through the session command
383
    /// worker and restore its snapshot if that command fails.
384
    pub fn transact(
385
        &mut self,
386
        store: &mut ReviewComments,
387
        update: impl FnOnce(&mut Self, &mut ReviewComments) -> bool,
388
    ) -> Option<String> {
389
        let mut updated_store = store.clone();
390
        let mut updated_view = self.clone();
391
        if !update(&mut updated_view, &mut updated_store) {
392
            return None;
393
        }
394
        let encoded = updated_store.encode();
395
        *store = updated_store;
396
        *self = updated_view;
397
        Some(encoded)
398
    }
399
400
    /// Authors a comment on `hunk` into `store`, returning whether one was
401
    /// added. The caller is responsible for persisting the updated store.
402
    pub fn author(&mut self, store: &mut ReviewComments, hunk: HunkId, body: String) -> bool {
403
        let Some(target) = self.targets.get(&hunk) else {
404
            return false;
405
        };
406
        let comment = store.add(target, body);
407
        self.by_hunk.entry(hunk).or_default().push(comment);
408
        true
409
    }
410
411
    /// Edits one comment on `hunk`.
412
    pub fn edit(
413
        &mut self,
414
        store: &mut ReviewComments,
415
        hunk: HunkId,
416
        id: &CommentId,
417
        body: String,
418
    ) -> bool {
419
        let Some(comments) = self.by_hunk.get_mut(&hunk) else {
420
            return false;
421
        };
422
        let Some(comment) = comments.iter_mut().find(|comment| comment.id == *id) else {
423
            return false;
424
        };
425
        if !store.edit(id, body.clone()) {
426
            return false;
427
        }
428
        comment.body = body;
429
        true
430
    }
431
432
    /// Deletes one comment from `hunk`.
433
    pub fn delete(&mut self, store: &mut ReviewComments, hunk: HunkId, id: &CommentId) -> bool {
434
        let Some(comments) = self.by_hunk.get_mut(&hunk) else {
435
            return false;
436
        };
437
        let Some(index) = comments.iter().position(|comment| comment.id == *id) else {
438
            return false;
439
        };
440
        if !store.delete(id) {
441
            return false;
442
        }
443
        comments.remove(index);
444
        if comments.is_empty() {
445
            self.by_hunk.remove(&hunk);
446
        }
447
        true
448
    }
449
450
    /// Returns the comments authored on `hunk`.
451
    pub fn for_hunk(&self, hunk: HunkId) -> &[Comment] {
452
        self.by_hunk.get(&hunk).map_or(&[], Vec::as_slice)
453
    }
454
455
    /// Returns the total number of comments in this commit view.
456
    pub fn len(&self) -> usize {
457
        self.by_hunk.values().map(Vec::len).sum()
458
    }
459
460
    /// Returns per-hunk comment counts, for decoration snapshots.
461
    pub fn counts(&self) -> BTreeMap<HunkId, usize> {
462
        self.by_hunk
463
            .iter()
464
            .map(|(hunk, comments)| (*hunk, comments.len()))
465
            .collect()
466
    }
467
}
468
469
/// Encodes arbitrary review identity text as one path or refname component.
470
pub(crate) fn encode_component(input: &str) -> String {
471
    let mut encoded = String::new();
472
    for byte in input.bytes() {
473
        match byte {
474
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-' => {
475
                encoded.push(byte as char);
476
            }
477
            _ => {
478
                write!(encoded, "%{byte:02x}").ok();
479
            }
480
        }
481
    }
482
    encoded
483
}
484
485
/// Decodes a review identity text from one encoded refname component.
486
pub(crate) fn decode_component(input: &str) -> String {
487
    let mut decoded = Vec::with_capacity(input.len());
488
    let mut bytes = input.as_bytes().iter().copied();
489
490
    while let Some(byte) = bytes.next() {
491
        if byte != b'%' {
492
            decoded.push(byte);
493
            continue;
494
        }
495
496
        let Some(high) = bytes.next() else {
497
            decoded.push(byte);
498
            break;
499
        };
500
        let Some(low) = bytes.next() else {
501
            decoded.extend([byte, high]);
502
            break;
503
        };
504
        match (hex_value(high), hex_value(low)) {
505
            (Some(high), Some(low)) => decoded.push(high << 4 | low),
506
            _ => decoded.extend([byte, high, low]),
507
        }
508
    }
509
510
    String::from_utf8_lossy(&decoded).into_owned()
511
}
512
513
/// Returns the numeric value of one hexadecimal digit.
514
fn hex_value(byte: u8) -> Option<u8> {
515
    match byte {
516
        b'0'..=b'9' => Some(byte - b'0'),
517
        b'a'..=b'f' => Some(byte - b'a' + 10),
518
        b'A'..=b'F' => Some(byte - b'A' + 10),
519
        _ => None,
520
    }
521
}
522
523
/// Returns the author name used for newly authored comments.
524
fn default_author() -> String {
525
    std::env::var("GIT_AUTHOR_NAME")
526
        .ok()
527
        .filter(|name| !name.trim().is_empty())
528
        .or_else(|| {
529
            std::env::var("USER")
530
                .ok()
531
                .filter(|name| !name.trim().is_empty())
532
        })
533
        .unwrap_or_else(|| "You".to_owned())
534
}
535
536
#[cfg(test)]
537
mod tests {
538
    use super::*;
539
540
    /// Hunk used by comment view tests.
541
    const HUNK: HunkId = HunkId::new(0);
542
    /// Second hunk used by comment view tests.
543
    const OTHER_HUNK: HunkId = HunkId::new(1);
544
545
    /// Builds an empty comment store and matching hunk view.
546
    fn empty_comments() -> (ReviewComments, Comments) {
547
        let target = CommentTarget {
548
            commit: "1111111111111111111111111111111111111111".parse().unwrap(),
549
            heading: "h".to_owned(),
550
            path: None,
551
            patch_id: PatchId::from("p".to_owned()),
552
            ordinal: 0,
553
        };
554
        let mut targets = BTreeMap::new();
555
        targets.insert(HUNK, target);
556
        let store = ReviewComments::parse("").unwrap();
557
        let comments = Comments::new(&store, targets);
558
        (store, comments)
559
    }
560
561
    #[test]
562
    fn comment_id_serializes_as_number() {
563
        let id = CommentId::from(7);
564
565
        assert_eq!(json::to_string(&id), "7");
566
        assert_eq!(json::from_str::<CommentId>("7").unwrap(), id);
567
    }
568
569
    #[test]
570
    fn next_id_continues_above_stored_ids() {
571
        let store = ReviewComments::parse(
572
            r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"old"}"#,
573
        )
574
        .unwrap();
575
576
        assert_eq!(store.next_id(), CommentId::from(8));
577
    }
578
    #[test]
579
    fn output_uses_public_schema() {
580
        let store = ReviewComments::parse(
581
            r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":"src/main.rs","patch_id":"p","ordinal":0,"body":"old"}"#,
582
        )
583
        .unwrap();
584
585
        let mut output = Vec::new();
586
        store
587
            .write_jsonl(&mut output, |patch_id, ordinal| {
588
                (patch_id.as_str() == "p" && ordinal == 0).then_some(12)
589
            })
590
            .unwrap();
591
        assert_eq!(
592
            String::from_utf8(output).unwrap(),
593
            "{\"id\":7,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":\"src/main.rs\",\"line\":12,\"patchId\":\"p\",\"ordinal\":0,\"body\":\"old\"}\n"
594
        );
595
    }
596
597
    #[test]
598
    fn comments_edit_updates_store_and_view() {
599
        let (mut store, mut comments) = empty_comments();
600
601
        assert!(comments.author(&mut store, HUNK, "old".to_owned()));
602
        let id = comments.for_hunk(HUNK)[0].id.clone();
603
        assert!(comments.edit(&mut store, HUNK, &id, "new".to_owned()));
604
605
        assert_eq!(comments.for_hunk(HUNK)[0].body, "new");
606
        assert!(store.encode().contains(r#""body":"new""#));
607
    }
608
609
    #[test]
610
    fn comments_delete_updates_store_and_view() {
611
        let (mut store, mut comments) = empty_comments();
612
613
        assert!(comments.author(&mut store, HUNK, "body".to_owned()));
614
        let id = comments.for_hunk(HUNK)[0].id.clone();
615
        assert!(comments.delete(&mut store, HUNK, &id));
616
617
        assert!(comments.for_hunk(HUNK).is_empty());
618
        assert!(store.encode().is_empty());
619
    }
620
621
    #[test]
622
    fn identical_patch_occurrences_keep_comments_separate() {
623
        let first = CommentTarget {
624
            commit: "1111111111111111111111111111111111111111".parse().unwrap(),
625
            heading: "h".to_owned(),
626
            path: Some(PathBuf::from("file")),
627
            patch_id: PatchId::from("same".to_owned()),
628
            ordinal: 0,
629
        };
630
        let second = CommentTarget {
631
            ordinal: 1,
632
            ..first.clone()
633
        };
634
        let targets = BTreeMap::from([(HUNK, first), (OTHER_HUNK, second)]);
635
        let mut store = ReviewComments::parse("").unwrap();
636
        let mut comments = Comments::new(&store, targets.clone());
637
638
        assert!(comments.author(&mut store, HUNK, "first occurrence".to_owned()));
639
640
        let mut reopened = Comments::new(&store, targets.clone());
641
        assert_eq!(reopened.for_hunk(HUNK)[0].body, "first occurrence");
642
        assert!(reopened.for_hunk(OTHER_HUNK).is_empty());
643
644
        assert!(reopened.author(&mut store, OTHER_HUNK, "second occurrence".to_owned()));
645
        let first_id = reopened.for_hunk(HUNK)[0].id.clone();
646
        let second_id = reopened.for_hunk(OTHER_HUNK)[0].id.clone();
647
        assert!(reopened.edit(
648
            &mut store,
649
            OTHER_HUNK,
650
            &second_id,
651
            "edited second".to_owned(),
652
        ));
653
        assert!(reopened.delete(&mut store, HUNK, &first_id));
654
655
        let reopened = Comments::new(&store, targets);
656
        assert!(reopened.for_hunk(HUNK).is_empty());
657
        assert_eq!(reopened.for_hunk(OTHER_HUNK)[0].body, "edited second");
658
    }
659
660
    #[test]
661
    fn range_diff_commit_match_recovers_unique_changed_hunk() {
662
        let old_commit: Oid = "1111111111111111111111111111111111111111".parse().unwrap();
663
        let new_commit: Oid = "2222222222222222222222222222222222222222".parse().unwrap();
664
        let mut store = ReviewComments::parse(
665
            r#"{"id":1,"author":"A","timestamp":1,"heading":"1111111 old","path":"file","patch_id":"old","ordinal":0,"body":"retained"}"#,
666
        )
667
        .unwrap();
668
        store.remap_commits(&BTreeMap::from([(old_commit, new_commit)]));
669
        let targets = BTreeMap::from([(
670
            HUNK,
671
            CommentTarget {
672
                commit: new_commit,
673
                heading: "new".to_owned(),
674
                path: Some(PathBuf::from("file")),
675
                patch_id: PatchId::from("changed".to_owned()),
676
                ordinal: 0,
677
            },
678
        )]);
679
680
        let comments = Comments::new(&store, targets);
681
682
        assert_eq!(comments.for_hunk(HUNK)[0].body, "retained");
683
        assert!(store.encode().contains(&new_commit.to_string()));
684
    }
685
}