conventional-commits-check 1.0.1

A lightweight library and CLI tool for validating Conventional Commits
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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
//! # Conventional Commits Validator
//!
//! A lightweight library for validating Git commit messages according to the
//! [Conventional Commits](https://conventionalcommits.org/) specification.
//!
//! ## Usage
//!
//! ```rust
//! use conventional_commits::{validate_commit, CommitType};
//!
//! let message = "feat: add new user authentication";
//! match validate_commit(message) {
//!     Ok(commit) => {
//!         println!("Valid commit: {:?}", commit.commit_type);
//!     }
//!     Err(e) => {
//!         eprintln!("Invalid commit: {}", e);
//!     }
//! }
//! ```

use regex::Regex;
use std::fmt;
use thiserror::Error;

/// Represents the type of a conventional commit
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommitType {
    /// A new feature
    Feat,
    /// A bug fix
    Fix,
    /// Documentation only changes
    Docs,
    /// Changes that do not affect the meaning of the code
    Style,
    /// A code change that neither fixes a bug nor adds a feature
    Refactor,
    /// A code change that improves performance
    Perf,
    /// Adding missing tests or correcting existing tests
    Test,
    /// Changes to the build process or auxiliary tools and libraries
    Build,
    /// Changes to CI configuration files and scripts
    Ci,
    /// Other changes that don't modify src or test files
    Chore,
    /// Reverts a previous commit
    Revert,
    /// Custom type not in the standard list
    Custom(String),
}

impl fmt::Display for CommitType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CommitType::Feat => write!(f, "feat"),
            CommitType::Fix => write!(f, "fix"),
            CommitType::Docs => write!(f, "docs"),
            CommitType::Style => write!(f, "style"),
            CommitType::Refactor => write!(f, "refactor"),
            CommitType::Perf => write!(f, "perf"),
            CommitType::Test => write!(f, "test"),
            CommitType::Build => write!(f, "build"),
            CommitType::Ci => write!(f, "ci"),
            CommitType::Chore => write!(f, "chore"),
            CommitType::Revert => write!(f, "revert"),
            CommitType::Custom(s) => write!(f, "{}", s),
        }
    }
}

impl From<&str> for CommitType {
    fn from(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "feat" => CommitType::Feat,
            "fix" => CommitType::Fix,
            "docs" => CommitType::Docs,
            "style" => CommitType::Style,
            "refactor" => CommitType::Refactor,
            "perf" => CommitType::Perf,
            "test" => CommitType::Test,
            "build" => CommitType::Build,
            "ci" => CommitType::Ci,
            "chore" => CommitType::Chore,
            "revert" => CommitType::Revert,
            _ => CommitType::Custom(s.to_string()),
        }
    }
}

/// Represents a parsed conventional commit
#[derive(Debug, Clone)]
pub struct ConventionalCommit {
    /// The type of the commit
    pub commit_type: CommitType,
    /// Optional scope of the commit
    pub scope: Option<String>,
    /// Whether this commit contains breaking changes
    pub breaking_change: bool,
    /// The description of the commit
    pub description: String,
    /// Optional body of the commit message
    pub body: Option<String>,
    /// Optional footers of the commit message
    pub footers: Vec<String>,
}

impl ConventionalCommit {
    /// Returns true if this commit represents a breaking change
    pub fn is_breaking_change(&self) -> bool {
        self.breaking_change
            || self
                .footers
                .iter()
                .any(|f| f.starts_with("BREAKING CHANGE:") || f.starts_with("BREAKING-CHANGE:"))
    }
}

/// A list of commit validation errors, used when multiple issues are detected simultaneously.
#[derive(Debug)]
pub struct ValidationErrors(pub Vec<CommitValidationError>);

impl fmt::Display for ValidationErrors {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, e) in self.0.iter().enumerate() {
            if i > 0 {
                writeln!(f)?;
            }
            write!(f, "  - {}", e)?;
        }
        Ok(())
    }
}

/// Errors that can occur when validating commit messages
#[derive(Error, Debug)]
pub enum CommitValidationError {
    #[error("Commit message is empty")]
    EmptyMessage,

    #[error("Invalid format: expected 'type(scope): description'")]
    InvalidFormat,

    #[error("Missing commit type")]
    MissingType,

    #[error("Missing description")]
    MissingDescription,

    #[error("Description must start with lowercase letter")]
    DescriptionNotLowercase,

    #[error("Description must not end with a period")]
    DescriptionEndsWithPeriod,

