sr-core 6.0.1

Pure domain logic for sr
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
use regex::Regex;
use serde::{Deserialize, Serialize};

use crate::error::ReleaseError;
use crate::version::BumpLevel;

/// A raw commit as read from git history.
#[derive(Debug, Clone)]
pub struct Commit {
    pub sha: String,
    pub message: String,
}

/// A commit parsed according to the Conventional Commits specification.
#[derive(Debug, Clone, Serialize)]
pub struct ConventionalCommit {
    pub sha: String,
    pub r#type: String,
    pub scope: Option<String>,
    pub description: String,
    pub body: Option<String>,
    pub breaking: bool,
}

/// Describes a recognised commit type.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CommitType {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bump: Option<BumpLevel>,
    /// Changelog section heading (e.g. "Features"). None = exclude from changelog.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub section: Option<String>,
    /// Optional regex matched against the full raw commit message as a fallback
    /// when the standard type-prefix pattern doesn't match. Useful for
    /// non-conventional commit formats (e.g. Dependabot, automated tooling).
    /// Named groups `type`, `scope`, `breaking`, `description` are used if present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,
}

/// Single source of truth for commit type classification.
pub trait CommitClassifier: Send + Sync {
    fn types(&self) -> &[CommitType];

    /// Commit message regex with named groups: type, scope, breaking, description.
    fn pattern(&self) -> &str;

    fn bump_level(&self, type_name: &str, breaking: bool) -> Option<BumpLevel> {
        if breaking {
            return Some(BumpLevel::Major);
        }
        self.types().iter().find(|t| t.name == type_name)?.bump
    }

    fn changelog_section(&self, type_name: &str) -> Option<&str> {
        self.types()
            .iter()
            .find(|t| t.name == type_name)?
            .section
            .as_deref()
    }

    fn is_allowed(&self, type_name: &str) -> bool {
        self.types().iter().any(|t| t.name == type_name)
    }
}

/// Default conventional commits pattern.
/// Named groups: type, scope (optional), breaking (optional `!`), description.
pub const DEFAULT_COMMIT_PATTERN: &str =
    r"^(?P<type>\w+)(?:\((?P<scope>[^)]+)\))?(?P<breaking>!)?:\s+(?P<description>.+)";

pub struct DefaultCommitClassifier {
    types: Vec<CommitType>,
    pattern: String,
}

impl DefaultCommitClassifier {
    pub fn new(types: Vec<CommitType>, pattern: String) -> Self {
        Self { types, pattern }
    }
}

impl Default for DefaultCommitClassifier {
    fn default() -> Self {
        Self::new(default_commit_types(), DEFAULT_COMMIT_PATTERN.into())
    }
}

impl CommitClassifier for DefaultCommitClassifier {
    fn types(&self) -> &[CommitType] {
        &self.types
    }
    fn pattern(&self) -> &str {
        &self.pattern
    }
}

pub fn default_commit_types() -> Vec<CommitType> {
    vec![
        CommitType {
            name: "feat".into(),
            bump: Some(BumpLevel::Minor),
            section: Some("Features".into()),
            pattern: None,
        },
        CommitType {
            name: "fix".into(),
            bump: Some(BumpLevel::Patch),
            section: Some("Bug Fixes".into()),
            pattern: None,
        },
        CommitType {
            name: "perf".into(),
            bump: Some(BumpLevel::Patch),
            section: Some("Performance".into()),
            pattern: None,
        },
        CommitType {
            name: "docs".into(),
            bump: None,
            section: Some("Documentation".into()),
            pattern: None,
        },
        CommitType {
            name: "refactor".into(),
            bump: Some(BumpLevel::Patch),
            section: Some("Refactoring".into()),
            pattern: None,
        },
        CommitType {
            name: "revert".into(),
            bump: None,
            section: Some("Reverts".into()),
            pattern: None,
        },
        CommitType {
            name: "chore".into(),
            bump: None,
            section: None,
            pattern: None,
        },
        CommitType {
            name: "ci".into(),
            bump: None,
            section: None,
            pattern: None,
        },
        CommitType {
            name: "test".into(),
            bump: None,
            section: None,
            pattern: None,
        },
        CommitType {
            name: "build".into(),
            bump: None,
            section: None,
            pattern: None,
        },
        CommitType {
            name: "style".into(),
            bump: None,
            section: None,
            pattern: None,
        },
    ]
}

