crates/brain/src/comments.rs 26.2 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
/// Resolution state selected by the comments command.
112
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
113
pub enum CommentState {
114
    /// Comments that still require action.
115
    Unresolved,
116
    /// Comments that have been resolved.
117
    Resolved,
118
}
119
120
/// One persisted comment row.
121
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
122
struct CommentRecord {
123
    /// Commit containing the hunk, when recorded by a commit-aware version.
124
    commit: Option<Oid>,
125
    /// Stable local comment id.
126
    id: CommentId,
127
    /// Author shown for this comment.
128
    author: String,
129
    /// Unix timestamp when the comment was authored.
130
    timestamp: u64,
131
    /// Heading identifying the reviewed item.
132
    heading: String,
133
    /// Optional file path associated with the hunk.
134
    path: Option<PathBuf>,
135
    /// Stable patch id of the hunk the comment is attached to.
136
    patch_id: PatchId,
137
    /// Occurrence of this patch id within the commit.
138
    ordinal: u32,
139
    /// Comment body.
140
    body: String,
141
    /// Unix timestamp when the comment was resolved.
142
    resolved: Option<u64>,
143
}
144
145
/// One comment row emitted by the non-interactive comments command.
146
#[derive(Serialize)]
147
struct CommentOutput<'a> {
148
    /// Stable local comment id.
149
    id: &'a CommentId,
150
    /// Author shown for this comment.
151
    author: &'a str,
152
    /// Unix timestamp when the comment was authored.
153
    timestamp: u64,
154
    /// Heading identifying the reviewed item.
155
    heading: &'a str,
156
    /// Optional file path associated with the hunk.
157
    path: &'a Option<PathBuf>,
158
    /// Current new-side line where the hunk starts.
159
    line: Option<u32>,
160
    /// Stable patch id of the hunk the comment is attached to.
161
    #[serde(rename = "patchId")]
162
    patch_id: &'a PatchId,
163
    /// Occurrence of this patch id within the commit.
164
    ordinal: u32,
165
    /// Comment body.
166
    body: &'a str,
167
}
168
169
/// Per-commit comment view keyed by the commit's hunk ids.
170
#[derive(Clone, Debug)]
171
pub struct Comments {
172
    /// Comments keyed by the hunk they were authored on.
173
    by_hunk: BTreeMap<HunkId, Vec<Comment>>,
174
    /// Hunk metadata used to persist newly authored comments.
175
    targets: BTreeMap<HunkId, CommentTarget>,
176
}
177
178
impl ReviewComments {
179
    /// Parses persisted JSONL text; empty text yields an empty store.
180
    pub fn parse(text: &str) -> io::Result<Self> {
181
        let mut records = Vec::new();
182
        for line in text.lines().filter(|line| !line.trim().is_empty()) {
183
            let record = json::from_str(line)
184
                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "malformed comment"))?;
185
            records.push(record);
186
        }
187
        Ok(Self {
188
            records,
189
            author: default_author(),
190
        })
191
    }
192
193
    /// Encodes all comment rows as JSONL text for persistence.
194
    pub fn encode(&self) -> String {
195
        let mut rows = String::new();
196
        for record in &self.records {
197
            rows.push_str(&json::to_string(record));
198
            rows.push('\n');
199
        }
200
        rows
201
    }
202
    /// Writes public comment rows in `state` as JSONL, resolving each hunk's current line.
203
    pub fn write_jsonl(
204
        &self,
205
        mut writer: impl io::Write,
206
        state: CommentState,
207
        line_for: impl Fn(&PatchId, u32) -> Option<u32>,
208
    ) -> io::Result<()> {
209
        for record in self.records.iter().filter(|record| {
210
            matches!(
211
                (state, record.resolved),
212
                (CommentState::Unresolved, None) | (CommentState::Resolved, Some(_))
213
            )
214
        }) {
215
            let output = CommentOutput {
216
                id: &record.id,
217
                author: &record.author,
218
                timestamp: record.timestamp,
219
                heading: &record.heading,
220
                path: &record.path,
221
                line: line_for(&record.patch_id, record.ordinal),
222
                patch_id: &record.patch_id,
223
                ordinal: record.ordinal,
224
                body: &record.body,
225
            };
226
            writeln!(writer, "{}", json::to_string(&output))?;
227
        }
228
        Ok(())
229
    }
