requirements-manager 0.1.1

Plain-text requirements management tool
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
598
599
600
601
602
603
604
605
606
607
608
use std::{fmt, num::NonZeroUsize, ops::Deref, str::FromStr};

use non_empty_string::NonEmptyString;

/// A validated string containing only uppercase alphabetic characters ([A-Z]+).
///
/// Used for HRID kind and namespace segments to ensure they conform to the
/// required format.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct KindString(NonEmptyString);

impl KindString {
    /// Creates a new `KindString` from a string.
    ///
    /// # Errors
    ///
    /// Returns `InvalidKindError` if the string is empty or contains
    /// characters other than uppercase letters (A-Z).
    pub fn new(s: String) -> Result<Self, InvalidKindError> {
        // Check non-empty
        let non_empty = NonEmptyString::new(s.clone()).map_err(|_| InvalidKindError(s.clone()))?;

        // Check all characters are uppercase ASCII letters
        if !s.chars().all(|c| c.is_ascii_uppercase()) {
            return Err(InvalidKindError(s));
        }

        Ok(Self(non_empty))
    }

    /// Returns the string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl TryFrom<String> for KindString {
    type Error = InvalidKindError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<&str> for KindString {
    type Error = InvalidKindError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value.to_string())
    }
}

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

impl Deref for KindString {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.0.as_str()
    }
}

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

impl FromStr for KindString {
    type Err = InvalidKindError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

/// Error returned when a string doesn't match the required pattern [A-Z]+.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("Invalid kind string '{0}': must be non-empty and contain only uppercase letters (A-Z)")]
pub struct InvalidKindError(String);

/// A human-readable identifier (HRID) for a requirement.
///
/// Format:
/// `{NAMESPACE*}-{KIND}-{ID}`, where:
/// - `NAMESPACE` is an optional sequence of uppercase alphabetic segments (e.g.
///   `COMPONENT-SUBCOMPONENT`)
/// - `KIND` is an uppercase alphabetic category string (e.g. `URS`, `SYS`)
/// - `ID` is a positive non-zero integer (e.g. `001`, `123`)
///
/// Examples: `URS-001`, `SYS-099`, `COMPONENT-SUBCOMPONENT-SYS-005`
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Hrid {
    namespace: Vec<KindString>,
    kind: KindString,
    id: NonZeroUsize,
}

impl Hrid {
    /// Create an HRID with no namespace.
    ///
    /// This is an infallible constructor that takes pre-validated types.
    #[must_use]
    pub const fn new(kind: KindString, id: NonZeroUsize) -> Self {
        Self::new_with_namespace(Vec::new(), kind, id)
    }

    /// Create an HRID with the given namespace.
    ///
    /// This is an infallible constructor that takes pre-validated types.
    #[must_use]
    pub const fn new_with_namespace(
        namespace: Vec<KindString>,
        kind: KindString,
        id: NonZeroUsize,
    ) -> Self {
        Self {
            namespace,
            kind,
            id,
        }
    }

    /// Returns the namespace segments as strings.
    pub fn namespace(&self) -> Vec<&str> {
        self.namespace.iter().map(KindString::as_str).collect()
    }

    /// Returns the kind component as a string.
    #[must_use]
    pub fn kind(&self) -> &str {
        self.kind.as_str()
    }

    /// Returns the numeric ID component.
    #[must_use]
    pub const fn id(&self) -> NonZeroUsize {
        self.id
    }

    /// Returns the prefix (namespace + kind) without the numeric ID.
    ///
    /// For example:
    /// - "USR" for a requirement with no namespace and kind "USR"
    /// - "AUTH-USR" for a requirement with namespace `["AUTH"]` and kind "USR"
    #[must_use]
    pub fn prefix(&self) -> String {
        if self.namespace.is_empty() {
            self.kind.to_string()
        } else {
            let namespace_str = self
                .namespace
                .iter()
                .map(KindString::as_str)
                .collect::<Vec<_>>()
                .join("-");
            format!("{}-{}", namespace_str, self.kind)
        }
    }
}

impl fmt::Display for Hrid {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let id_str = format!("{:03}", self.id);
        if self.namespace.is_empty() {
            write!(f, "{}-{}", self.kind, id_str)
        } else {
            let namespace_str = self
                .namespace
                .iter()
                .map(KindString::as_str)
                .collect::<Vec<_>>()
                .join("-");
            write!(f, "{}-{}-{}", namespace_str, self.kind, id_str)
        }
    }
}

