tuicr 0.15.0

Review AI-generated diffs like a GitHub pull request, right from your terminal.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Which side of the diff a line comment belongs to
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum LineSide {
    /// Comment on a deleted line (keyed by old_lineno)
    Old,
    /// Comment on an added or context line (keyed by new_lineno)
    #[default]
    New,
}

/// A range of lines for a comment (inclusive)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct LineRange {
    pub start: u32,
    pub end: u32,
}

impl LineRange {
    /// Create a new line range
    pub fn new(start: u32, end: u32) -> Self {
        Self {
            start: start.min(end),
            end: start.max(end),
        }
    }

    /// Create a single-line range
    pub fn single(line: u32) -> Self {
        Self {
            start: line,
            end: line,
        }
    }

    /// Check if this is a single-line range
    pub fn is_single(&self) -> bool {
        self.start == self.end
    }

    /// Check if this range contains a given line
    pub fn contains(&self, line: u32) -> bool {
        line >= self.start && line <= self.end
    }
}

/// Lifecycle state of a local comment relative to the remote forge.
///
/// `LocalDraft` is editable in tuicr. `PushedDraft` and `Submitted` are locked:
/// they have been written to GitHub and edits/deletions in tuicr would diverge
/// from the remote. PR 5 introduces the field and the lock check; PR 6 wires
/// the transitions on successful submit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum CommentLifecycleState {
    #[default]
    LocalDraft,
    PushedDraft,
    Submitted,
}

impl CommentLifecycleState {
    /// True for any state that has already been written to the remote forge.
    pub fn is_locked(self) -> bool {
        !matches!(self, CommentLifecycleState::LocalDraft)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub enum CommentType {
    #[default]
    Note,
    Suggestion,
    Issue,
    Praise,
    Custom(String),
}

impl CommentType {
    pub fn from_id(id: &str) -> Self {
        match id.to_ascii_lowercase().as_str() {
            "note" => Self::Note,
            "suggestion" => Self::Suggestion,
            "issue" => Self::Issue,
            "praise" => Self::Praise,
            _ => Self::Custom(id.to_string()),
        }
    }

    pub fn id(&self) -> &str {
        match self {
            CommentType::Note => "note",
            CommentType::Suggestion => "suggestion",
            CommentType::Issue => "issue",
            CommentType::Praise => "praise",
            CommentType::Custom(id) => id.as_str(),
        }
    }

    pub fn as_str(&self) -> String {
        self.id().to_ascii_uppercase()
    }
}

impl Serialize for CommentType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.id())
    }
}