230
231
    /// Returns the author name used for newly authored comments.
232
    pub fn author(&self) -> &str {
233
        &self.author
234
    }
235
236
    /// Selects the author name used for newly authored comments.
237
    pub(crate) fn set_author(&mut self, author: String) {
238
        if !author.trim().is_empty() {
239
            self.author = author;
240
        }
241
    }
242
243
    /// Returns the number of stored comment rows.
244
    pub fn len(&self) -> usize {
245
        self.records.len()
246
    }
247
248
    /// Returns the number of comments attached to one patch occurrence.
249
    pub fn matching_count(&self, commit: Oid, patch_id: &PatchId, ordinal: u32) -> usize {
250
        self.records
251
            .iter()
252
            .filter(|record| {
253
                record.resolved.is_none()
254
                    && record.patch_id == *patch_id
255
                    && record.ordinal == ordinal
256
                    && record.commit.is_none_or(|stored| stored == commit)
257
            })
258
            .count()
259
    }
260
261
    /// Returns comments attached exactly to `target`, in storage order.
262
    fn matching(&self, target: &CommentTarget) -> Vec<Comment> {
263
        self.records
264
            .iter()
265
            .filter(|record| {
266
                record.resolved.is_none()
267
                    && record.patch_id == target.patch_id
268
                    && record.ordinal == target.ordinal
269
                    && record.commit.is_none_or(|commit| commit == target.commit)
270
            })
271
            .map(Comment::from)
272
            .collect()
273
    }
274
275
    /// Rewrites persisted commit anchors using range-diff correspondence.
276
    ///
277
    /// Older rows recover their commit from the abbreviated object id at the
278
    /// start of the persisted heading when it identifies exactly one pair.
279
    pub fn remap_commits(&mut self, commits: &BTreeMap<Oid, Oid>) {
280
        for record in &mut self.records {
281
            if let Some(commit) = record.commit {
282
                if let Some(mapped) = commits.get(&commit) {
283
                    record.commit = Some(*mapped);
284
                }
285
                continue;
286
            }
287
            let Some(prefix) = record.heading.split_whitespace().next() else {
288
                continue;
289
            };
290
            let mut matches = commits
291
                .iter()
292
                .filter(|(old, _)| old.to_string().starts_with(prefix));
293
            let Some((_, mapped)) = matches.next() else {
294
                continue;
295
            };
296
            if matches.next().is_none() {
297
                record.commit = Some(*mapped);
298
            }
299
        }
300
    }
301
302
    /// Adds one comment row for `target` and returns its view.
303
    fn add(&mut self, target: &CommentTarget, body: String) -> Comment {
304
        let timestamp = SystemTime::now()
305
            .duration_since(UNIX_EPOCH)
306
            .unwrap_or_default()
307
            .as_secs();
308
        let record = CommentRecord {
309
            id: self.next_id(),
310
            author: self.author.clone(),
311
            timestamp,
312
            heading: target.heading.clone(),
313
            commit: Some(target.commit),
314
            path: target.path.clone(),
315
            patch_id: target.patch_id.clone(),
316
            ordinal: target.ordinal,
317
            body,
318
            resolved: None,
319
        };
320
        let comment = Comment::from(&record);
321
        self.records.push(record);
322
323
        comment
324
    }
325
326
    /// Replaces the body of the comment with `id`.
327
    fn edit(&mut self, id: &CommentId, body: String) -> bool {
328
        let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else {
329
            return false;
330
        };
331
        record.body = body;
332
        true
333
    }
334
335
    /// Resolves the comment with `id`.
336
    pub fn resolve(&mut self, id: &CommentId) -> bool {
337
        let Some(record) = self.records.iter_mut().find(|record| record.id == *id) else {
338
            return false;
339
        };
340
        if record.resolved.is_some() {
341
            return true;
342
        }
343
        record.resolved = Some(
344
            SystemTime::now()
345
                .duration_since(UNIX_EPOCH)
346
                .unwrap_or_default()
347
                .as_secs(),
348
        );
349
        true
350
    }