/// Errors that can occur during HRID parsing or construction.
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum Error {
    /// Invalid HRID format (malformed structure).
    #[error("Invalid HRID format: {0}")]
    Syntax(String),

    /// Invalid ID value in HRID (non-numeric or zero).
    #[error("Invalid ID in HRID '{0}': expected a non-zero integer, got {1}")]
    Id(String, String),

    /// ID cannot be zero.
    #[error("Invalid ID: cannot be zero")]
    ZeroId,

    /// Invalid kind string (not uppercase alphabetic).
    #[error(transparent)]
    Kind(InvalidKindError),
}

impl From<InvalidKindError> for Error {
    fn from(err: InvalidKindError) -> Self {
        Self::Kind(err)
    }
}

impl FromStr for Hrid {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Early validation: check for empty string or malformed structure
        if s.is_empty()
            || s.starts_with('-')
            || s.ends_with('-')
            || s.contains("--")
            || !s.contains('-')
        {
            return Err(Error::Syntax(s.to_string()));
        }

        let parts: Vec<&str> = s.split('-').collect();

        // Must have at least KIND-ID (2 parts)
        if parts.len() < 2 {
            return Err(Error::Syntax(s.to_string()));
        }

        // Parse ID from the last part
        let id_str = parts[parts.len() - 1];
        let id_usize = id_str
            .parse::<usize>()
            .map_err(|_| Error::Id(s.to_string(), id_str.to_string()))?;
        let id = NonZeroUsize::new(id_usize)
            .ok_or_else(|| Error::Id(s.to_string(), id_str.to_string()))?;

        // Parse KIND from the second-to-last part
        let kind_str = parts[parts.len() - 2];
        let kind = KindString::new(kind_str.to_string())?;

        // Parse namespace from all remaining parts
        let namespace = if parts.len() > 2 {
            parts[..parts.len() - 2]
                .iter()
                .map(|&segment| KindString::new(segment.to_string()))
                .collect::<Result<Vec<_>, _>>()?
        } else {
            Vec::new()
        };

        Ok(Self::new_with_namespace(namespace, kind, id))
    }
}