    #[error("Description is too long (max 72 characters)")]
    DescriptionTooLong,

    #[error("Description is too short (min {0} characters)")]
    DescriptionTooShort(usize),

    #[error("Commit type '{0}' is not recognized")]
    UnknownType(String),

    #[error("Type '{0}' is not allowed. Allowed types are: {1}")]
    TypeNotAllowed(String, String),

    #[error("A blank line is required between the header and the body")]
    MissingBlankLine,

    #[error("Scope '{0}' is not in the allowed scopes list")]
    ScopeNotAllowed(String),

    #[error("Scope '{0}' must be lowercase")]
    ScopeNotLowercase(String),

    #[error("A scope is required")]
    ScopeRequired,

    #[error("No footer matches the required issue pattern '{0}'")]
    MissingIssueRef(String),

    #[error("Invalid issue pattern regex '{0}': {1}")]
    InvalidIssuePattern(String, String),

    #[error("Multiple validation errors:\n{0}")]
    Multiple(ValidationErrors),
}

/// Configuration for commit validation
#[derive(Debug, Clone)]
pub struct ValidationConfig {
    /// Maximum length for the description
    pub max_description_length: usize,
    /// Whether to allow custom commit types
    pub allow_custom_types: bool,
    /// Whether to enforce lowercase description
    pub enforce_lowercase_description: bool,
    /// Whether to disallow period at end of description
    pub disallow_description_period: bool,
    /// Optional list of allowed scopes; if `None`, any scope is accepted
    pub allowed_scopes: Option<Vec<String>>,
    /// Whether to enforce lowercase scope
    pub enforce_lowercase_scope: bool,
    /// Whether a scope is required on every commit
    pub require_scope: bool,
    /// Optional regex pattern that at least one footer must match (e.g. `r"^Refs: #\d+"`)
    pub issue_pattern: Option<String>,
    /// Minimum length for the description (0 means no minimum beyond non-empty)
    pub min_description_length: usize,
    /// Optional list of allowed types; if `None`, all types are accepted
    pub allowed_types: Option<Vec<String>>,
}

impl Default for ValidationConfig {
    fn default() -> Self {
        Self {
            max_description_length: 72,
            allow_custom_types: true,
            enforce_lowercase_description: true,
            disallow_description_period: true,
            allowed_scopes: None,
            enforce_lowercase_scope: false,
            require_scope: false,
            issue_pattern: None,
            min_description_length: 0,
            allowed_types: None,
        }
    }
}

/// Parses a commit header strictly: requires exactly one space after `:`.
fn parse_header(
    header: &str,
) -> Result<(String, Option<String>, bool, String), CommitValidationError> {
    let bytes = header.as_bytes();
    let mut i = 0;

    while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
        i += 1;
    }
    if i == 0 {
        return Err(CommitValidationError::MissingType);
    }
    let type_str = header[..i].to_string();

    let scope = if bytes.get(i) == Some(&b'(') {
        i += 1;
        let start = i;
        while i < bytes.len() && bytes[i] != b')' {
            i += 1;
        }
        if i >= bytes.len() {
            return Err(CommitValidationError::InvalidFormat);
        }
        let sc = header[start..i].to_string();
        i += 1;
        Some(sc)
    } else {
        None
    };

    let breaking = if bytes.get(i) == Some(&b'!') {
        i += 1;
        true
    } else {
        false
    };

    if bytes.get(i) != Some(&b':') || bytes.get(i + 1) != Some(&b' ') {
        return Err(CommitValidationError::InvalidFormat);
    }
    i += 2;

    let description = header[i..].to_string();
    if description.is_empty() {
        return Err(CommitValidationError::MissingDescription);
    }

    Ok((type_str, scope, breaking, description))
}

/// Parses a commit header loosely: allows zero or more spaces after `:` (for auto-fix).
fn parse_header_loose(header: &str) -> Option<(String, Option<String>, bool, String)> {
    let bytes = header.as_bytes();
    let mut i = 0;

    while i < bytes.len() && (bytes[i].is_ascii_alphanumeric() || bytes[i] == b'_') {
        i += 1;
    }
    if i == 0 {
        return None;
    }
    let type_str = header[..i].to_string();

    let scope = if bytes.get(i) == Some(&b'(') {
        i += 1;
        let start = i;
        while i < bytes.len() && bytes[i] != b')' {
            i += 1;
        }
        if i >= bytes.len() {
            return None;
        }
        let sc = header[start..i].to_string();
        i += 1;
        Some(sc)
    } else {
        None
    };

    let breaking = if bytes.get(i) == Some(&b'!') {
        i += 1;
        true
    } else {
        false
    };

    if bytes.get(i) != Some(&b':') {
        return None;
    }
    i += 1;

    while i < bytes.len() && bytes[i] == b' ' {
        i += 1;
    }

    let description = header[i..].to_string();
    if description.is_empty() {
        return None;
    }

    Some((type_str, scope, breaking, description))
}