351
352
    /// Deletes the comment with `id`.
353
    fn delete(&mut self, id: &CommentId) -> bool {
354
        let Some(index) = self.records.iter().position(|record| record.id == *id) else {
355
            return false;
356
        };
357
        self.records.remove(index);
358
        true
359
    }
360
361
    /// Returns the next stable local comment id.
362
    fn next_id(&self) -> CommentId {
363
        let next = self
364
            .records
365
            .iter()
366
            .map(|record| record.id.as_u64())
367
            .max()
368
            .unwrap_or_default()
369
            .saturating_add(1);
370
        CommentId::from(next)
371
    }
372
373
    /// Applies the difference between two snapshots without replacing unrelated rows.
374
    pub(crate) fn merge(&mut self, previous: &Self, updated: &Self) {
375
        for record in &previous.records {
376
            if !updated
377
                .records
378
                .iter()
379
                .any(|candidate| candidate.id == record.id)
380
            {
381
                self.delete(&record.id);
382
            }
383
        }
384
        for record in &updated.records {
385
            match previous
386
                .records
387
                .iter()
388
                .find(|candidate| candidate.id == record.id)
389
            {
390
                Some(previous) if previous != record => {
391
                    if let Some(current) = self
392
                        .records
393
                        .iter_mut()
394
                        .find(|candidate| candidate.id == record.id)
395
                    {
396
                        *current = record.clone();
397
                    }
398
                }
399
                None => {
400
                    let mut added = record.clone();
401
                    added.id = self.next_id();
402
                    self.records.push(added);
403
                }
404
                _ => {}
405
            }
406
        }
407
    }