impl<'de> Deserialize<'de> for CommentType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Ok(Self::from_id(&value))
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LineContext {
    pub new_line: Option<u32>,
    pub old_line: Option<u32>,
    pub content: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Comment {
    pub id: String,
    pub content: String,
    pub comment_type: CommentType,
    pub created_at: DateTime<Utc>,
    pub line_context: Option<LineContext>,
    /// Which side of the diff this comment belongs to (for line comments)
    /// None for file-level comments, defaults to New for backward compatibility
    #[serde(default)]
    pub side: Option<LineSide>,
    /// Line range for multi-line comments (for line comments)
    /// None for file-level comments or single-line comments (backward compatibility)
    #[serde(default)]
    pub line_range: Option<LineRange>,
    /// Where this comment sits in its remote forge lifecycle. Old session
    /// JSON predates this field and rehydrates as `LocalDraft`.
    #[serde(default)]
    pub lifecycle_state: CommentLifecycleState,
    /// Remote review ID this comment belongs to once submitted/pushed.
    /// `None` while still `LocalDraft`.
    #[serde(default)]
    pub remote_review_id: Option<String>,
    /// Remote review-comment ID once GitHub assigns one. Only meaningful for
    /// inline comments; review-level / summary comments don't get one.
    #[serde(default)]
    pub remote_comment_id: Option<String>,
}

impl Comment {
    pub fn new(content: String, comment_type: CommentType, side: Option<LineSide>) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            content,
            comment_type,
            created_at: Utc::now(),
            line_context: None,
            side,
            line_range: None,
            lifecycle_state: CommentLifecycleState::default(),
            remote_review_id: None,
            remote_comment_id: None,
        }
    }

    /// Create a new comment with a line range
    pub fn new_with_range(
        content: String,
        comment_type: CommentType,
        side: Option<LineSide>,
        line_range: LineRange,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            content,
            comment_type,
            created_at: Utc::now(),
            line_context: None,
            side,
            line_range: Some(line_range),
            lifecycle_state: CommentLifecycleState::default(),
            remote_review_id: None,
            remote_comment_id: None,
        }
    }

    /// True if this comment has been pushed/submitted to the forge and is
    /// therefore locked from local edits/deletions.
    pub fn is_locked(&self) -> bool {
        self.lifecycle_state.is_locked()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod line_range_tests {
        use super::*;

        #[test]
        fn new_creates_range_with_correct_bounds() {
            let range = LineRange::new(10, 20);
            assert_eq!(range.start, 10);
            assert_eq!(range.end, 20);
        }

        #[test]
        fn new_normalizes_reversed_bounds() {
            // When start > end, new() should normalize them
            let range = LineRange::new(20, 10);
            assert_eq!(range.start, 10);
            assert_eq!(range.end, 20);
        }

        #[test]
        fn single_creates_single_line_range() {
            let range = LineRange::single(42);
            assert_eq!(range.start, 42);
            assert_eq!(range.end, 42);
        }

        #[test]
        fn is_single_returns_true_for_single_line() {
            let range = LineRange::single(10);
            assert!(range.is_single());
        }

        #[test]
        fn is_single_returns_false_for_multi_line() {
            let range = LineRange::new(10, 15);
            assert!(!range.is_single());
        }

        #[test]
        fn contains_returns_true_for_start_line() {
            let range = LineRange::new(10, 20);
            assert!(range.contains(10));
        }

        #[test]
        fn contains_returns_true_for_end_line() {
            let range = LineRange::new(10, 20);
            assert!(range.contains(20));
        }

        #[test]
        fn contains_returns_true_for_middle_line() {
            let range = LineRange::new(10, 20);
            assert!(range.contains(15));
        }

        #[test]
        fn contains_returns_false_for_line_before_range() {
            let range = LineRange::new(10, 20);
            assert!(!range.contains(5));
        }

        #[test]
        fn contains_returns_false_for_line_after_range() {
            let range = LineRange::new(10, 20);
            assert!(!range.contains(25));
        }

        #[test]
        fn single_line_range_contains_only_that_line() {
            let range = LineRange::single(42);
            assert!(!range.contains(41));
            assert!(range.contains(42));
            assert!(!range.contains(43));
        }

        #[test]
        fn line_range_serializes_correctly() {
            let range = LineRange::new(10, 20);
            let json = serde_json::to_string(&range).unwrap();
            assert!(json.contains("\"start\":10"));
            assert!(json.contains("\"end\":20"));
        }

        #[test]
        fn line_range_deserializes_correctly() {
            let json = r#"{"start":10,"end":20}"#;
            let range: LineRange = serde_json::from_str(json).unwrap();
            assert_eq!(range.start, 10);
            assert_eq!(range.end, 20);
        }
    }

    mod comment_tests {
        use super::*;

        #[test]
        fn comment_type_serializes_custom_type_as_string() {
            let comment_type = CommentType::from_id("question");
            let json = serde_json::to_string(&comment_type).unwrap();
            assert_eq!(json, "\"question\"");
        }

        #[test]
        fn comment_type_deserializes_custom_type_from_string() {
            let json = "\"question\"";
            let comment_type: CommentType = serde_json::from_str(json).unwrap();
            assert_eq!(comment_type.id(), "question");
        }

        #[test]
        fn new_creates_comment_without_line_range() {
            let comment = Comment::new(
                "Test comment".to_string(),
                CommentType::Note,
                Some(LineSide::New),
            );
            assert!(comment.line_range.is_none());
            assert_eq!(comment.content, "Test comment");
            assert_eq!(comment.comment_type, CommentType::Note);
            assert_eq!(comment.side, Some(LineSide::New));
        }

        #[test]
        fn new_with_range_creates_comment_with_line_range() {
            let range = LineRange::new(10, 15);
            let comment = Comment::new_with_range(
                "Range comment".to_string(),
                CommentType::Issue,
                Some(LineSide::Old),
                range,
            );
            assert!(comment.line_range.is_some());
            let stored_range = comment.line_range.unwrap();
            assert_eq!(stored_range.start, 10);
            assert_eq!(stored_range.end, 15);
            assert_eq!(comment.side, Some(LineSide::Old));
        }

        #[test]
        fn comment_with_line_range_serializes_correctly() {
            let range = LineRange::new(10, 15);
            let comment = Comment::new_with_range(
                "Test".to_string(),
                CommentType::Note,
                Some(LineSide::New),
                range,
            );
            let json = serde_json::to_string(&comment).unwrap();
            assert!(json.contains("\"line_range\""));
            assert!(json.contains("\"start\":10"));
            assert!(json.contains("\"end\":15"));
        }

        #[test]
        fn comment_without_line_range_deserializes_with_none() {
            // Simulate old format without line_range field
            let json = r#"{
                "id": "test-id",
                "content": "Test comment",
                "comment_type": "note",
                "created_at": "2024-01-01T00:00:00Z",
                "line_context": null,
                "side": "new"
            }"#;
            let comment: Comment = serde_json::from_str(json).unwrap();
            assert!(comment.line_range.is_none());
            assert_eq!(comment.content, "Test comment");
        }

        #[test]
        fn comment_with_line_range_deserializes_correctly() {
            let json = r#"{
                "id": "test-id",
                "content": "Range comment",
                "comment_type": "issue",
                "created_at": "2024-01-01T00:00:00Z",
                "line_context": null,
                "side": "old",
                "line_range": {"start": 10, "end": 15}
            }"#;
            let comment: Comment = serde_json::from_str(json).unwrap();
            assert!(comment.line_range.is_some());
            let range = comment.line_range.unwrap();
            assert_eq!(range.start, 10);
            assert_eq!(range.end, 15);
        }

        #[test]
        fn should_default_lifecycle_state_to_local_draft_for_new_comment() {
            // given/when
            let comment = Comment::new("hi".to_string(), CommentType::Note, None);
            // then
            assert_eq!(comment.lifecycle_state, CommentLifecycleState::LocalDraft);
            assert!(!comment.is_locked());
            assert!(comment.remote_review_id.is_none());
            assert!(comment.remote_comment_id.is_none());
        }

        #[test]
        fn should_report_pushed_and_submitted_comments_as_locked() {
            // given
            let mut pushed = Comment::new("p".to_string(), CommentType::Note, None);
            pushed.lifecycle_state = CommentLifecycleState::PushedDraft;
            let mut submitted = Comment::new("s".to_string(), CommentType::Note, None);
            submitted.lifecycle_state = CommentLifecycleState::Submitted;
            // then
            assert!(pushed.is_locked());
            assert!(submitted.is_locked());
        }

        #[test]
        fn should_roundtrip_lifecycle_fields_via_serde() {
            // given
            let mut original = Comment::new("body".to_string(), CommentType::Issue, None);
            original.lifecycle_state = CommentLifecycleState::Submitted;
            original.remote_review_id = Some("R_kgDOEx".to_string());
            original.remote_comment_id = Some("RC_kgDOEx".to_string());
            // when
            let json = serde_json::to_string(&original).unwrap();
            let restored: Comment = serde_json::from_str(&json).unwrap();
            // then
            assert_eq!(restored.lifecycle_state, CommentLifecycleState::Submitted);
            assert_eq!(restored.remote_review_id.as_deref(), Some("R_kgDOEx"));
            assert_eq!(restored.remote_comment_id.as_deref(), Some("RC_kgDOEx"));
        }

        #[test]
        fn should_default_lifecycle_fields_for_pre_pr5_comment_json() {
            // given — JSON saved before PR 5 introduced lifecycle fields.
            let json = r#"{
                "id": "legacy",
                "content": "pre-pr5",
                "comment_type": "note",
                "created_at": "2024-01-01T00:00:00Z",
                "line_context": null
            }"#;
            // when
            let comment: Comment =
                serde_json::from_str(json).expect("pre-PR-5 comment JSON should parse");
            // then
            assert_eq!(comment.lifecycle_state, CommentLifecycleState::LocalDraft);
            assert!(comment.remote_review_id.is_none());
            assert!(comment.remote_comment_id.is_none());
            // and the rest of the comment survived
            assert_eq!(comment.id, "legacy");
            assert_eq!(comment.content, "pre-pr5");
        }
    }
}