/// Validates a commit message according to Conventional Commits specification
///
/// # Arguments
///
/// * `message` - The commit message to validate
///
/// # Returns
///
/// Returns `Ok(ConventionalCommit)` if valid, or `Err(CommitValidationError)` if invalid
///
/// # Examples
///
/// ```
/// use conventional_commits::validate_commit;
///
/// let result = validate_commit("feat: add user authentication");
/// assert!(result.is_ok());
///
/// let result = validate_commit("invalid commit message");
/// assert!(result.is_err());
/// ```
pub fn validate_commit(message: &str) -> Result<ConventionalCommit, CommitValidationError> {
    validate_commit_with_config(message, &ValidationConfig::default())
}

/// Validates a commit message with custom configuration
///
/// # Arguments
///
/// * `message` - The commit message to validate
/// * `config` - Custom validation configuration
///
/// # Returns
///
/// Returns `Ok(ConventionalCommit)` if valid, or `Err(CommitValidationError)` if invalid
pub fn validate_commit_with_config(
    message: &str,
    config: &ValidationConfig,
) -> Result<ConventionalCommit, CommitValidationError> {
    if message.trim().is_empty() {
        return Err(CommitValidationError::EmptyMessage);
    }

    let lines: Vec<&str> = message.lines().collect();
    let header = lines[0];

    // Header parsing fails fast — without a parseable header we cannot continue.
    let (type_str, scope, breaking_change, description) = parse_header(header)?;

    let mut errors: Vec<CommitValidationError> = Vec::new();

    // Validate Blank Line Rule:
    // If there is more than one line, the second line MUST be empty.
    if lines.len() > 1 && !lines[1].trim().is_empty() {
        errors.push(CommitValidationError::MissingBlankLine);
    }

    // Validate commit type
    let commit_type = CommitType::from(type_str.as_str());
    if !config.allow_custom_types {
        if let CommitType::Custom(_) = commit_type {
            errors.push(CommitValidationError::UnknownType(type_str.clone()));
        }
    }
    if let Some(ref allowed) = config.allowed_types {
        if !allowed.contains(&type_str) {
            errors.push(CommitValidationError::TypeNotAllowed(
                type_str.clone(),
                allowed.join(", "),
            ));
        }
    }

    // Validate scope (only when a scope is present)
    if let Some(ref s) = scope {
        if let Some(ref allowed) = config.allowed_scopes {
            if !allowed.iter().any(|a| a == s) {
                errors.push(CommitValidationError::ScopeNotAllowed(s.clone()));
            }
        }
        if config.enforce_lowercase_scope && s.chars().any(|c| c.is_uppercase()) {
            errors.push(CommitValidationError::ScopeNotLowercase(s.clone()));
        }
    } else if config.require_scope {
        errors.push(CommitValidationError::ScopeRequired);
    }

    // Validate description
    if config.enforce_lowercase_description {
        if let Some(first) = description.chars().next() {
            if !first.is_lowercase() {
                errors.push(CommitValidationError::DescriptionNotLowercase);
            }
        }
    }

    if config.disallow_description_period && description.ends_with('.') {
        errors.push(CommitValidationError::DescriptionEndsWithPeriod);
    }

    if description.len() > config.max_description_length {
        errors.push(CommitValidationError::DescriptionTooLong);
    }

    if config.min_description_length > 0 && description.len() < config.min_description_length {
        errors.push(CommitValidationError::DescriptionTooShort(
            config.min_description_length,
        ));
    }

    // Parse body and footers
    let mut body_lines: Vec<String> = Vec::new();
    let mut footer_lines: Vec<String> = Vec::new();
    let mut is_breaking = breaking_change;

    if lines.len() > 2 {
        for line in lines[2..].iter() {
            if is_breaking_footer(line) || is_footer(line) {
                footer_lines.push(line.to_string());
                if is_breaking_footer(line) {
                    is_breaking = true;
                }
            } else {
                if !footer_lines.is_empty() {
                    body_lines.append(&mut footer_lines);
                }
                body_lines.push((*line).to_string());
            }
        }
    }

    // Validate issue pattern: at least one footer must match
    if let Some(ref pattern) = config.issue_pattern {
        let re = Regex::new(pattern).map_err(|e| {
            CommitValidationError::InvalidIssuePattern(pattern.clone(), e.to_string())
        })?;
        if !footer_lines.iter().any(|f| re.is_match(f)) {
            errors.push(CommitValidationError::MissingIssueRef(pattern.clone()));
        }
    }

    if errors.len() == 1 {
        return Err(errors.remove(0));
    } else if errors.len() > 1 {
        return Err(CommitValidationError::Multiple(ValidationErrors(errors)));
    }

    let body = if body_lines.is_empty() {
        None
    } else {
        Some(body_lines.join("\n").trim().to_string())
    };

    Ok(ConventionalCommit {
        commit_type,
        scope,
        breaking_change: is_breaking,
        description,
        body,
        footers: footer_lines,
    })
}