/// Parses raw commits into conventional commits.
pub trait CommitParser: Send + Sync {
    fn parse(&self, commit: &Commit) -> Result<ConventionalCommit, ReleaseError>;
}

/// Default parser using the built-in `DEFAULT_COMMIT_PATTERN` regex.
pub struct DefaultCommitParser;

impl CommitParser for DefaultCommitParser {
    fn parse(&self, commit: &Commit) -> Result<ConventionalCommit, ReleaseError> {
        let re =
            Regex::new(DEFAULT_COMMIT_PATTERN).map_err(|e| ReleaseError::Config(e.to_string()))?;

        let caps = re.captures(&commit.message).ok_or_else(|| {
            ReleaseError::Config(format!("not a conventional commit: {}", commit.message))
        })?;

        let r#type = caps.name("type").unwrap().as_str().to_string();
        let scope = caps.name("scope").map(|m| m.as_str().to_string());
        let breaking = caps.name("breaking").is_some();
        let description = caps.name("description").unwrap().as_str().to_string();

        let body = commit
            .message
            .split_once("\n\n")
            .map(|x| x.1)
            .map(|b| b.to_string());

        // Detect BREAKING CHANGE: / BREAKING-CHANGE: footers in the body.
        // Per the Conventional Commits spec, footers must start at column 0
        // (no leading whitespace) and use a colon separator.
        let breaking = breaking
            || body.as_deref().is_some_and(|b| {
                b.lines().any(|line| {
                    line.starts_with("BREAKING CHANGE:") || line.starts_with("BREAKING-CHANGE:")
                })
            });

        Ok(ConventionalCommit {
            sha: commit.sha.clone(),
            r#type,
            scope,
            description,
            body,
            breaking,
        })
    }
}

/// Parser that tries the standard commit pattern first, then falls back to
/// per-type `pattern` regexes for non-conventional commit formats.
pub struct ConfiguredCommitParser {
    types: Vec<CommitType>,
    commit_pattern: String,
}

impl ConfiguredCommitParser {
    pub fn new(types: Vec<CommitType>, commit_pattern: String) -> Self {
        Self {
            types,
            commit_pattern,
        }
    }
}

