jj-cz 1.1.0

Conventional commits for Jujutsu
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
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct Scope(String);

impl Scope {
    /// Maximum allowed length for a scope
    pub const MAX_LENGTH: usize = 30;

    /// Parse and validate a scope string
    ///
    /// # Validation
    /// - Trims leading/trailing whitespace
    /// - Empty/whitespace-only input returns empty Scope
    /// - Validates character set
    /// - Validates maximum length (30 chars)
    pub fn parse(value: impl Into<String>) -> Result<Self, ScopeError> {
        let value: String = value.into().trim().to_owned();
        if value.is_empty() {
            return Ok(Self::empty());
        }
        if value.chars().count() > Self::MAX_LENGTH {
            return Err(ScopeError::TooLong {
                actual: value.chars().count(),
                max: Self::MAX_LENGTH,
            });
        }
        match lazy_regex::regex_find!(r"[^-a-zA-Z0-9_/]", &value) {
            None => Ok(Self(value)),
            Some(val) => val
                .chars()
                .next()
                .map(ScopeError::InvalidCharacter)
                .map(Err)
                .unwrap_or_else(|| unreachable!("regex match is always non-empty")),
        }
    }

    /// Create an empty scope (convenience constructor)
    pub fn empty() -> Self {
        Self(String::new())
    }

    /// Returns true if the scope is empty
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the inner string slice
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Returns itself as a formatted header segment
    pub fn header_segment(&self) -> String {
        if self.is_empty() {
            "".into()
        } else {
            format!("({self})")
        }
    }

    /// Returns the visible length of the header segment
    pub fn header_segment_len(&self) -> usize {
        if self.is_empty() {
            0
        } else {
            self.0.chars().count() + 2
        }
    }
}

impl std::fmt::Display for Scope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl AsRef<str> for Scope {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Error type for Scope validation failures
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ScopeError {
    #[error("Invalid character '{0}' in scope (allowed: a-z, A-Z, 0-9, -, _, /)")]
    InvalidCharacter(char),

    #[error("Scope too long ({actual} characters, maximum is {max})")]
    TooLong { actual: usize, max: usize },
}

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

