rivets 0.1.0

A Rust-based issue tracking system using JSONL storage
Documentation
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
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! CLI input validation functions.
//!
//! These validators are used by clap's `value_parser` attribute to validate
//! user input at parse time, providing immediate feedback for invalid values.

use crate::domain::MAX_TITLE_LENGTH;

/// Validate issue ID prefix format.
///
/// Delegates to the domain validator in `commands::init` to maintain
/// a single source of truth for validation rules.
pub fn validate_prefix(s: &str) -> Result<String, String> {
    use crate::commands::init;

    let trimmed = s.trim();
    init::validate_prefix(trimmed).map_err(|e| e.to_string())?;
    Ok(trimmed.to_string())
}

/// Validate issue ID format.
///
/// Expected format: `prefix-suffix` where:
/// - prefix: 2-20 alphanumeric characters
/// - suffix: 1+ alphanumeric characters
///
/// Examples: `proj-abc`, `rivets-12x`, `test-1`
pub fn validate_issue_id(s: &str) -> Result<String, String> {
    let s = s.trim();

    if s.is_empty() {
        return Err("Issue ID cannot be empty".to_string());
    }

    // Check for the prefix-suffix format (must have at least one hyphen)
    let parts: Vec<&str> = s.splitn(2, '-').collect();
    if parts.len() != 2 {
        return Err(format!(
            "Invalid issue ID format: '{}'. Expected format: prefix-suffix (e.g., proj-abc or proj-abc-123)",
            s
        ));
    }

    let prefix = parts[0];
    let suffix = parts[1];

    // Validate prefix using shared validation logic
    validate_prefix(prefix).map_err(|e| format!("Issue ID {}", e.to_lowercase()))?;

    // Validate suffix
    //
    // Note: We use explicit checks instead of regex (e.g., `^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$`)
    // to provide specific, actionable error messages and avoid adding regex as a dependency.
    // This approach is more maintainable for a CLI tool where user-facing errors matter.
    if suffix.is_empty() {
        return Err("Issue ID suffix cannot be empty".to_string());
    }

    // Suffix can contain alphanumerics and hyphens (for IDs like proj-abc-123)
    if !suffix
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '-')
    {
        return Err("Issue ID suffix must contain only alphanumerics and hyphens".to_string());
    }

    // Prevent edge cases: leading/trailing hyphens or consecutive hyphens
    // Equivalent to regex: ^[a-zA-Z0-9]+(-[a-zA-Z0-9]+)*$
    if suffix.starts_with('-') {
        return Err("Issue ID suffix cannot start with a hyphen".to_string());
    }

    if suffix.ends_with('-') {
        return Err("Issue ID suffix cannot end with a hyphen".to_string());
    }

    if suffix.contains("--") {
        return Err("Issue ID suffix cannot contain consecutive hyphens".to_string());
    }

    Ok(s.to_string())
}

/// Validate title length.
///
/// Title must not exceed MAX_TITLE_LENGTH (200 characters).
///
/// Examples: Valid titles under 200 chars
pub fn validate_title(s: &str) -> Result<String, String> {
    let s = s.trim();

    if s.is_empty() {
        return Err("Title cannot be empty".to_string());
    }

    if s.len() > MAX_TITLE_LENGTH {
        return Err(format!(
            "Title cannot exceed {} characters, got {} characters",
            MAX_TITLE_LENGTH,
            s.len()
        ));
    }

    // Check for newlines in title (titles should be single-line)
    if s.contains('\n') || s.contains('\r') {
        return Err("Title cannot contain newline characters".to_string());
    }

    // Check for control characters (0x00-0x1F except tab, and 0x7F-0x9F)
    // These can cause display issues and are likely user errors
    if let Some(pos) = s.chars().position(|c| {
        let code = c as u32;
        // Control characters excluding tab (0x09)
        (code < 0x20 && code != 0x09) || (0x7F..=0x9F).contains(&code)
    }) {
        return Err(format!(
            "Title contains invalid control character at position {}",
            pos
        ));
    }

    Ok(s.to_string())
}