impl CommitParser for ConfiguredCommitParser {
    fn parse(&self, commit: &Commit) -> Result<ConventionalCommit, ReleaseError> {
        let re =
            Regex::new(&self.commit_pattern).map_err(|e| ReleaseError::Config(e.to_string()))?;

        let first_line = commit.message.lines().next().unwrap_or("");

        // Try the standard type-prefix pattern first.
        if let Some(caps) = re.captures(first_line) {
            let r#type = caps.name("type").unwrap().as_str().to_string();
            let scope = caps.name("scope").map(|m| m.as_str().to_string());
            let breaking = caps.name("breaking").is_some();
            let description = caps.name("description").unwrap().as_str().to_string();

            let body = commit
                .message
                .split_once("\n\n")
                .map(|x| x.1)
                .map(|b| b.to_string());

            let breaking = breaking
                || body.as_deref().is_some_and(|b| {
                    b.lines().any(|line| {
                        let trimmed = line.trim();
                        trimmed.starts_with("BREAKING CHANGE:")
                            || trimmed.starts_with("BREAKING CHANGE ")
                            || trimmed.starts_with("BREAKING-CHANGE:")
                            || trimmed.starts_with("BREAKING-CHANGE ")
                    })
                });

            return Ok(ConventionalCommit {
                sha: commit.sha.clone(),
                r#type,
                scope,
                description,
                body,
                breaking,
            });
        }

        // Fallback: try per-type pattern regexes.
        for ct in &self.types {
            let Some(ref pat) = ct.pattern else {
                continue;
            };
            let Ok(type_re) = Regex::new(pat) else {
                continue;
            };
            if let Some(caps) = type_re.captures(first_line) {
                let scope = caps.name("scope").map(|m| m.as_str().to_string());
                let breaking = caps.name("breaking").is_some();
                let description = caps
                    .name("description")
                    .map(|m| m.as_str().to_string())
                    .unwrap_or_else(|| first_line.to_string());

                let body = commit
                    .message
                    .split_once("\n\n")
                    .map(|x| x.1)
                    .map(|b| b.to_string());

                return Ok(ConventionalCommit {
                    sha: commit.sha.clone(),
                    r#type: ct.name.clone(),
                    scope,
                    description,
                    body,
                    breaking,
                });
            }
        }

        Err(ReleaseError::Config(format!(
            "not a conventional commit: {}",
            commit.message
        )))
    }
}

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

    fn raw(message: &str) -> Commit {
        Commit {
            sha: "abc1234".into(),
            message: message.into(),
        }
    }

    #[test]
    fn parse_simple_feat() {
        let result = DefaultCommitParser.parse(&raw("feat: add button")).unwrap();
        assert_eq!(result.r#type, "feat");
        assert_eq!(result.description, "add button");
        assert_eq!(result.scope, None);
        assert!(!result.breaking);
    }

    #[test]
    fn parse_scoped_fix() {
        let result = DefaultCommitParser
            .parse(&raw("fix(core): null check"))
            .unwrap();
        assert_eq!(result.r#type, "fix");
        assert_eq!(result.scope.as_deref(), Some("core"));
    }

    #[test]
    fn parse_breaking_bang() {
        let result = DefaultCommitParser.parse(&raw("feat!: new API")).unwrap();
        assert!(result.breaking);
    }

    #[test]
    fn parse_with_body() {
        let result = DefaultCommitParser
            .parse(&raw("fix: x\n\ndetails"))
            .unwrap();
        assert_eq!(result.body.as_deref(), Some("details"));
    }

    #[test]
    fn parse_breaking_change_footer() {
        let result = DefaultCommitParser
            .parse(&raw(
                "feat: new API\n\nBREAKING CHANGE: removed old endpoint",
            ))
            .unwrap();
        assert!(result.breaking);
        assert_eq!(result.r#type, "feat");
    }

    #[test]
    fn parse_breaking_change_hyphenated_footer() {
        let result = DefaultCommitParser
            .parse(&raw("fix: update schema\n\nBREAKING-CHANGE: field renamed"))
            .unwrap();
        assert!(result.breaking);
    }

    #[test]
    fn parse_breaking_change_footer_with_bang() {
        // Both bang and footer — should still be breaking
        let result = DefaultCommitParser
            .parse(&raw(
                "feat!: overhaul\n\nBREAKING CHANGE: everything changed",
            ))
            .unwrap();
        assert!(result.breaking);
    }

    #[test]
    fn parse_no_breaking_change_in_body() {
        // Body text that mentions "BREAKING CHANGE" but not as a footer line
        let result = DefaultCommitParser
            .parse(&raw("fix: tweak\n\nThis is not a BREAKING CHANGE footer"))
            .unwrap();
        assert!(!result.breaking);
    }

    #[test]
    fn parse_no_breaking_change_indented_bullet() {
        // Indented bullet mentioning BREAKING CHANGE should not trigger a major bump
        let result = DefaultCommitParser
            .parse(&raw(
                "feat(mcp): add breaking flag\n\n- add `breaking` field — sets \"!\" and adds\n  BREAKING CHANGE footer automatically",
            ))
            .unwrap();
        assert!(!result.breaking);
    }

    #[test]
    fn parse_no_breaking_change_space_separator() {
        // "BREAKING CHANGE " (space, no colon) is not a valid footer per spec
        let result = DefaultCommitParser
            .parse(&raw("feat: something\n\nBREAKING CHANGE without colon"))
            .unwrap();
        assert!(!result.breaking);
    }

    #[test]
    fn parse_invalid_message() {
        let result = DefaultCommitParser.parse(&raw("not conventional"));
        assert!(result.is_err());
    }

    // --- CommitClassifier tests ---

    #[test]
    fn classifier_bump_level_feat() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.bump_level("feat", false), Some(BumpLevel::Minor));
    }

    #[test]
    fn classifier_bump_level_fix() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.bump_level("fix", false), Some(BumpLevel::Patch));
    }

    #[test]
    fn classifier_bump_level_breaking_overrides() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.bump_level("fix", true), Some(BumpLevel::Major));
        assert_eq!(c.bump_level("chore", true), Some(BumpLevel::Major));
    }

    #[test]
    fn classifier_bump_level_no_bump_type() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.bump_level("chore", false), None);
        assert_eq!(c.bump_level("docs", false), None);
    }

    #[test]
    fn classifier_bump_level_unknown_type() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.bump_level("unknown", false), None);
    }

    #[test]
    fn classifier_changelog_section() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.changelog_section("feat"), Some("Features"));
        assert_eq!(c.changelog_section("fix"), Some("Bug Fixes"));
        assert_eq!(c.changelog_section("perf"), Some("Performance"));
        assert_eq!(c.changelog_section("docs"), Some("Documentation"));
        assert_eq!(c.changelog_section("refactor"), Some("Refactoring"));
        assert_eq!(c.changelog_section("revert"), Some("Reverts"));
        assert_eq!(c.changelog_section("chore"), None);
        assert_eq!(c.changelog_section("unknown"), None);
    }

    #[test]
    fn classifier_is_allowed() {
        let c = DefaultCommitClassifier::default();
        assert!(c.is_allowed("feat"));
        assert!(c.is_allowed("chore"));
        assert!(!c.is_allowed("unknown"));
    }

    #[test]
    fn classifier_pattern() {
        let c = DefaultCommitClassifier::default();
        assert_eq!(c.pattern(), DEFAULT_COMMIT_PATTERN);
    }

    #[test]
    fn default_commit_types_count() {
        let types = default_commit_types();
        assert_eq!(types.len(), 11);
    }

    #[test]
    fn commit_type_serialization_roundtrip() {
        let ct = CommitType {
            name: "feat".into(),
            bump: Some(BumpLevel::Minor),
            section: Some("Features".into()),
            pattern: None,
        };
        let yaml = serde_yaml_ng::to_string(&ct).unwrap();
        let parsed: CommitType = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(parsed, ct);
    }

    #[test]
    fn commit_type_no_bump_no_section_roundtrip() {
        let ct = CommitType {
            name: "chore".into(),
            bump: None,
            section: None,
            pattern: None,
        };
        let yaml = serde_yaml_ng::to_string(&ct).unwrap();
        assert!(!yaml.contains("bump"));
        assert!(!yaml.contains("section"));
        assert!(!yaml.contains("pattern"));
        let parsed: CommitType = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(parsed, ct);
    }

    #[test]
    fn commit_type_with_pattern_roundtrip() {
        let ct = CommitType {
            name: "deps".into(),
            bump: Some(BumpLevel::Patch),
            section: Some("Dependencies".into()),
            pattern: Some(r"^Bump .+ from .+ to .+".into()),
        };
        let yaml = serde_yaml_ng::to_string(&ct).unwrap();
        assert!(yaml.contains("pattern"));
        let parsed: CommitType = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(parsed, ct);
    }

    // --- ConfiguredCommitParser tests ---

    fn configured_parser_with_deps() -> ConfiguredCommitParser {
        let mut types = default_commit_types();
        types.push(CommitType {
            name: "deps".into(),
            bump: Some(BumpLevel::Patch),
            section: Some("Dependencies".into()),
            pattern: Some(r"^Bump (?P<description>.+)".into()),
        });
        ConfiguredCommitParser::new(types, DEFAULT_COMMIT_PATTERN.into())
    }

    #[test]
    fn configured_parser_standard_match_preferred() {
        let parser = configured_parser_with_deps();
        let result = parser.parse(&raw("feat: add button")).unwrap();
        assert_eq!(result.r#type, "feat");
        assert_eq!(result.description, "add button");
    }

    #[test]
    fn configured_parser_fallback_match() {
        let parser = configured_parser_with_deps();
        let result = parser
            .parse(&raw("Bump serde from 1.0.0 to 1.1.0"))
            .unwrap();
        assert_eq!(result.r#type, "deps");
        assert_eq!(result.description, "serde from 1.0.0 to 1.1.0");
    }

    #[test]
    fn configured_parser_fallback_no_named_groups() {
        let mut types = default_commit_types();
        types.push(CommitType {
            name: "deps".into(),
            bump: Some(BumpLevel::Patch),
            section: Some("Dependencies".into()),
            pattern: Some(r"^Bump .+ from .+ to .+".into()),
        });
        let parser = ConfiguredCommitParser::new(types, DEFAULT_COMMIT_PATTERN.into());
        let result = parser
            .parse(&raw("Bump serde from 1.0.0 to 1.1.0"))
            .unwrap();
        assert_eq!(result.r#type, "deps");
        // Without named description group, uses full first line
        assert_eq!(result.description, "Bump serde from 1.0.0 to 1.1.0");
    }

    #[test]
    fn configured_parser_no_match() {
        let parser = configured_parser_with_deps();
        let result = parser.parse(&raw("random garbage message"));
        assert!(result.is_err());
    }
}