    /// Test that valid alphanumeric scope is accepted
    #[test]
    fn valid_alphanumeric_scope_accepted() {
        let result = Scope::parse("cli");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "cli");
    }

    /// Test that valid scope with uppercase letters is accepted
    #[test]
    fn valid_uppercase_scope_accepted() {
        let result = Scope::parse("CLI");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "CLI");
    }

    /// Test that valid scope with mixed case is accepted
    #[test]
    fn valid_mixed_case_scope_accepted() {
        let result = Scope::parse("AuthModule");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "AuthModule");
    }

    /// Test that valid scope with numbers is accepted
    #[test]
    fn valid_scope_with_numbers_accepted() {
        let result = Scope::parse("api2");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "api2");
    }

    /// Test that valid scope with hyphens is accepted
    #[test]
    fn valid_scope_with_hyphens_accepted() {
        let result = Scope::parse("user-auth");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "user-auth");
    }

    /// Test that valid scope with underscores is accepted
    #[test]
    fn valid_scope_with_underscores_accepted() {
        let result = Scope::parse("user_auth");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "user_auth");
    }

    /// Test that valid scope with slashes is accepted (Jira refs)
    #[test]
    fn valid_scope_with_slashes_accepted() {
        let result = Scope::parse("PROJ-123/feature");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "PROJ-123/feature");
    }

    /// Test another Jira-style scope with slashes
    #[test]
    fn valid_jira_style_scope_accepted() {
        let result = Scope::parse("TEAM-456/bugfix");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "TEAM-456/bugfix");
    }

    /// Test scope with all allowed special characters combined
    #[test]
    fn valid_scope_with_all_special_chars() {
        let result = Scope::parse("my-scope_v2/test");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "my-scope_v2/test");
    }

    /// Test that empty string returns valid empty Scope
    #[test]
    fn empty_string_returns_valid_empty_scope() {
        let result = Scope::parse("");
        assert!(result.is_ok());
        let scope = result.unwrap();
        assert!(scope.is_empty());
        assert_eq!(scope.as_str(), "");
    }

    /// Test that whitespace-only input returns valid empty Scope
    #[test]
    fn whitespace_only_returns_valid_empty_scope() {
        let result = Scope::parse("   ");
        assert!(result.is_ok());
        let scope = result.unwrap();
        assert!(scope.is_empty());
        assert_eq!(scope.as_str(), "");
    }

    /// Test that tabs-only input returns valid empty Scope
    #[test]
    fn tabs_only_returns_valid_empty_scope() {
        let result = Scope::parse("\t\t");
        assert!(result.is_ok());
        let scope = result.unwrap();
        assert!(scope.is_empty());
    }

    /// Test that mixed whitespace returns valid empty Scope
    #[test]
    fn mixed_whitespace_returns_valid_empty_scope() {
        let result = Scope::parse("  \t  \n  ");
        assert!(result.is_ok());
        let scope = result.unwrap();
        assert!(scope.is_empty());
    }

    /// Test that leading whitespace is trimmed
    #[test]
    fn leading_whitespace_trimmed() {
        let result = Scope::parse("  cli");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "cli");
    }

    /// Test that trailing whitespace is trimmed
    #[test]
    fn trailing_whitespace_trimmed() {
        let result = Scope::parse("cli  ");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "cli");
    }

    /// Test that both leading and trailing whitespace is trimmed
    #[test]
    fn leading_and_trailing_whitespace_trimmed() {
        let result = Scope::parse("  cli  ");
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str(), "cli");
    }

    /// Test that spaces within scope are rejected
    #[test]
    fn space_in_scope_rejected() {
        let result = Scope::parse("user auth");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter(' '));
    }

    /// Test that dot is rejected
    #[test]
    fn dot_rejected() {
        let result = Scope::parse("user.auth");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter('.'));
    }

    /// Test that colon is rejected
    #[test]
    fn colon_rejected() {
        let result = Scope::parse("user:auth");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter(':'));
    }

    /// Test that parentheses are rejected
    #[test]
    fn parentheses_rejected() {
        let result = Scope::parse("user(auth)");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter('('));
    }

    /// Test that exclamation mark is rejected
    #[test]
    fn exclamation_rejected() {
        let result = Scope::parse("breaking!");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter('!'));
    }

    /// Test that @ symbol is rejected
    #[test]
    fn at_symbol_rejected() {
        let result = Scope::parse("user@domain");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter('@'));
    }

    /// Test that hash is rejected
    #[test]
    fn hash_rejected() {
        let result = Scope::parse("issue#123");
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter('#'));
    }

    /// Test that emoji is rejected
    #[test]
    fn emoji_rejected() {
        let result = Scope::parse("cli🚀");
        assert!(result.is_err());
        // The error should contain the emoji character
        match result.unwrap_err() {
            ScopeError::InvalidCharacter(c) => assert_eq!(c, '🚀'),
            _ => panic!("Expected InvalidCharacter error"),
        }
    }

    /// Test that first invalid character is reported
    #[test]
    fn first_invalid_character_reported() {
        let result = Scope::parse("a.b:c");
        assert!(result.is_err());
        // Should report the first invalid character (dot)
        assert_eq!(result.unwrap_err(), ScopeError::InvalidCharacter('.'));
    }

    /// Test that exactly 30 characters is accepted (boundary)
    #[test]
    fn thirty_characters_accepted() {
        let scope_30 = "a".repeat(30);
        let result = Scope::parse(&scope_30);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str().len(), 30);
    }

    /// Test that 31 characters is rejected
    #[test]
    fn thirty_one_characters_rejected() {
        let scope_31 = "a".repeat(31);
        let result = Scope::parse(&scope_31);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            ScopeError::TooLong {
                actual: 31,
                max: 30
            }
        );
    }

    /// Test that 100 characters is rejected
    #[test]
    fn hundred_characters_rejected() {
        let scope_100 = "a".repeat(100);
        let result = Scope::parse(&scope_100);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            ScopeError::TooLong {
                actual: 100,
                max: 30
            }
        );
    }

    /// Test that length is checked after trimming
    #[test]
    fn length_checked_after_trimming() {
        // 30 chars + leading/trailing spaces = should be valid after trim
        let scope_with_spaces = format!("  {}  ", "a".repeat(30));
        let result = Scope::parse(&scope_with_spaces);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().as_str().len(), 30);
    }

    /// Test MAX_LENGTH constant is 30
    #[test]
    fn max_length_constant_is_30() {
        assert_eq!(Scope::MAX_LENGTH, 30);
    }

    /// Test that empty() creates an empty Scope
    #[test]
    fn empty_constructor_creates_empty_scope() {
        let scope = Scope::empty();
        assert!(scope.is_empty());
        assert_eq!(scope.as_str(), "");
    }

    /// Test is_empty() returns true for empty scope
    #[test]
    fn is_empty_returns_true_for_empty() {
        let scope = Scope::parse("").unwrap();
        assert!(scope.is_empty());
    }

    /// Test is_empty() returns false for non-empty scope
    #[test]
    fn is_empty_returns_false_for_non_empty() {
        let scope = Scope::parse("cli").unwrap();
        assert!(!scope.is_empty());
    }

    /// Test as_str() returns inner string
    #[test]
    fn as_str_returns_inner_string() {
        let scope = Scope::parse("my-scope").unwrap();
        assert_eq!(scope.as_str(), "my-scope");
    }

    /// Test Display trait implementation
    #[test]
    fn display_outputs_inner_string() {
        let scope = Scope::parse("cli").unwrap();
        assert_eq!(format!("{}", scope), "cli");
    }

    /// Test Display for empty scope
    #[test]
    fn display_empty_scope() {
        let scope = Scope::empty();
        assert_eq!(format!("{}", scope), "");
    }

    /// Test Clone trait
    #[test]
    fn scope_is_cloneable() {
        let original = Scope::parse("cli").unwrap();
        let cloned = original.clone();
        assert_eq!(original, cloned);
    }

    /// Test PartialEq trait
    #[test]
    fn scope_equality() {
        let scope1 = Scope::parse("cli").unwrap();
        let scope2 = Scope::parse("cli").unwrap();
        let scope3 = Scope::parse("api").unwrap();
        assert_eq!(scope1, scope2);
        assert_ne!(scope1, scope3);
    }

    /// Test Debug trait
    #[test]
    fn scope_has_debug() {
        let scope = Scope::parse("cli").unwrap();
        let debug_output = format!("{:?}", scope);
        assert!(debug_output.contains("Scope"));
        assert!(debug_output.contains("cli"));
    }

    /// Test AsRef<str> trait
    #[test]
    fn scope_as_ref_str() {
        let scope = Scope::parse("cli").unwrap();
        let s: &str = scope.as_ref();
        assert_eq!(s, "cli");
    }

    /// Test ScopeError::InvalidCharacter displays correctly
    #[test]
    fn invalid_character_error_display() {
        let err = ScopeError::InvalidCharacter('.');
        let msg = format!("{}", err);
        assert!(msg.contains("Invalid character"));
        assert!(msg.contains("'.'"));
        assert!(msg.contains("allowed: a-z, A-Z, 0-9, -, _, /"));
    }

    /// Test ScopeError::TooLong displays correctly
    #[test]
    fn too_long_error_display() {
        let err = ScopeError::TooLong {
            actual: 31,
            max: 30,
        };
        let msg = format!("{}", err);
        assert!(msg.contains("too long"));
        assert!(msg.contains("31"));
        assert!(msg.contains("30"));
    }

    /// Test header_segment() returns empty string for empty scope
    #[test]
    fn header_segment_empty_scope_returns_empty_string() {
        assert_eq!(Scope::empty().header_segment(), "");
    }

    /// Test header_segment() wraps a non-empty scope in parentheses
    #[test]
    fn header_segment_wraps_scope_in_parentheses() {
        let scope = Scope::parse("auth").unwrap();
        assert_eq!(scope.header_segment(), "(auth)");
    }

    /// Test header_segment() for a variety of valid scopes
    #[test]
    fn header_segment_various_scopes() {
        assert_eq!(Scope::parse("cli").unwrap().header_segment(), "(cli)");
        assert_eq!(
            Scope::parse("user-auth").unwrap().header_segment(),
            "(user-auth)"
        );
        assert_eq!(
            Scope::parse("PROJ-123/feature").unwrap().header_segment(),
            "(PROJ-123/feature)"
        );
    }

    /// Test header_segment_len() is 0 for an empty scope
    #[test]
    fn header_segment_len_empty_scope_is_zero() {
        assert_eq!(Scope::empty().header_segment_len(), 0);
    }

    /// Test header_segment_len() includes the two parentheses characters
    #[test]
    fn header_segment_len_includes_parentheses() {
        // "(auth)" = 6 chars
        let scope = Scope::parse("auth").unwrap();
        assert_eq!(scope.header_segment_len(), 6);
    }

    /// Test header_segment_len() agrees with header_segment().chars().count()
    #[test]
    fn header_segment_len_equals_segment_chars_count() {
        let values = ["cli", "user-auth", "PROJ-123/feature"];
        for s in values {
            let scope = Scope::parse(s).unwrap();
            assert_eq!(
                scope.header_segment_len(),
                scope.header_segment().chars().count(),
                "header_segment_len() should equal chars().count() for scope {:?}",
                s
            );
        }
    }

    /// A scope whose byte count exceeds MAX_LENGTH but whose char
    /// count does not must be rejected with InvalidCharacter, not
    /// TooLong.
    ///
    /// Before the fix the byte-based `.len()` check fired first,
    /// producing a misleading "too long" error for a string that is
    /// actually within the limit.
    #[test]
    fn length_limit_uses_char_count_not_byte_count() {
        // "ñ" is 2 bytes in UTF-8; 16 × "ñ" = 16 chars, 32 bytes.
        // char count 16 ≤ 30  →  length check passes
        // regex rejects "ñ"   →  should return InvalidCharacter, not TooLong
        let input = "ñ".repeat(16);
        assert_eq!(input.chars().count(), 16, "sanity: 16 chars");
        assert_eq!(input.len(), 32, "sanity: 32 bytes");

        let result = Scope::parse(&input);
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            ScopeError::InvalidCharacter('ñ'),
            "expected InvalidCharacter('ñ') for a 16-char / 32-byte input, not TooLong",
        );
    }

    /// The actual length reported in TooLong must be the char count,
    /// not the byte count.
    ///
    /// "a".repeat(30) + "é" is 31 chars and 32 bytes. The length
    /// check should fire on char count (31 > 30) and report actual =
    /// 31.
    #[test]
    fn too_long_error_actual_reports_char_count_not_byte_count() {
        // 30 ASCII 'a' + 1 two-byte 'é' = 31 chars, 32 bytes
        let input = "a".repeat(30) + "é";
        assert_eq!(input.chars().count(), 31, "sanity: 31 chars");
        assert_eq!(input.len(), 32, "sanity: 32 bytes");

        let result = Scope::parse(&input);
        assert_eq!(
            result.unwrap_err(),
            ScopeError::TooLong {
                actual: 31,
                max: 30
            },
            "actual should be the char count (31), not the byte count (32)",
        );
    }
}