/// Attempts to fix common mistakes in a commit message header.
///
/// Fixes applied (only to the first line):
/// - Lowercases the commit type (`Feat:` → `feat:`)
/// - Adds missing space after colon (`feat:add thing` → `feat: add thing`)
/// - Lowercases first letter of description (`feat: Add thing` → `feat: add thing`)
/// - Removes trailing period from description (`feat: add thing.` → `feat: add thing`)
/// - Strips leading/trailing whitespace from description (`feat:  add thing  ` → `feat: add thing`)
///
/// Returns the (potentially modified) message. If the header cannot be parsed
/// even loosely, the original message is returned unchanged.
pub fn fix_commit_message(message: &str) -> String {
    let lines: Vec<&str> = message.lines().collect();
    if lines.is_empty() {
        return message.to_string();
    }

    let header = lines[0];

    // Loose parse: allows zero or more spaces after colon so we can fix missing space
    let fixed_header = match parse_header_loose(header) {
        None => return message.to_string(),
        Some((type_str, scope, breaking, description)) => {
            let type_lower = type_str.to_lowercase();
            let breaking_str = if breaking { "!" } else { "" };
            let fixed_desc = fix_description(&description);
            match scope {
                Some(s) => format!("{}({}){}: {}", type_lower, s, breaking_str, fixed_desc),
                None => format!("{}{}: {}", type_lower, breaking_str, fixed_desc),
            }
        }
    };

    if lines.len() == 1 {
        fixed_header
    } else {
        format!("{}\n{}", fixed_header, lines[1..].join("\n"))
    }
}

fn fix_description(desc: &str) -> String {
    // Strip leading/trailing whitespace
    let desc = desc.trim();
    // Strip trailing period
    let desc = desc.strip_suffix('.').unwrap_or(desc);
    // Lowercase first char
    let mut chars = desc.chars();
    match chars.next() {
        None => String::new(),
        Some(first) => {
            let lower: String = first.to_lowercase().collect();
            lower + chars.as_str()
        }
    }
}

/// Result of applying clean rules to a commit message body.
#[derive(Debug, Clone)]
pub struct CleanResult {
    /// The message after removing matched lines, collapsing excess blank lines,
    /// and trimming trailing whitespace.
    pub cleaned_message: String,
    /// Every line that was removed (in the order they appeared in the original message).
    pub removed_lines: Vec<String>,
}

/// Cleans a commit message body by removing lines that match any of the provided rules.
///
/// Rules are applied only to lines after the first (header). Cleaning steps:
/// 1. Remove lines where `line.trim_end()` starts with any entry in `starts_with_rules`.
/// 2. Remove lines where `line.trim_end()` matches any compiled regex in `regex_rules`.
/// 3. Trim trailing whitespace from every surviving line.
/// 4. Collapse consecutive blank lines down to at most one.
/// 5. Strip trailing blank lines.
///
/// Returns `Err` if any regex pattern fails to compile.
pub fn clean_commit_body(
    message: &str,
    starts_with_rules: &[&str],
    regex_rules: &[&str],
) -> Result<CleanResult, regex::Error> {
    let compiled: Vec<Regex> = regex_rules
        .iter()
        .map(|p| Regex::new(p))
        .collect::<Result<Vec<_>, _>>()?;

    let lines: Vec<&str> = message.lines().collect();
    if lines.len() <= 1 || (starts_with_rules.is_empty() && compiled.is_empty()) {
        return Ok(CleanResult {
            cleaned_message: message.to_string(),
            removed_lines: vec![],
        });
    }

    let header = lines[0].to_string();
    let mut removed_lines: Vec<String> = Vec::new();
    let mut kept: Vec<String> = Vec::new();

    for line in &lines[1..] {
        let trimmed = line.trim_end();
        let matches = starts_with_rules.iter().any(|r| trimmed.starts_with(r))
            || compiled.iter().any(|re| re.is_match(trimmed));
        if matches {
            removed_lines.push(line.to_string());
        } else {
            kept.push(trimmed.to_string());
        }
    }

    // Collapse consecutive blank lines to at most one
    let mut collapsed: Vec<String> = Vec::new();
    let mut last_blank = false;
    for line in kept {
        let blank = line.is_empty();
        if blank && last_blank {
            continue;
        }
        last_blank = blank;
        collapsed.push(line);
    }

    // Strip trailing blank lines
    while collapsed
        .last()
        .map(|l: &String| l.is_empty())
        .unwrap_or(false)
    {
        collapsed.pop();
    }

    let mut result_lines = vec![header];
    result_lines.extend(collapsed);

    Ok(CleanResult {
        cleaned_message: result_lines.join("\n"),
        removed_lines,
    })
}