impl TryFrom<&str> for Hrid {
    type Error = Error;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::from_str(value)
    }
}

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

    #[test]
    fn hrid_creation_no_namespace() {
        let kind = KindString::new("URS".to_string()).unwrap();
        let id = NonZeroUsize::new(42).unwrap();
        let hrid = Hrid::new(kind, id);
        assert!(hrid.namespace().is_empty());
        assert_eq!(hrid.kind(), "URS");
        assert_eq!(hrid.id().get(), 42);
    }

    #[test]
    fn hrid_creation_with_namespace() {
        let namespace = vec![
            KindString::new("COMPONENT".to_string()).unwrap(),
            KindString::new("SUBCOMPONENT".to_string()).unwrap(),
        ];
        let kind = KindString::new("SYS".to_string()).unwrap();
        let id = NonZeroUsize::new(5).unwrap();
        let hrid = Hrid::new_with_namespace(namespace, kind, id);

        assert_eq!(hrid.namespace(), vec!["COMPONENT", "SUBCOMPONENT"]);
        assert_eq!(hrid.kind(), "SYS");
        assert_eq!(hrid.id().get(), 5);
    }

    #[test]
    fn hrid_creation_empty_kind_fails() {
        assert!(KindString::new(String::new()).is_err());
    }

    #[test]
    fn hrid_creation_lowercase_kind_fails() {
        assert!(KindString::new("sys".to_string()).is_err());
    }

    #[test]
    fn hrid_creation_zero_id_fails() {
        assert!(NonZeroUsize::new(0).is_none());
    }

    #[test]
    fn hrid_display_no_namespace() {
        let hrid = Hrid::new(
            KindString::new("SYS".to_string()).unwrap(),
            NonZeroUsize::new(1).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "SYS-001");

        let hrid = Hrid::new(
            KindString::new("URS".to_string()).unwrap(),
            NonZeroUsize::new(42).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "URS-042");

        let hrid = Hrid::new(
            KindString::new("TEST".to_string()).unwrap(),
            NonZeroUsize::new(999).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "TEST-999");
    }

    #[test]
    fn hrid_display_with_namespace() {
        let hrid = Hrid::new_with_namespace(
            vec![KindString::new("COMPONENT".to_string()).unwrap()],
            KindString::new("SYS".to_string()).unwrap(),
            NonZeroUsize::new(5).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "COMPONENT-SYS-005");

        let hrid = Hrid::new_with_namespace(
            vec![
                KindString::new("COMPONENT".to_string()).unwrap(),
                KindString::new("SUBCOMPONENT".to_string()).unwrap(),
            ],
            KindString::new("SYS".to_string()).unwrap(),
            NonZeroUsize::new(5).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "COMPONENT-SUBCOMPONENT-SYS-005");

        let hrid = Hrid::new_with_namespace(
            vec![
                KindString::new("A".to_string()).unwrap(),
                KindString::new("B".to_string()).unwrap(),
                KindString::new("C".to_string()).unwrap(),
            ],
            KindString::new("REQ".to_string()).unwrap(),
            NonZeroUsize::new(123).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "A-B-C-REQ-123");
    }

    #[test]
    fn hrid_display_large_numbers() {
        let hrid = Hrid::new(
            KindString::new("BIG".to_string()).unwrap(),
            NonZeroUsize::new(1000).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "BIG-1000");

        let hrid = Hrid::new_with_namespace(
            vec![KindString::new("NS".to_string()).unwrap()],
            KindString::new("HUGE".to_string()).unwrap(),
            NonZeroUsize::new(12345).unwrap(),
        );
        assert_eq!(format!("{hrid}"), "NS-HUGE-12345");
    }

    #[test]
    fn try_from_valid_no_namespace() {
        let hrid = Hrid::try_from("URS-001").unwrap();
        assert!(hrid.namespace().is_empty());
        assert_eq!(hrid.kind(), "URS");
        assert_eq!(hrid.id().get(), 1);

        let hrid = Hrid::try_from("SYS-042").unwrap();
        assert!(hrid.namespace().is_empty());
        assert_eq!(hrid.kind(), "SYS");
        assert_eq!(hrid.id().get(), 42);

        let hrid = Hrid::try_from("TEST-999").unwrap();
        assert!(hrid.namespace().is_empty());
        assert_eq!(hrid.kind(), "TEST");
        assert_eq!(hrid.id().get(), 999);
    }

    #[test]
    fn try_from_valid_with_namespace() {
        let hrid = Hrid::try_from("COMPONENT-SYS-005").unwrap();
        assert_eq!(hrid.namespace(), vec!["COMPONENT"]);
        assert_eq!(hrid.kind(), "SYS");
        assert_eq!(hrid.id().get(), 5);

        let hrid = Hrid::try_from("COMPONENT-SUBCOMPONENT-SYS-005").unwrap();
        assert_eq!(hrid.namespace(), vec!["COMPONENT", "SUBCOMPONENT"]);
        assert_eq!(hrid.kind(), "SYS");
        assert_eq!(hrid.id().get(), 5);

        let hrid = Hrid::try_from("A-B-C-REQ-123").unwrap();
        assert_eq!(hrid.namespace(), vec!["A", "B", "C"]);
        assert_eq!(hrid.kind(), "REQ");
        assert_eq!(hrid.id().get(), 123);
    }

    #[test]
    fn try_from_valid_no_leading_zeros() {
        let hrid = Hrid::try_from("URS-1").unwrap();
        assert!(hrid.namespace().is_empty());
        assert_eq!(hrid.kind(), "URS");
        assert_eq!(hrid.id().get(), 1);

        let hrid = Hrid::try_from("NS-SYS-42").unwrap();
        assert_eq!(hrid.namespace(), vec!["NS"]);
        assert_eq!(hrid.kind(), "SYS");
        assert_eq!(hrid.id().get(), 42);
    }

    #[test]
    fn try_from_valid_large_numbers() {
        let hrid = Hrid::try_from("BIG-1000").unwrap();
        assert!(hrid.namespace().is_empty());
        assert_eq!(hrid.kind(), "BIG");
        assert_eq!(hrid.id().get(), 1000);

        let hrid = Hrid::try_from("NS-HUGE-12345").unwrap();
        assert_eq!(hrid.namespace(), vec!["NS"]);
        assert_eq!(hrid.kind(), "HUGE");
        assert_eq!(hrid.id().get(), 12345);
    }

    #[test]
    fn try_from_invalid_no_dash() {
        let result = Hrid::try_from("URS001");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn try_from_invalid_empty_string() {
        let result = Hrid::try_from("");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn try_from_invalid_only_dash() {
        let result = Hrid::try_from("-");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn try_from_invalid_single_part() {
        let result = Hrid::try_from("JUSTONEWORD");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn try_from_invalid_non_numeric_id() {
        let result = Hrid::try_from("URS-abc");
        assert!(matches!(result, Err(Error::Id(_, _))));

        let result = Hrid::try_from("NS-URS-abc");
        assert!(matches!(result, Err(Error::Id(_, _))));
    }

    #[test]
    fn try_from_invalid_mixed_id() {
        let result = Hrid::try_from("SYS-12abc");
        assert!(matches!(result, Err(Error::Id(_, _))));
    }

    #[test]
    fn try_from_invalid_negative_id() {
        let result = Hrid::try_from("URS--1");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn try_from_invalid_zero_id() {
        let result = Hrid::try_from("URS-0");
        assert!(matches!(result, Err(Error::Id(_, _))));
    }

    #[test]
    fn try_from_invalid_lowercase_kind() {
        let result = Hrid::try_from("urs-001");
        assert!(matches!(result, Err(Error::Kind(_))));
    }

    #[test]
    fn try_from_invalid_lowercase_namespace() {
        let result = Hrid::try_from("ns-URS-001");
        assert!(matches!(result, Err(Error::Kind(_))));
    }

    #[test]
    fn try_from_empty_namespace_segment_fails() {
        let result = Hrid::try_from("-NS-SYS-001");
        assert!(matches!(result, Err(Error::Syntax(_))));

        let result = Hrid::try_from("NS--SYS-001");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn try_from_empty_kind_fails() {
        let result = Hrid::try_from("-001");
        assert!(matches!(result, Err(Error::Syntax(_))));
    }

    #[test]
    fn hrid_clone_and_eq() {
        let hrid1 = Hrid::new_with_namespace(
            vec![KindString::new("NS".to_string()).unwrap()],
            KindString::new("URS".to_string()).unwrap(),
            NonZeroUsize::new(42).unwrap(),
        );
        let hrid2 = hrid1.clone();

        assert_eq!(hrid1, hrid2);
        assert_eq!(hrid1.namespace(), hrid2.namespace());
        assert_eq!(hrid1.kind(), hrid2.kind());
        assert_eq!(hrid1.id(), hrid2.id());
    }

    #[test]
    fn hrid_not_eq() {
        let hrid1 = Hrid::new(
            KindString::new("URS".to_string()).unwrap(),
            NonZeroUsize::new(42).unwrap(),
        );
        let hrid2 = Hrid::new(
            KindString::new("SYS".to_string()).unwrap(),
            NonZeroUsize::new(42).unwrap(),
        );
        let hrid3 = Hrid::new(
            KindString::new("URS".to_string()).unwrap(),
            NonZeroUsize::new(43).unwrap(),
        );
        let hrid4 = Hrid::new_with_namespace(
            vec![KindString::new("NS".to_string()).unwrap()],
            KindString::new("URS".to_string()).unwrap(),
            NonZeroUsize::new(42).unwrap(),
        );

        assert_ne!(hrid1, hrid2);
        assert_ne!(hrid1, hrid3);
        assert_ne!(hrid1, hrid4);
    }

    #[test]
    fn roundtrip_conversion_no_namespace() {
        let original = Hrid::new(
            KindString::new("TEST".to_string()).unwrap(),
            NonZeroUsize::new(123).unwrap(),
        );

        let as_string = format!("{original}");
        let parsed = Hrid::try_from(as_string.as_str()).unwrap();

        assert_eq!(original, parsed);
    }

    #[test]
    fn roundtrip_conversion_with_namespace() {
        let original = Hrid::new_with_namespace(
            vec![
                KindString::new("COMPONENT".to_string()).unwrap(),
                KindString::new("SUBCOMPONENT".to_string()).unwrap(),
            ],
            KindString::new("SYS".to_string()).unwrap(),
            NonZeroUsize::new(5).unwrap(),
        );

        let as_string = format!("{original}");
        let parsed = Hrid::try_from(as_string.as_str()).unwrap();

        assert_eq!(original, parsed);
    }

    #[test]
    fn strict_uppercase_validation() {
        // Domain layer is strict - lowercase should fail
        assert!(KindString::new("sys".to_string()).is_err());

        // FromStr is also strict
        let result = Hrid::from_str("component-sys-001");
        assert!(matches!(result, Err(Error::Kind(_))));
    }

    #[test]
    fn error_display() {
        let syntax_error = Error::Syntax("bad-format".to_string());
        assert_eq!(format!("{syntax_error}"), "Invalid HRID format: bad-format");

        let id_error = Error::Id("URS-bad".to_string(), "bad".to_string());
        assert_eq!(
            format!("{id_error}"),
            "Invalid ID in HRID 'URS-bad': expected a non-zero integer, got bad"
        );
    }
}