/// Validate text field (description, notes, etc.)
///
/// Allows newlines but rejects control characters that could cause display issues.
/// Unlike titles, multi-line text is acceptable for descriptions and notes.
fn validate_text_field(s: &str, field_name: &str) -> Result<String, String> {
    // Check for control characters (0x00-0x1F except tab and newlines, and 0x7F-0x9F)
    if let Some(pos) = s.chars().position(|c| {
        let code = c as u32;
        // Control characters excluding tab (0x09), LF (0x0A), and CR (0x0D)
        (code < 0x20 && code != 0x09 && code != 0x0A && code != 0x0D)
            || (0x7F..=0x9F).contains(&code)
    }) {
        return Err(format!(
            "{} contains invalid control character at position {}",
            field_name, pos
        ));
    }

    Ok(s.to_string())
}

/// Validate description field
///
/// Wrapper for validate_text_field specifically for descriptions.
pub fn validate_description(s: &str) -> Result<String, String> {
    validate_text_field(s, "Description")
}

/// Maximum length for labels
pub const MAX_LABEL_LENGTH: usize = 50;

/// Validate label format.
///
/// Labels must be:
/// - 1-50 characters
/// - Lowercase alphanumeric, hyphens, and underscores only
/// - Must start and end with alphanumeric character
/// - No consecutive hyphens or underscores
///
/// Examples: `bug`, `high-priority`, `needs_review`, `v2`
pub fn validate_label(s: &str) -> Result<String, String> {
    let s = s.trim();

    if s.is_empty() {
        return Err("Label cannot be empty".to_string());
    }

    if s.len() > MAX_LABEL_LENGTH {
        return Err(format!(
            "Label cannot exceed {} characters, got {} characters",
            MAX_LABEL_LENGTH,
            s.len()
        ));
    }

    // Check for valid characters (lowercase alphanumeric, hyphens, underscores)
    if !s
        .chars()
        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-' || c == '_')
    {
        // Check if it contains uppercase to give a more specific error
        if s.chars().any(|c| c.is_ascii_uppercase()) {
            return Err(
                "Label must be lowercase. Use hyphens or underscores instead of spaces".to_string(),
            );
        }
        return Err(
            "Label must contain only lowercase letters, numbers, hyphens, and underscores"
                .to_string(),
        );
    }

    // Must start with alphanumeric
    if let Some(first) = s.chars().next() {
        if !first.is_ascii_alphanumeric() {
            return Err("Label must start with a letter or number".to_string());
        }
    }

    // Must end with alphanumeric
    if let Some(last) = s.chars().last() {
        if !last.is_ascii_alphanumeric() {
            return Err("Label must end with a letter or number".to_string());
        }
    }

    // No consecutive hyphens or underscores
    if s.contains("--") {
        return Err("Label cannot contain consecutive hyphens".to_string());
    }
    if s.contains("__") {
        return Err("Label cannot contain consecutive underscores".to_string());
    }

    Ok(s.to_string())
}

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

    // ========== Prefix Validation ==========

    #[test]
    fn test_validate_prefix_valid() {
        assert!(validate_prefix("proj").is_ok());
        assert!(validate_prefix("rivets").is_ok());
        assert!(validate_prefix("AB").is_ok());
        assert!(validate_prefix("test123").is_ok());
        assert!(validate_prefix("a1b2c3d4e5f6g7h8i9j0").is_ok()); // 20 chars
    }

    #[test]
    fn test_validate_prefix_too_short() {
        let result = validate_prefix("a");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("at least 2 characters"));
    }

    #[test]
    fn test_validate_prefix_too_long() {
        let result = validate_prefix("a".repeat(21).as_str());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot exceed 20"));
    }

    #[test]
    fn test_validate_prefix_invalid_chars() {
        assert!(validate_prefix("proj-test").is_err()); // hyphen
        assert!(validate_prefix("proj_test").is_err()); // underscore
        assert!(validate_prefix("proj test").is_err()); // space
        assert!(validate_prefix("proj.test").is_err()); // dot
    }

    #[test]
    fn test_validate_prefix_trims_whitespace() {
        assert_eq!(validate_prefix("  proj  ").unwrap(), "proj");
    }

    // ========== Issue ID Validation ==========

    #[test]
    fn test_validate_issue_id_valid() {
        assert!(validate_issue_id("proj-abc").is_ok());
        assert!(validate_issue_id("rivets-123").is_ok());
        assert!(validate_issue_id("ab-1").is_ok());
        assert!(validate_issue_id("TEST-xyz").is_ok());
    }

    #[test]
    fn test_validate_issue_id_empty() {
        let result = validate_issue_id("");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot be empty"));
    }

    #[test]
    fn test_validate_issue_id_no_hyphen() {
        let result = validate_issue_id("projabc");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Expected format"));
    }

    #[test]
    fn test_validate_issue_id_empty_suffix() {
        let result = validate_issue_id("proj-");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("suffix cannot be empty"));
    }

    #[test]
    fn test_validate_issue_id_prefix_too_short() {
        let result = validate_issue_id("a-123");
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_lowercase()
            .contains("at least 2 characters"));
    }

    #[test]
    fn test_validate_issue_id_invalid_chars() {
        assert!(validate_issue_id("proj-abc_123").is_err()); // underscore in suffix
        assert!(validate_issue_id("proj_test-abc").is_err()); // underscore in prefix
    }

    #[test]
    fn test_validate_issue_id_multiple_hyphens() {
        // Issue IDs with multiple hyphens in suffix should now be valid
        assert!(validate_issue_id("proj-abc-123").is_ok());
        assert!(validate_issue_id("rivets-feature-xyz").is_ok());
        assert!(validate_issue_id("test-a-b-c-d").is_ok());
        assert_eq!(validate_issue_id("proj-abc-123").unwrap(), "proj-abc-123");
    }

    #[test]
    fn test_validate_issue_id_prefix_exactly_20_chars() {
        let prefix_20 = "a".repeat(20);
        let issue_id = format!("{}-xyz", prefix_20);
        assert!(validate_issue_id(&issue_id).is_ok());
    }

    #[test]
    fn test_validate_issue_id_prefix_21_chars() {
        let prefix_21 = "a".repeat(21);
        let issue_id = format!("{}-xyz", prefix_21);
        let result = validate_issue_id(&issue_id);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_lowercase()
            .contains("cannot exceed 20"));
    }

    #[test]
    fn test_validate_issue_id_leading_hyphen_suffix() {
        // `proj--abc` has a leading hyphen in the suffix (after the first hyphen)
        let result = validate_issue_id("proj--abc");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot start with a hyphen"));
    }

    #[test]
    fn test_validate_issue_id_trailing_hyphen_suffix() {
        let result = validate_issue_id("proj-abc-");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot end with a hyphen"));
    }

    #[test]
    fn test_validate_issue_id_consecutive_hyphens() {
        let result = validate_issue_id("proj-a--b");
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("cannot contain consecutive hyphens"));
    }

    // ========== Title Validation ==========

    #[test]
    fn test_validate_title_valid() {
        assert!(validate_title("Short title").is_ok());
        assert!(validate_title("A".repeat(200).as_str()).is_ok()); // Exactly 200 chars
    }

    #[test]
    fn test_validate_title_empty() {
        let result = validate_title("");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot be empty"));
    }

    #[test]
    fn test_validate_title_too_long() {
        let long_title = "A".repeat(201);
        let result = validate_title(&long_title);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot exceed 200"));
    }

    #[test]
    fn test_validate_title_exactly_max_length() {
        let max_title = "A".repeat(200);
        assert!(validate_title(&max_title).is_ok());
        assert_eq!(validate_title(&max_title).unwrap().len(), 200);
    }

    #[test]
    fn test_validate_title_trims_whitespace() {
        assert_eq!(validate_title("  Test Title  ").unwrap(), "Test Title");
    }

    #[test]
    fn test_validate_title_whitespace_only() {
        let result = validate_title("   ");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot be empty"));
    }

    #[test]
    fn test_validate_title_with_newline() {
        let result = validate_title("Title with\nnewline");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("newline"));
    }

    #[test]
    fn test_validate_title_with_carriage_return() {
        let result = validate_title("Title with\rcarriage return");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("newline"));
    }

    #[test]
    fn test_validate_title_with_control_character() {
        // Test with null character (0x00)
        let result = validate_title("Title with\x00control");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("control character"));
    }

    #[test]
    fn test_validate_title_with_tab_allowed() {
        // Tab (0x09) should be allowed
        let result = validate_title("Title with\ttab");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Title with\ttab");
    }

    #[test]
    fn test_validate_title_with_delete_character() {
        // DEL character (0x7F)
        let result = validate_title("Title with\x7Fdelete");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("control character"));
    }

    // ========== Description Validation ==========

    #[test]
    fn test_validate_description_with_newline_allowed() {
        // Newlines should be allowed in descriptions
        let result = validate_description("Multi-line\ndescription");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Multi-line\ndescription");
    }

    #[test]
    fn test_validate_description_with_control_character() {
        // Control characters should be rejected
        let result = validate_description("Description with\x00control");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("control character"));
    }

    #[test]
    fn test_validate_description_with_tab_and_newline() {
        // Both tab and newline should be allowed
        let result = validate_description("Line1\n\tIndented line");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "Line1\n\tIndented line");
    }

    #[test]
    fn test_validate_description_empty() {
        // Empty descriptions should be allowed
        let result = validate_description("");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "");
    }

    // ========== Label Validation ==========

    #[test]
    fn test_validate_label_valid() {
        assert!(validate_label("bug").is_ok());
        assert!(validate_label("feature").is_ok());
        assert!(validate_label("high-priority").is_ok());
        assert!(validate_label("needs_review").is_ok());
        assert!(validate_label("v2").is_ok());
        assert!(validate_label("p0").is_ok());
        assert!(validate_label("front-end").is_ok());
        assert!(validate_label("back_end").is_ok());
    }

    #[test]
    fn test_validate_label_empty() {
        let result = validate_label("");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot be empty"));
    }

    #[test]
    fn test_validate_label_whitespace_only() {
        let result = validate_label("   ");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot be empty"));
    }

    #[test]
    fn test_validate_label_trims_whitespace() {
        assert_eq!(validate_label("  bug  ").unwrap(), "bug");
    }

    #[test]
    fn test_validate_label_too_long() {
        let long_label = "a".repeat(51);
        let result = validate_label(&long_label);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("cannot exceed 50"));
    }

    #[test]
    fn test_validate_label_exactly_max_length() {
        let max_label = "a".repeat(50);
        assert!(validate_label(&max_label).is_ok());
        assert_eq!(validate_label(&max_label).unwrap().len(), 50);
    }

    #[test]
    fn test_validate_label_uppercase_rejected() {
        let result = validate_label("Bug");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("lowercase"));
    }

    #[test]
    fn test_validate_label_space_rejected() {
        let result = validate_label("high priority");
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("lowercase letters, numbers, hyphens"));
    }

    #[test]
    fn test_validate_label_special_chars_rejected() {
        assert!(validate_label("bug!").is_err());
        assert!(validate_label("feature@v2").is_err());
        assert!(validate_label("needs.review").is_err());
        assert!(validate_label("test/label").is_err());
    }

    #[test]
    fn test_validate_label_must_start_with_alphanumeric() {
        let result = validate_label("-bug");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must start with"));

        let result = validate_label("_bug");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must start with"));
    }

    #[test]
    fn test_validate_label_must_end_with_alphanumeric() {
        let result = validate_label("bug-");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must end with"));

        let result = validate_label("bug_");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("must end with"));
    }

    #[rstest]
    #[case::two_hyphens("high--priority")]
    #[case::three_hyphens("high---priority")]
    #[case::four_hyphens("high----priority")]
    fn test_validate_label_no_consecutive_hyphens(#[case] input: &str) {
        let result = validate_label(input);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("consecutive hyphens"));
    }

    #[rstest]
    #[case::two_underscores("needs__review")]
    #[case::three_underscores("needs___review")]
    #[case::four_underscores("needs____review")]
    fn test_validate_label_no_consecutive_underscores(#[case] input: &str) {
        let result = validate_label(input);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("consecutive underscores"));
    }

    #[test]
    fn test_validate_label_mixed_separators_allowed() {
        // Mixing hyphens and underscores is allowed
        assert!(validate_label("high-priority_v2").is_ok());
        assert!(validate_label("needs_review-urgent").is_ok());
    }
}