/// Helper to identify Git trailers (footers): "Token: Value" or "Token #Value"
fn is_footer(line: &str) -> bool {
    let token_end = line
        .find(|c: char| !c.is_ascii_alphabetic() && c != '-')
        .unwrap_or(0);
    if token_end == 0 {
        return false;
    }
    let rest = &line[token_end..];
    (rest.starts_with(": ") && rest.len() > 2) || rest.starts_with(" #")
}

fn is_breaking_footer(line: &str) -> bool {
    line.starts_with("BREAKING CHANGE: ") || line.starts_with("BREAKING-CHANGE: ")
}

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

    #[test]
    fn test_valid_commits() {
        let valid_commits = vec![
            "feat: add user authentication",
            "feat(auth): add OAuth support",
            "feat!: breaking change",
            "fix: bug\n\nBody message", // Standard compliant
        ];

        for commit in valid_commits {
            let res = validate_commit(commit);
            assert!(res.is_ok(), "Failed on: {}\nError: {:?}", commit, res.err());
        }
    }

    #[test]
    fn test_invalid_commits() {
        let invalid = vec![
            ("feat:no-space", "Missing space after colon"),
            (
                "feat: description\nNo blank line",
                "Missing blank line rule",
            ),
        ];

        for (msg, reason) in invalid {
            let res = validate_commit(msg);
            assert!(res.is_err(), "Should fail for {}: {}", reason, msg);
        }
    }

    #[test]
    fn test_breaking_change_footer() {
        let msg = "feat: logic\n\nBREAKING CHANGE: this is a footer";
        let commit = validate_commit(msg).unwrap();
        assert!(
            commit.breaking_change,
            "Footer should trigger breaking_change flag"
        );
    }

    #[test]
    fn test_breaking_change_detection() {
        let commit = validate_commit("feat!: breaking change").unwrap();
        assert!(commit.breaking_change);

        let commit_with_footer =
            validate_commit("feat: new feature\n\nBREAKING CHANGE: this breaks something").unwrap();
        assert!(commit_with_footer.is_breaking_change());
    }

    #[test]
    fn test_commit_types() {
        assert_eq!(CommitType::from("feat"), CommitType::Feat);
        assert_eq!(CommitType::from("fix"), CommitType::Fix);
        assert_eq!(
            CommitType::from("custom"),
            CommitType::Custom("custom".to_string())
        );
    }

    #[test]
    fn test_fix_missing_space() {
        assert_eq!(fix_commit_message("feat:add thing"), "feat: add thing");
        assert_eq!(fix_commit_message("fix:resolve bug"), "fix: resolve bug");
    }

    #[test]
    fn test_fix_uppercase_description() {
        assert_eq!(fix_commit_message("feat: Add thing"), "feat: add thing");
        assert_eq!(fix_commit_message("fix: Resolve bug"), "fix: resolve bug");
    }

    #[test]
    fn test_fix_trailing_period() {
        assert_eq!(fix_commit_message("feat: add thing."), "feat: add thing");
        assert_eq!(fix_commit_message("fix: resolve bug."), "fix: resolve bug");
    }

    #[test]
    fn test_fix_all_at_once() {
        assert_eq!(fix_commit_message("feat:Add thing."), "feat: add thing");
        assert_eq!(
            fix_commit_message("fix(parser):Resolve bug."),
            "fix(parser): resolve bug"
        );
    }

    #[test]
    fn test_fix_preserves_valid_message() {
        let msg = "feat: add thing";
        assert_eq!(fix_commit_message(msg), msg);
    }

    #[test]
    fn test_fix_with_scope_and_breaking() {
        assert_eq!(
            fix_commit_message("feat(auth)!:Add OAuth."),
            "feat(auth)!: add OAuth"
        );
    }

    #[test]
    fn test_fix_preserves_body() {
        let msg = "feat:Add thing.\n\nThis is the body.";
        let fixed = fix_commit_message(msg);
        assert_eq!(fixed, "feat: add thing\n\nThis is the body.");
    }

    #[test]
    fn test_fix_type_casing() {
        assert_eq!(fix_commit_message("Feat: add thing"), "feat: add thing");
        assert_eq!(fix_commit_message("FIX: resolve bug"), "fix: resolve bug");
        assert_eq!(
            fix_commit_message("CHORE(deps): bump version"),
            "chore(deps): bump version"
        );
    }

    #[test]
    fn test_fix_description_whitespace() {
        assert_eq!(fix_commit_message("feat:   add thing  "), "feat: add thing");
        assert_eq!(
            fix_commit_message("fix:  resolve  bug  "),
            "fix: resolve  bug"
        );
    }

    #[test]
    fn test_fix_unparseable_returns_original() {
        let msg = "not a conventional commit at all";
        assert_eq!(fix_commit_message(msg), msg);
    }

    // ---- scope-enum tests ----

    fn config_with_scopes(scopes: &[&str]) -> ValidationConfig {
        ValidationConfig {
            allowed_scopes: Some(scopes.iter().map(|s| s.to_string()).collect()),
            ..ValidationConfig::default()
        }
    }

    #[test]
    fn test_allowed_types_validation() {
        let config = ValidationConfig {
            allowed_types: Some(vec!["feat".to_string(), "fix".to_string()]),
            ..ValidationConfig::default()
        };

        // Should pass: 'feat' is in the allowed list
        let res = validate_commit_with_config("feat: add feature", &config);
        assert!(res.is_ok());

        // Should fail: 'chore' is not in the allowed list
        let res = validate_commit_with_config("chore: update deps", &config);
        assert!(res.is_err());
        if let Err(CommitValidationError::TypeNotAllowed(t, list)) = res {
            assert_eq!(t, "chore");
            assert!(list.contains("feat, fix"));
        } else {
            panic!("Expected TypeNotAllowed error");
        }
    }

    #[test]
    fn test_scope_allowed() {
        let cfg = config_with_scopes(&["api", "client"]);
        assert!(validate_commit_with_config("feat(api): add endpoint", &cfg).is_ok());
        assert!(validate_commit_with_config("fix(client): handle timeout", &cfg).is_ok());
    }

    #[test]
    fn test_scope_not_allowed() {
        let cfg = config_with_scopes(&["api", "client"]);
        let err = validate_commit_with_config("feat(ui): add button", &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::ScopeNotAllowed(ref s) if s == "ui"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_no_scope_passes_when_scopes_restricted() {
        // Commits without any scope are always accepted even when the list is set
        let cfg = config_with_scopes(&["api"]);
        assert!(validate_commit_with_config("feat: add thing", &cfg).is_ok());
    }

    #[test]
    fn test_no_scope_restriction_accepts_anything() {
        // Default config (allowed_scopes = None) accepts any scope
        assert!(validate_commit("feat(whatever): add thing").is_ok());
    }

    // ---- issue-pattern tests ----

    fn config_with_issue_pattern(pattern: &str) -> ValidationConfig {
        ValidationConfig {
            issue_pattern: Some(pattern.to_string()),
            ..ValidationConfig::default()
        }
    }

    #[test]
    fn test_issue_pattern_matched_by_footer() {
        let cfg = config_with_issue_pattern(r"^Refs: #\d+");
        let msg = "feat: add feature\n\nRefs: #123";
        assert!(validate_commit_with_config(msg, &cfg).is_ok());
    }

    #[test]
    fn test_issue_pattern_matched_jira_style() {
        let cfg = config_with_issue_pattern(r"^Fixes: [A-Z]+-\d+");
        let msg = "fix: resolve crash\n\nFixes: PROJ-456";
        assert!(validate_commit_with_config(msg, &cfg).is_ok());
    }

    #[test]
    fn test_issue_pattern_no_matching_footer_fails() {
        let cfg = config_with_issue_pattern(r"^Refs: #\d+");
        let msg = "feat: add feature\n\nReviewed-by: Alice";
        let err = validate_commit_with_config(msg, &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::MissingIssueRef(_)),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_issue_pattern_no_footers_at_all_fails() {
        let cfg = config_with_issue_pattern(r"^Refs: #\d+");
        let msg = "feat: add feature";
        let err = validate_commit_with_config(msg, &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::MissingIssueRef(_)),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_issue_pattern_none_always_passes() {
        // Default config has no issue_pattern — any valid commit passes
        assert!(validate_commit("feat: add feature").is_ok());
        assert!(validate_commit("fix: resolve crash\n\nReviewed-by: Alice").is_ok());
    }

    #[test]
    fn test_issue_pattern_invalid_regex_returns_error() {
        let cfg = config_with_issue_pattern(r"[invalid(");
        let msg = "feat: add feature\n\nRefs: #123";
        let err = validate_commit_with_config(msg, &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::InvalidIssuePattern(_, _)),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_issue_pattern_one_of_multiple_footers_matches() {
        let cfg = config_with_issue_pattern(r"^Closes: #\d+");
        let msg = "feat: add feature\n\nReviewed-by: Bob\nCloses: #42";
        assert!(validate_commit_with_config(msg, &cfg).is_ok());
    }

    // ---- require-scope tests ----

    #[test]
    fn test_require_scope_missing() {
        let cfg = ValidationConfig {
            require_scope: true,
            ..ValidationConfig::default()
        };
        let err = validate_commit_with_config("feat: add thing", &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::ScopeRequired),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_require_scope_present_passes() {
        let cfg = ValidationConfig {
            require_scope: true,
            ..ValidationConfig::default()
        };
        assert!(validate_commit_with_config("feat(api): add thing", &cfg).is_ok());
    }

    #[test]
    fn test_require_scope_not_enforced_by_default() {
        assert!(validate_commit("feat: add thing").is_ok());
    }

    // ---- scope-lowercase tests ----

    #[test]
    fn test_scope_lowercase_enforced() {
        let cfg = ValidationConfig {
            enforce_lowercase_scope: true,
            ..ValidationConfig::default()
        };
        let err = validate_commit_with_config("feat(API): add endpoint", &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::ScopeNotLowercase(ref s) if s == "API"),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_scope_lowercase_not_enforced_by_default() {
        assert!(validate_commit("feat(API): add endpoint").is_ok());
    }

    #[test]
    fn test_scope_already_lowercase_passes() {
        let cfg = ValidationConfig {
            enforce_lowercase_scope: true,
            ..ValidationConfig::default()
        };
        assert!(validate_commit_with_config("feat(api): add endpoint", &cfg).is_ok());
    }

    // ---- multiple-errors tests ----

    #[test]
    fn test_multiple_errors_collected() {
        // Uppercase first letter + trailing period → two description errors reported at once
        let err = validate_commit("feat: Add thing.").unwrap_err();
        assert!(
            matches!(err, CommitValidationError::Multiple(_)),
            "expected Multiple, got: {err}"
        );
    }

    // ---- min-description-length tests ----

    #[test]
    fn test_min_description_length_too_short() {
        let cfg = ValidationConfig {
            min_description_length: 20,
            ..ValidationConfig::default()
        };
        let err = validate_commit_with_config("feat: add thing", &cfg).unwrap_err();
        assert!(
            matches!(err, CommitValidationError::DescriptionTooShort(20)),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn test_min_description_length_ok() {
        let cfg = ValidationConfig {
            min_description_length: 5,
            ..ValidationConfig::default()
        };
        assert!(validate_commit_with_config("feat: add thing", &cfg).is_ok());
    }

    #[test]
    fn test_min_description_length_zero_default() {
        // Default config has no minimum — single-char description passes
        assert!(validate_commit("fix: x").is_ok());
    }

    #[test]
    fn test_single_error_not_wrapped_in_multiple() {
        // Only one violation should not be wrapped in Multiple
        let err = validate_commit("feat: Add thing").unwrap_err();
        assert!(
            matches!(err, CommitValidationError::DescriptionNotLowercase),
            "expected DescriptionNotLowercase, got: {err}"
        );
    }

    // ---- clean_commit_body tests ----

    #[test]
    fn clean_no_rules_returns_message_unchanged() {
        let msg = "feat: add thing\n\nBody line.\nCo-authored-by: Alice";
        let result = clean_commit_body(msg, &[], &[]).unwrap();
        assert_eq!(result.cleaned_message, msg);
        assert!(result.removed_lines.is_empty());
    }

    #[test]
    fn clean_starts_with_removes_matching_lines() {
        let msg =
            "feat: add thing\n\nBody text.\nCo-authored-by: Alice <a@x.com>\nSigned-off-by: Bob";
        let result = clean_commit_body(msg, &["Co-authored-by", "Signed-off-by"], &[]).unwrap();
        assert_eq!(result.cleaned_message, "feat: add thing\n\nBody text.");
        assert_eq!(result.removed_lines.len(), 2);
        assert!(result.removed_lines[0].contains("Co-authored-by"));
        assert!(result.removed_lines[1].contains("Signed-off-by"));
    }

    #[test]
    fn clean_regex_removes_matching_lines() {
        let msg = "fix: crash\n\nFixed the thing.\nCo-authored-by: Alice <a@x.com>";
        let result = clean_commit_body(msg, &[], &[r"^Co-authored-by:"]).unwrap();
        assert_eq!(result.cleaned_message, "fix: crash\n\nFixed the thing.");
        assert_eq!(result.removed_lines.len(), 1);
    }

    #[test]
    fn clean_both_rule_types_combined() {
        let msg = "feat: thing\n\nBody.\nCo-authored-by: Alice\nSigned-off-by: Bob\n🤖 generated";
        let result =
            clean_commit_body(msg, &["Co-authored-by", "Signed-off-by"], &[r"^🤖"]).unwrap();
        assert_eq!(result.cleaned_message, "feat: thing\n\nBody.");
        assert_eq!(result.removed_lines.len(), 3);
    }

    #[test]
    fn clean_collapses_consecutive_blank_lines() {
        let msg = "feat: thing\n\nParagraph one.\n\n\nParagraph two.";
        let result = clean_commit_body(msg, &["__no_match__"], &[]).unwrap();
        assert_eq!(
            result.cleaned_message,
            "feat: thing\n\nParagraph one.\n\nParagraph two."
        );
    }

    #[test]
    fn clean_strips_trailing_blank_lines() {
        let msg = "feat: thing\n\nBody.\n\n";
        let result = clean_commit_body(msg, &["__no_match__"], &[]).unwrap();
        assert_eq!(result.cleaned_message, "feat: thing\n\nBody.");
    }

    #[test]
    fn clean_trims_trailing_whitespace_per_line() {
        let msg = "feat: thing\n\nLine with spaces.   \nAnother line.  ";
        let result = clean_commit_body(msg, &["__no_match__"], &[]).unwrap();
        assert_eq!(
            result.cleaned_message,
            "feat: thing\n\nLine with spaces.\nAnother line."
        );
    }

    #[test]
    fn clean_header_only_message_is_unchanged() {
        let msg = "feat: add thing";
        let result = clean_commit_body(msg, &["Co-authored-by"], &[]).unwrap();
        assert_eq!(result.cleaned_message, msg);
        assert!(result.removed_lines.is_empty());
    }

    #[test]
    fn clean_invalid_regex_returns_error() {
        let msg = "feat: thing\n\nBody.";
        let err = clean_commit_body(msg, &[], &[r"[invalid("]);
        assert!(err.is_err());
    }

    #[test]
    fn clean_does_not_touch_header() {
        // Even if the header would match a rule, it must not be removed.
        let msg = "feat: add thing\n\nCo-authored-by: Alice";
        let result = clean_commit_body(msg, &["feat"], &[]).unwrap();
        // header line starts with "feat" but must be kept
        assert!(result.cleaned_message.starts_with("feat: add thing"));
    }

    #[test]
    fn clean_preserves_message_when_no_lines_removed() {
        let msg = "fix: resolve crash\n\nFixed the null pointer.\n\nRefs: #42";
        let result = clean_commit_body(msg, &["Co-authored-by"], &[]).unwrap();
        assert_eq!(result.cleaned_message, msg);
        assert!(result.removed_lines.is_empty());
    }

    #[test]
    fn test_allowed_types_with_custom_type() {
        let config = ValidationConfig {
            allowed_types: Some(vec!["api".to_string()]),
            ..ValidationConfig::default()
        };

        // Should pass: 'api' is explicitly allowed
        let res = validate_commit_with_config("api: new endpoint", &config);
        assert!(res.is_ok());

        // Should fail: standard 'feat' is not in this specific project's list
        let res = validate_commit_with_config("feat: add feature", &config);
        assert!(res.is_err());
    }
}