408
}
409
410
impl From<&CommentRecord> for Comment {
411
    fn from(record: &CommentRecord) -> Self {
412
        Self {
413
            id: record.id.clone(),
414
            author: record.author.clone(),
415
            timestamp: record.timestamp,
416
            body: record.body.clone(),
417
        }
418
    }
419
}
420
421
impl Comments {
422
    /// Creates a comment view for a commit's hunk targets.
423
    pub fn new(store: &ReviewComments, targets: BTreeMap<HunkId, CommentTarget>) -> Self {
424
        let mut by_hunk = targets
425
            .iter()
426
            .filter_map(|(hunk, target)| {
427
                let comments = store.matching(target);
428
                (!comments.is_empty()).then_some((*hunk, comments))
429
            })
430
            .collect::<BTreeMap<_, _>>();
431
        for record in &store.records {
432
            let Some(commit) = record.commit else {
433
                continue;
434
            };
435
            let exact = targets.values().any(|target| {
436
                target.commit == commit
437
                    && target.patch_id == record.patch_id
438
                    && target.ordinal == record.ordinal
439
            });
440
            if exact {
441
                continue;
442
            }
443
            let mut candidates = targets
444
                .iter()
445
                .filter(|(_, target)| target.commit == commit && target.path == record.path);
446
            let Some((hunk, _)) = candidates.next() else {
447
                continue;
448
            };
449
            if candidates.next().is_none() {
450
                by_hunk
451
                    .entry(*hunk)
452
                    .or_default()
453
                    .push(Comment::from(record));
454
            }
455
        }
456
457
        Self { by_hunk, targets }
458
    }
459
460
    /// Applies one comment mutation and returns the encoded updated store.
461
    ///
462
    /// The caller must persist the returned text through the session command
463
    /// worker and restore its snapshot if that command fails.
464
    pub fn transact(
465
        &mut self,
466
        store: &mut ReviewComments,
467
        update: impl FnOnce(&mut Self, &mut ReviewComments) -> bool,
468
    ) -> Option<String> {
469
        let mut updated_store = store.clone();
470
        let mut updated_view = self.clone();
471
        if !update(&mut updated_view, &mut updated_store) {
472
            return None;
473
        }
474
        let encoded = updated_store.encode();
475
        *store = updated_store;
476
        *self = updated_view;
477
        Some(encoded)
478
    }
479
480
    /// Authors a comment on `hunk` into `store`, returning whether one was
481
    /// added. The caller is responsible for persisting the updated store.
482
    pub fn author(&mut self, store: &mut ReviewComments, hunk: HunkId, body: String) -> bool {
483
        let Some(target) = self.targets.get(&hunk) else {
484
            return false;
485
        };
486
        let comment = store.add(target, body);
487
        self.by_hunk.entry(hunk).or_default().push(comment);
488
        true
489
    }
490
491
    /// Edits one comment on `hunk`.
492
    pub fn edit(
493
        &mut self,
494
        store: &mut ReviewComments,
495
        hunk: HunkId,
496
        id: &CommentId,
497
        body: String,
498
    ) -> bool {
499
        let Some(comments) = self.by_hunk.get_mut(&hunk) else {
500
            return false;
501
        };
502
        let Some(comment) = comments.iter_mut().find(|comment| comment.id == *id) else {
503
            return false;
504
        };
505
        if !store.edit(id, body.clone()) {
506
            return false;
507
        }
508
        comment.body = body;
509
        true
510
    }
511
512
    /// Deletes one comment from `hunk`.
513
    pub fn delete(&mut self, store: &mut ReviewComments, hunk: HunkId, id: &CommentId) -> bool {
514
        let Some(comments) = self.by_hunk.get_mut(&hunk) else {
515
            return false;
516
        };
517
        let Some(index) = comments.iter().position(|comment| comment.id == *id) else {
518
            return false;
519
        };
520
        if !store.delete(id) {
521
            return false;
522
        }
523
        comments.remove(index);
524
        if comments.is_empty() {
525
            self.by_hunk.remove(&hunk);
526
        }
527
        true
528
    }
529
530
    /// Returns the comments authored on `hunk`.
531
    pub fn for_hunk(&self, hunk: HunkId) -> &[Comment] {
532
        self.by_hunk.get(&hunk).map_or(&[], Vec::as_slice)
533
    }
534
535
    /// Returns the total number of comments in this commit view.
536
    pub fn len(&self) -> usize {
537
        self.by_hunk.values().map(Vec::len).sum()
538
    }
539
540
    /// Returns per-hunk comment counts, for decoration snapshots.
541
    pub fn counts(&self) -> BTreeMap<HunkId, usize> {
542
        self.by_hunk
543
            .iter()
544
            .map(|(hunk, comments)| (*hunk, comments.len()))
545
            .collect()
546
    }
547
548
    /// Rebuilds this per-hunk view from an updated review-wide store.
549
    pub fn refresh(&mut self, store: &ReviewComments) {
550
        *self = Self::new(store, self.targets.clone());
551
    }
552
}
553
554
/// Encodes arbitrary review identity text as one path or refname component.
555
pub(crate) fn encode_component(input: &str) -> String {
556
    let mut encoded = String::new();
557
    for byte in input.bytes() {
558
        match byte {
559
            b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'.' | b'_' | b'-' => {
560
                encoded.push(byte as char);
561
            }
562
            _ => {
563
                write!(encoded, "%{byte:02x}").ok();
564
            }
565
        }
566
    }
567
    encoded
568
}
569
570
/// Decodes a review identity text from one encoded refname component.
571
pub(crate) fn decode_component(input: &str) -> String {
572
    let mut decoded = Vec::with_capacity(input.len());
573
    let mut bytes = input.as_bytes().iter().copied();
574
575
    while let Some(byte) = bytes.next() {
576
        if byte != b'%' {
577
            decoded.push(byte);
578
            continue;
579
        }
580
581
        let Some(high) = bytes.next() else {
582
            decoded.push(byte);
583
            break;
584
        };
585
        let Some(low) = bytes.next() else {
586
            decoded.extend([byte, high]);
587
            break;
588
        };
589
        match (hex_value(high), hex_value(low)) {
590
            (Some(high), Some(low)) => decoded.push(high << 4 | low),
591
            _ => decoded.extend([byte, high, low]),
592
        }
593
    }
594
595
    String::from_utf8_lossy(&decoded).into_owned()
596
}
597
598
/// Returns the numeric value of one hexadecimal digit.
599
fn hex_value(byte: u8) -> Option<u8> {
600
    match byte {
601
        b'0'..=b'9' => Some(byte - b'0'),
602
        b'a'..=b'f' => Some(byte - b'a' + 10),
603
        b'A'..=b'F' => Some(byte - b'A' + 10),
604
        _ => None,
605
    }
606
}
607
608
/// Returns the author name used for newly authored comments.
609
fn default_author() -> String {
610
    std::env::var("GIT_AUTHOR_NAME")
611
        .ok()
612
        .filter(|name| !name.trim().is_empty())
613
        .or_else(|| {
614
            std::env::var("USER")
615
                .ok()
616
                .filter(|name| !name.trim().is_empty())
617
        })
618
        .unwrap_or_else(|| "You".to_owned())
619
}
620
621
#[cfg(test)]
622
mod tests {
623
    use super::*;
624
625
    /// Hunk used by comment view tests.
626
    const HUNK: HunkId = HunkId::new(0);
627
    /// Second hunk used by comment view tests.
628
    const OTHER_HUNK: HunkId = HunkId::new(1);
629
630
    /// Builds an empty comment store and matching hunk view.
631
    fn empty_comments() -> (ReviewComments, Comments) {
632
        let target = CommentTarget {
633
            commit: "1111111111111111111111111111111111111111".parse().unwrap(),
634
            heading: "h".to_owned(),
635
            path: None,
636
            patch_id: PatchId::from("p".to_owned()),
637
            ordinal: 0,
638
        };
639
        let mut targets = BTreeMap::new();
640
        targets.insert(HUNK, target);
641
        let store = ReviewComments::parse("").unwrap();
642
        let comments = Comments::new(&store, targets);
643
        (store, comments)
644
    }
645
646
    #[test]
647
    fn output_selects_comment_resolution_state() {
648
        let mut store = ReviewComments::parse(
649
            "{\"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}",
650
        )
651
        .unwrap();
652
653
        let mut output = Vec::new();
654
        store
655
            .write_jsonl(&mut output, CommentState::Unresolved, |_, _| None)
656
            .unwrap();
657
        assert!(
658
            String::from_utf8(output)
659
                .unwrap()
660
                .contains(r#""body":"open""#)
661
        );
662
663
        let mut output = Vec::new();
664
        store
665
            .write_jsonl(&mut output, CommentState::Resolved, |_, _| None)
666
            .unwrap();
667
        assert!(
668
            String::from_utf8(output)
669
                .unwrap()
670
                .contains(r#""body":"done""#)
671
        );
672
673
        assert!(store.resolve(&CommentId::from(1)));
674
        assert_eq!(
675
            store.matching_count(
676
                "1111111111111111111111111111111111111111".parse().unwrap(),
677
                &PatchId::from("p".to_owned()),
678
                0,
679
            ),
680
            0
681
        );
682
    }
683
684
    #[test]
685
    fn comment_id_serializes_as_number() {
686
        let id = CommentId::from(7);
687
688
        assert_eq!(json::to_string(&id), "7");
689
        assert_eq!(json::from_str::<CommentId>("7").unwrap(), id);
690
    }
691
692
    #[test]
693
    fn next_id_continues_above_stored_ids() {
694
        let store = ReviewComments::parse(
695
            r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":null,"patch_id":"p","ordinal":0,"body":"old"}"#,
696
        )
697
        .unwrap();
698
699
        assert_eq!(store.next_id(), CommentId::from(8));
700
    }
701
    #[test]
702
    fn output_uses_public_schema() {
703
        let store = ReviewComments::parse(
704
            r#"{"id":7,"author":"A","timestamp":1,"heading":"h","path":"src/main.rs","patch_id":"p","ordinal":0,"body":"old"}"#,
705
        )
706
        .unwrap();
707
708
        let mut output = Vec::new();
709
        store
710
            .write_jsonl(
711
                &mut output,
712
                CommentState::Unresolved,
713
                |patch_id, ordinal| (patch_id.as_str() == "p" && ordinal == 0).then_some(12),
714
            )
715
            .unwrap();
716
        assert_eq!(
717
            String::from_utf8(output).unwrap(),
718
            "{\"id\":7,\"author\":\"A\",\"timestamp\":1,\"heading\":\"h\",\"path\":\"src/main.rs\",\"line\":12,\"patchId\":\"p\",\"ordinal\":0,\"body\":\"old\"}\n"
719
        );
720
    }
721
722
    #[test]
723
    fn comments_edit_updates_store_and_view() {
724
        let (mut store, mut comments) = empty_comments();
725
726
        assert!(comments.author(&mut store, HUNK, "old".to_owned()));
727
        let id = comments.for_hunk(HUNK)[0].id.clone();
728
        assert!(comments.edit(&mut store, HUNK, &id, "new".to_owned()));
729
730
        assert_eq!(comments.for_hunk(HUNK)[0].body, "new");
731
        assert!(store.encode().contains(r#""body":"new""#));
732
    }
733
734
    #[test]
735
    fn comments_delete_updates_store_and_view() {
736
        let (mut store, mut comments) = empty_comments();
737
738
        assert!(comments.author(&mut store, HUNK, "body".to_owned()));
739
        let id = comments.for_hunk(HUNK)[0].id.clone();
740
        assert!(comments.delete(&mut store, HUNK, &id));
741
742
        assert!(comments.for_hunk(HUNK).is_empty());
743
        assert!(store.encode().is_empty());
744
    }
745
746
    #[test]
747
    fn identical_patch_occurrences_keep_comments_separate() {
748
        let first = CommentTarget {
749
            commit: "1111111111111111111111111111111111111111".parse().unwrap(),
750
            heading: "h".to_owned(),
751
            path: Some(PathBuf::from("file")),
752
            patch_id: PatchId::from("same".to_owned()),
753
            ordinal: 0,
754
        };
755
        let second = CommentTarget {
756
            ordinal: 1,
757
            ..first.clone()
758
        };
759
        let targets = BTreeMap::from([(HUNK, first), (OTHER_HUNK, second)]);
760
        let mut store = ReviewComments::parse("").unwrap();
761
        let mut comments = Comments::new(&store, targets.clone());
762
763
        assert!(comments.author(&mut store, HUNK, "first occurrence".to_owned()));
764
765
        let mut reopened = Comments::new(&store, targets.clone());
766
        assert_eq!(reopened.for_hunk(HUNK)[0].body, "first occurrence");
767
        assert!(reopened.for_hunk(OTHER_HUNK).is_empty());
768
769
        assert!(reopened.author(&mut store, OTHER_HUNK, "second occurrence".to_owned()));
770
        let first_id = reopened.for_hunk(HUNK)[0].id.clone();
771
        let second_id = reopened.for_hunk(OTHER_HUNK)[0].id.clone();
772
        assert!(reopened.edit(
773
            &mut store,
774
            OTHER_HUNK,
775
            &second_id,
776
            "edited second".to_owned(),
777
        ));
778
        assert!(reopened.delete(&mut store, HUNK, &first_id));
779
780
        let reopened = Comments::new(&store, targets);
781
        assert!(reopened.for_hunk(HUNK).is_empty());
782
        assert_eq!(reopened.for_hunk(OTHER_HUNK)[0].body, "edited second");
783
    }
784
785
    #[test]
786
    fn range_diff_commit_match_recovers_unique_changed_hunk() {
787
        let old_commit: Oid = "1111111111111111111111111111111111111111".parse().unwrap();
788
        let new_commit: Oid = "2222222222222222222222222222222222222222".parse().unwrap();
789
        let mut store = ReviewComments::parse(
790
            r#"{"id":1,"author":"A","timestamp":1,"heading":"1111111 old","path":"file","patch_id":"old","ordinal":0,"body":"retained"}"#,
791
        )
792
        .unwrap();
793
        store.remap_commits(&BTreeMap::from([(old_commit, new_commit)]));
794
        let targets = BTreeMap::from([(
795
            HUNK,
796
            CommentTarget {
797
                commit: new_commit,
798
                heading: "new".to_owned(),
799
                path: Some(PathBuf::from("file")),
800
                patch_id: PatchId::from("changed".to_owned()),
801
                ordinal: 0,
802
            },
803
        )]);
804
805
        let comments = Comments::new(&store, targets);
806
807
        assert_eq!(comments.for_hunk(HUNK)[0].body, "retained");
808
        assert!(store.encode().contains(&new_commit.to_string()));
809
    }
810
}