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
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
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
use super::{Body, BreakingChange, CommitType, Description, Footer, References, Scope};
use thiserror::Error;

/// Errors that can occur when creating a ConventionalCommit
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum CommitMessageError {
    /// The complete first line exceeds the maximum allowed length
    #[error("first line too long: {actual} characters (max {max})")]
    FirstLineTooLong { actual: usize, max: usize },

    /// The formatted message is not parseable as a conventional commit
    ///
    /// This should never occur in normal use - it indicates a bug in the
    /// formatting logic.
    #[error("output failed git-conventional validation: {reason}")]
    InvalidConventionalFormat { reason: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConventionalCommit {
    commit_type: CommitType,
    scope: Scope,
    description: Description,
    breaking_change: BreakingChange,
    body: Body,
    references: References,
}

impl ConventionalCommit {
    /// Maximum allowed length for the complete first line (type + scope + description)
    pub const FIRST_LINE_MAX_LENGTH: usize = 72;

    /// Create a new conventional commit message
    ///
    /// # Arguments
    /// All arguments are pre-validated types, but the combined first line
    /// length is validated here (max 72 characters).
    ///
    /// # Errors
    /// Returns `CommitMessageError::FirstLineTooLong` if the formatted first
    /// line exceeds 72 characters.
    pub fn new(
        commit_type: CommitType,
        scope: Scope,
        description: Description,
        breaking_change: BreakingChange,
        body: Body,
        references: References,
    ) -> Result<Self, CommitMessageError> {
        let commit = Self {
            commit_type,
            scope,
            description,
            breaking_change,
            body,
            references,
        };
        let len = commit.first_line_len();
        if len > Self::FIRST_LINE_MAX_LENGTH {
            return Err(CommitMessageError::FirstLineTooLong {
                actual: len,
                max: Self::FIRST_LINE_MAX_LENGTH,
            });
        }
        let formatted = commit.format();
        git_conventional::Commit::parse(&formatted).map_err(|e| {
            CommitMessageError::InvalidConventionalFormat {
                reason: e.to_string(),
            }
        })?;
        Ok(commit)
    }

    /// Calculate the length of the formatted first line
    ///
    /// Formula:
    /// - `len(type)` + `len(scope)` + `len(breaking_change)` + 2 + `len(description)`
    ///   (the 2 accounts for colon and space: ": ")
    pub fn first_line_len(&self) -> usize {
        self.commit_type.len()
            + self.scope.header_segment_len()
            + if self.breaking_change.is_absent() { 0 } else { 1 }
            + 2 // ": "
            + self.description.len()
    }

    /// Format the complete commit message
    ///
    /// Returns `type(scope): description` if scope is non-empty, or
    /// `type: description` if scope is empty
    pub fn format(&self) -> String {
        Self::format_preview(
            self.commit_type,
            &self.scope,
            &self.description,
            &self.breaking_change,
            &self.body,
            &self.references,
        )
    }

    /// Format a preview of the commit message without creating a validated instance
    ///
    /// This is useful for showing what the message would look like before validation
    /// Returns `type(scope): description` if scope is non-empty, or
    /// `type: description` if scope is empty
    pub fn format_preview(
        commit_type: CommitType,
        scope: &Scope,
        description: &Description,
        breaking_change: &BreakingChange,
        body: &Body,
        references: &References,
    ) -> String {
        let scope = scope.header_segment();
        let breaking_change_header = breaking_change.header_segment();
        let breaking_change_footer = breaking_change.as_footer();
        let refs_footer = references.as_footer();
        format!(
            r#"{commit_type}{scope}{breaking_change_header}: {description}
{}
{breaking_change_footer}{refs_footer}"#,
            body.format()
        )
        .trim()
        .to_string()
    }
}

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

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

    /// Helper to create a valid Scope for testing
    fn test_scope(value: &str) -> Scope {
        Scope::parse(value).expect("test scope should be valid")
    }

    /// Helper to create a valid Description for testing
    fn test_description(value: &str) -> Description {
        Description::parse(value).expect("test description should be valid")
    }

    /// Helper to create a valid ConventionalCommit for testing
    fn test_commit(
        commit_type: CommitType,
        scope: Scope,
        description: Description,
        breaking_change: BreakingChange,
    ) -> ConventionalCommit {
        ConventionalCommit::new(
            commit_type,
            scope,
            description,
            breaking_change,
            Body::default(),
            References::default(),
        )
        .expect("test commit should have valid line length")
    }

    /// Test that ConventionalCommit::new() creates a valid commit with all fields
    #[test]
    fn new_creates_commit_with_all_fields() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add new feature"),
            BreakingChange::No,
        );
        assert_eq!(commit.commit_type, CommitType::Feat);
        assert_eq!(commit.scope.as_str(), "cli");
        assert_eq!(commit.description.as_str(), "add new feature");
    }

    /// Test that ConventionalCommit::new() works with empty scope
    #[test]
    fn new_creates_commit_with_empty_scope() {
        let commit = test_commit(
            CommitType::Fix,
            Scope::empty(),
            test_description("fix critical bug"),
            BreakingChange::No,
        );
        assert_eq!(commit.commit_type, CommitType::Fix);
        assert!(commit.scope.is_empty());
        assert_eq!(commit.description.as_str(), "fix critical bug");
    }

    /// Test that format() produces "type(scope): description" when scope is non-empty
    #[test]
    fn format_with_scope_produces_correct_output() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("add login"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "feat(auth): add login");
    }

    /// Test format with different scope values
    #[test]
    fn format_with_various_scopes() {
        // Hyphenated scope
        let commit1 = test_commit(
            CommitType::Fix,
            test_scope("user-auth"),
            test_description("fix token refresh"),
            BreakingChange::No,
        );
        assert_eq!(commit1.format(), "fix(user-auth): fix token refresh");

        // Underscored scope
        let commit2 = test_commit(
            CommitType::Docs,
            test_scope("api_docs"),
            test_description("update README"),
            BreakingChange::No,
        );
        assert_eq!(commit2.format(), "docs(api_docs): update README");

        // Scope with slash (Jira-style)
        let commit3 = test_commit(
            CommitType::Chore,
            test_scope("PROJ-123/cleanup"),
            test_description("remove unused code"),
            BreakingChange::No,
        );
        assert_eq!(
            commit3.format(),
            "chore(PROJ-123/cleanup): remove unused code"
        );
    }

    /// Test that format() produces "type: description" when scope is empty
    #[test]
    fn format_without_scope_produces_correct_output() {
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("add login"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "feat: add login");
    }

    /// Test format without scope for various descriptions
    #[test]
    fn format_without_scope_various_descriptions() {
        let commit1 = test_commit(
            CommitType::Fix,
            Scope::empty(),
            test_description("fix critical bug"),
            BreakingChange::No,
        );
        assert_eq!(commit1.format(), "fix: fix critical bug");

        let commit2 = test_commit(
            CommitType::Docs,
            Scope::empty(),
            test_description("update installation guide"),
            BreakingChange::No,
        );
        assert_eq!(commit2.format(), "docs: update installation guide");
    }

    /// Test that all 11 commit types format correctly with scope
    #[test]
    fn all_commit_types_format_correctly_with_scope() {
        let scope = test_scope("cli");
        let desc = test_description("test change");

        let expected_formats = [
            (CommitType::Feat, "feat(cli): test change"),
            (CommitType::Fix, "fix(cli): test change"),
            (CommitType::Docs, "docs(cli): test change"),
            (CommitType::Style, "style(cli): test change"),
            (CommitType::Refactor, "refactor(cli): test change"),
            (CommitType::Perf, "perf(cli): test change"),
            (CommitType::Test, "test(cli): test change"),
            (CommitType::Build, "build(cli): test change"),
            (CommitType::Ci, "ci(cli): test change"),
            (CommitType::Chore, "chore(cli): test change"),
            (CommitType::Revert, "revert(cli): test change"),
        ];

        for (commit_type, expected) in expected_formats {
            let commit = test_commit(commit_type, scope.clone(), desc.clone(), BreakingChange::No);
            assert_eq!(
                commit.format(),
                expected,
                "Format should be correct for {:?}",
                commit_type
            );
        }
    }

    /// Test that all 11 commit types format correctly without scope
    #[test]
    fn all_commit_types_format_correctly_without_scope() {
        let desc = test_description("test change");

        let expected_formats = [
            (CommitType::Feat, "feat: test change"),
            (CommitType::Fix, "fix: test change"),
            (CommitType::Docs, "docs: test change"),
            (CommitType::Style, "style: test change"),
            (CommitType::Refactor, "refactor: test change"),
            (CommitType::Perf, "perf: test change"),
            (CommitType::Test, "test: test change"),
            (CommitType::Build, "build: test change"),
            (CommitType::Ci, "ci: test change"),
            (CommitType::Chore, "chore: test change"),
            (CommitType::Revert, "revert: test change"),
        ];

        for (commit_type, expected) in expected_formats {
            let commit = test_commit(
                commit_type,
                Scope::empty(),
                desc.clone(),
                BreakingChange::No,
            );
            assert_eq!(
                commit.format(),
                expected,
                "Format should be correct for {:?}",
                commit_type
            );
        }
    }

    /// Test that Display implementation delegates to format()
    #[test]
    fn display_delegates_to_format() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("add login"),
            BreakingChange::No,
        );
        let display_output = format!("{}", commit);
        let format_output = commit.format();
        assert_eq!(display_output, format_output);
    }

    /// Test Display with scope
    #[test]
    fn display_with_scope() {
        let commit = test_commit(
            CommitType::Fix,
            test_scope("api"),
            test_description("handle null response"),
            BreakingChange::No,
        );
        assert_eq!(format!("{}", commit), "fix(api): handle null response");
    }

    /// Test Display without scope
    #[test]
    fn display_without_scope() {
        let commit = test_commit(
            CommitType::Docs,
            Scope::empty(),
            test_description("improve README"),
            BreakingChange::No,
        );
        assert_eq!(format!("{}", commit), "docs: improve README");
    }

    /// Test Display delegates to format for all commit types
    #[test]
    fn display_equals_format_for_all_types() {
        for commit_type in CommitType::all() {
            // With scope
            let commit_with_scope = test_commit(
                *commit_type,
                test_scope("test"),
                test_description("change"),
                BreakingChange::No,
            );
            assert_eq!(
                format!("{}", commit_with_scope),
                commit_with_scope.format(),
                "Display should equal format() for {:?} with scope",
                commit_type
            );

            // Without scope
            let commit_without_scope = test_commit(
                *commit_type,
                Scope::empty(),
                test_description("change"),
                BreakingChange::No,
            );
            assert_eq!(
                format!("{}", commit_without_scope),
                commit_without_scope.format(),
                "Display should equal format() for {:?} without scope",
                commit_type
            );
        }
    }

    /// Test Clone trait
    #[test]
    fn conventional_commit_is_cloneable() {
        let original = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add feature"),
            BreakingChange::No,
        );
        let cloned = original.clone();
        assert_eq!(original, cloned);
    }

    /// Test PartialEq trait - equal commits
    #[test]
    fn conventional_commit_equality() {
        let commit1 = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add feature"),
            BreakingChange::No,
        );
        let commit2 = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add feature"),
            BreakingChange::No,
        );
        assert_eq!(commit1, commit2);
    }

    /// Test PartialEq trait - different commit types
    #[test]
    fn conventional_commit_inequality_different_type() {
        let commit1 = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("change"),
            BreakingChange::No,
        );
        let commit2 = test_commit(
            CommitType::Fix,
            test_scope("cli"),
            test_description("change"),
            BreakingChange::No,
        );
        assert_ne!(commit1, commit2);
    }

    /// Test PartialEq trait - different scopes
    #[test]
    fn conventional_commit_inequality_different_scope() {
        let commit1 = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("change"),
            BreakingChange::No,
        );
        let commit2 = test_commit(
            CommitType::Feat,
            test_scope("api"),
            test_description("change"),
            BreakingChange::No,
        );
        assert_ne!(commit1, commit2);
    }

    /// Test PartialEq trait - different descriptions
    #[test]
    fn conventional_commit_inequality_different_description() {
        let commit1 = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add feature"),
            BreakingChange::No,
        );
        let commit2 = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("fix bug"),
            BreakingChange::No,
        );
        assert_ne!(commit1, commit2);
    }

    /// Test Debug trait
    #[test]
    fn conventional_commit_has_debug() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add feature"),
            BreakingChange::No,
        );
        let debug_output = format!("{:?}", commit);
        assert!(debug_output.contains("ConventionalCommit"));
        assert!(debug_output.contains("Feat"));
    }

    /// Test real-world commit message example: feature with scope
    #[test]
    fn real_world_feature_with_scope() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("implement OAuth2 login flow"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "feat(auth): implement OAuth2 login flow");
    }

    /// Test real-world commit message example: bug fix without scope
    #[test]
    fn real_world_bugfix_without_scope() {
        let commit = test_commit(
            CommitType::Fix,
            Scope::empty(),
            test_description("prevent crash on empty input"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "fix: prevent crash on empty input");
    }

    /// Test real-world commit message example: documentation
    #[test]
    fn real_world_docs() {
        let commit = test_commit(
            CommitType::Docs,
            test_scope("README"),
            test_description("add installation instructions"),
            BreakingChange::No,
        );
        assert_eq!(
            commit.format(),
            "docs(README): add installation instructions"
        );
    }

    /// Test real-world commit message example: refactoring
    #[test]
    fn real_world_refactor() {
        let commit = test_commit(
            CommitType::Refactor,
            test_scope("core"),
            test_description("extract validation logic"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "refactor(core): extract validation logic");
    }

    /// Test real-world commit message example: CI change
    #[test]
    fn real_world_ci() {
        let commit = test_commit(
            CommitType::Ci,
            test_scope("github"),
            test_description("add release workflow"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "ci(github): add release workflow");
    }

    /// Test commit message with maximum description length (50 chars)
    #[test]
    fn format_with_max_length_description() {
        let long_desc = "a".repeat(50);
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            Description::parse(&long_desc).unwrap(),
            BreakingChange::No,
        );
        // Format should be "feat: " + 50 chars = 56 total chars
        let formatted = commit.format();
        assert!(formatted.starts_with("feat: "));
        assert_eq!(formatted.len(), 56); // "feat: " (6) + 50 = 56
    }

    /// Test commit message with scope containing all valid special chars
    #[test]
    fn format_with_complex_scope() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("my-scope_v2/feature"),
            test_description("add support"),
            BreakingChange::No,
        );
        assert_eq!(commit.format(), "feat(my-scope_v2/feature): add support");
    }

    /// Test FIRST_LINE_MAX_LENGTH constant is 72
    #[test]
    fn first_line_max_length_constant_is_72() {
        assert_eq!(ConventionalCommit::FIRST_LINE_MAX_LENGTH, 72);
    }

    /// Test first_line_len() calculates correctly without scope
    #[test]
    fn first_line_len_without_scope() {
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("add login"),
            BreakingChange::No,
        );
        // "feat: add login" = 4 + 2 + 9 = 15
        assert_eq!(commit.first_line_len(), 15);
    }

    /// Test first_line_len() calculates correctly with scope
    #[test]
    fn first_line_len_with_scope() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("add login"),
            BreakingChange::No,
        );
        // "feat(auth): add login" = 4 + 4 + 4 + 9 = 21
        assert_eq!(commit.first_line_len(), 21);
    }

    /// Test exactly 72 characters is accepted (boundary)
    #[test]
    fn exactly_72_characters_accepted() {
        // Build a commit that's exactly 72 chars:
        // feat(20chars): 44chars = 4 + 20 + 4 + 44 = 72
        let scope_20 = "a".repeat(20);
        let desc_44 = "b".repeat(44);
        let result = ConventionalCommit::new(
            CommitType::Feat,
            Scope::parse(&scope_20).unwrap(),
            Description::parse(&desc_44).unwrap(),
            BreakingChange::No,
            Body::default(),
            References::default(),
        );
        assert!(result.is_ok());
        let commit = result.unwrap();
        assert_eq!(commit.first_line_len(), 72);
    }

    /// Test 73 characters is rejected (boundary)
    #[test]
    fn seventy_three_characters_rejected() {
        // Build a commit that's 73 chars:
        // "refactor: " = 10 chars, so we need 63 chars of description for 73 total
        // But wait, we need to account for commit type and potentially scope
        // Let's use "feat" (4) + ": " (2) + 67 chars = 73
        // However Description MAX_LENGTH is 50, so we need a different approach
        // Use scope to pad: "refactor(scope): desc"
        // refactor = 8, (scope) = 7, : = 1, space = 1, desc needed for 73
        // 8 + 7 + 2 + desc = 73, so desc = 56, but max is 50
        // Let's use a longer type: "refactor" (8) + longer scope
        // Actually, let me use max scope (30) and appropriate description:
        // type(scope): desc
        // refactor(30chars): X = 8 + 30 + 4 + X = 73
        // X = 73 - 42 = 31
        let scope_30 = "a".repeat(30);
        let desc_31 = "b".repeat(31);
        let result = ConventionalCommit::new(
            CommitType::Refactor,
            Scope::parse(&scope_30).unwrap(),
            Description::parse(&desc_31).unwrap(),
            BreakingChange::No,
            Body::default(),
            References::default(),
        );
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            CommitMessageError::FirstLineTooLong {
                actual: 73,
                max: 72
            }
        );
    }

    /// Test that valid components can still exceed 72 chars when combined
    #[test]
    fn valid_components_can_exceed_limit() {
        // Use maximum valid scope (30 chars) and a 40-char description
        // refactor(30): 40 = 8 + 30 + 4 + 40 = 82 chars (exceeds 72)
        let scope_30 = "a".repeat(30);
        let desc_40 = "b".repeat(40);
        let result = ConventionalCommit::new(
            CommitType::Refactor,
            Scope::parse(&scope_30).unwrap(),
            Description::parse(&desc_40).unwrap(),
            BreakingChange::No,
            Body::default(),
            References::default(),
        );
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            CommitMessageError::FirstLineTooLong {
                actual: 82,
                max: 72
            }
        );
    }

    /// Test short commit without scope is accepted
    #[test]
    fn short_commit_without_scope_accepted() {
        let result = ConventionalCommit::new(
            CommitType::Fix,
            Scope::empty(),
            test_description("quick fix"),
            BreakingChange::No,
            Body::default(),
            References::default(),
        );
        assert!(result.is_ok());
    }

    /// Test short commit with scope is accepted
    #[test]
    fn short_commit_with_scope_accepted() {
        let result = ConventionalCommit::new(
            CommitType::Feat,
            test_scope("cli"),
            test_description("add feature"),
            BreakingChange::No,
            Body::default(),
            References::default(),
        );
        assert!(result.is_ok());
    }

    /// Test CommitMessageError::FirstLineTooLong displays correctly
    #[test]
    fn first_line_too_long_error_display() {
        let err = CommitMessageError::FirstLineTooLong {
            actual: 80,
            max: 72,
        };
        let msg = format!("{}", err);
        assert!(msg.contains("too long"));
        assert!(msg.contains("80"));
        assert!(msg.contains("72"));
    }

    /// Test new() returns Result type
    #[test]
    fn new_returns_result() {
        let result = ConventionalCommit::new(
            CommitType::Feat,
            Scope::empty(),
            test_description("test"),
            BreakingChange::No,
            Body::default(),
            References::default(),
        );
        // Just verify it's a Result by using is_ok()
        assert!(result.is_ok());
    }

    /// Test that all valid commits produce messages parseable by git-conventional (SC-002)
    ///
    /// This verifies that 100% of commit messages produced by this tool conform to
    /// the conventional commit specification.
    #[test]
    fn all_valid_commits_parse_with_git_conventional() {
        let cases: &[(&str, Option<&str>)] = &[
            ("add new feature", None),
            ("fix critical bug", Some("api")),
            ("update README", Some("docs")),
            ("remove unused code", Some("core")),
        ];

        for commit_type in CommitType::all() {
            for (desc_str, scope_str) in cases {
                let scope = match scope_str {
                    Some(s) => Scope::parse(*s).unwrap(),
                    None => Scope::empty(),
                };
                let desc = Description::parse(*desc_str).unwrap();
                let commit = ConventionalCommit::new(
                    *commit_type,
                    scope,
                    desc,
                    BreakingChange::No,
                    Body::default(),
                    References::default(),
                );
                // new() itself calls git_conventional::Commit::parse internally, so
                // if this is Ok, SC-002 is satisfied for this case.
                assert!(
                    commit.is_ok(),
                    "git-conventional rejected {:?}/{:?}/{:?}",
                    commit_type,
                    scope_str,
                    desc_str
                );
            }
        }
    }

    /// Test InvalidConventionalFormat error displays correctly
    #[test]
    fn invalid_conventional_format_error_display() {
        let err = CommitMessageError::InvalidConventionalFormat {
            reason: "missing type".to_string(),
        };
        let msg = format!("{}", err);
        assert!(msg.contains("git-conventional"));
        assert!(msg.contains("missing type"));
    }

    /// Breaking change without note and without scope: header gets '!', no footer
    #[test]
    fn format_breaking_change_no_note_no_scope() {
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("add login"),
            BreakingChange::Yes,
        );
        assert_eq!(commit.format(), "feat!: add login");
    }

    /// Breaking change without note and with scope: '!' goes after closing paren
    #[test]
    fn format_breaking_change_no_note_with_scope() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("add login"),
            BreakingChange::Yes,
        );
        assert_eq!(commit.format(), "feat(auth)!: add login");
    }

    /// Breaking change with note and without scope: footer is appended after a blank line
    #[test]
    fn format_breaking_change_with_note_no_scope() {
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("drop Node 6"),
            "Node 6 is no longer supported".into(),
        );
        assert_eq!(
            commit.format(),
            "feat!: drop Node 6\n\nBREAKING CHANGE: Node 6 is no longer supported",
        );
    }

    /// Breaking change with note and with scope: both '!' and footer are present
    #[test]
    fn format_breaking_change_with_note_and_scope() {
        let commit = test_commit(
            CommitType::Fix,
            test_scope("api"),
            test_description("drop Node 6"),
            "Node 6 is no longer supported".into(),
        );
        assert_eq!(
            commit.format(),
            "fix(api)!: drop Node 6\n\nBREAKING CHANGE: Node 6 is no longer supported",
        );
    }

    /// Display with breaking change delegates to format() (no scope, with note)
    #[test]
    fn display_breaking_change_with_note() {
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("drop Node 6"),
            "Node 6 is no longer supported".into(),
        );
        assert_eq!(
            format!("{}", commit),
            "feat!: drop Node 6\n\nBREAKING CHANGE: Node 6 is no longer supported",
        );
    }

    /// first_line_len() counts the '!' for a breaking change without scope
    ///
    /// "feat!: add login" = 4 + 1 + 2 + 9 = 16
    #[test]
    fn first_line_len_breaking_change_no_scope() {
        let commit = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("add login"),
            BreakingChange::Yes,
        );
        assert_eq!(commit.first_line_len(), 16);
    }

    /// first_line_len() counts the '!' for a breaking change with scope
    ///
    /// "feat(auth)!: add login" = 4 + 6 + 1 + 2 + 9 = 22
    #[test]
    fn first_line_len_breaking_change_with_scope() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("add login"),
            BreakingChange::Yes,
        );
        assert_eq!(commit.first_line_len(), 22);
    }

    /// The `!` counts toward the 72-character first-line limit
    ///
    /// The inputs below produce exactly 72 chars without a breaking change
    /// (covered by `exactly_72_characters_accepted`). With `!` they reach
    /// 73 and must be rejected.
    #[test]
    fn breaking_change_exclamation_counts_toward_line_limit() {
        let scope_20 = "a".repeat(20);
        let desc_44 = "b".repeat(44);
        let result = ConventionalCommit::new(
            CommitType::Feat,
            Scope::parse(&scope_20).unwrap(),
            Description::parse(&desc_44).unwrap(),
            BreakingChange::Yes,
            Body::default(),
            References::default(),
        );
        assert!(result.is_err());
        assert_eq!(
            result.unwrap_err(),
            CommitMessageError::FirstLineTooLong {
                actual: 73,
                max: 72
            },
        );
    }

    /// Breaking change footer does not count toward the 72-character first-line limit
    #[test]
    fn breaking_change_footer_does_not_count_toward_line_limit() {
        // First line is short; the note itself is long - should still be accepted.
        let long_note = "x".repeat(200);
        let result = ConventionalCommit::new(
            CommitType::Fix,
            Scope::empty(),
            test_description("quick fix"),
            long_note.into(),
            Body::default(),
            References::default(),
        );
        assert!(result.is_ok());
    }

    /// format_preview() static method produces the same result as format() for identical inputs
    #[test]
    fn format_preview_matches_format() {
        let commit = test_commit(
            CommitType::Feat,
            test_scope("auth"),
            test_description("add login"),
            BreakingChange::No,
        );
        let preview = ConventionalCommit::format_preview(
            commit.commit_type,
            &commit.scope,
            &commit.description,
            &BreakingChange::No,
            &Body::default(),
            &References::default(),
        );
        assert_eq!(preview, commit.format());
    }

    /// format_preview() with a breaking-change note produces the full multi-line message
    #[test]
    fn format_preview_breaking_change_with_note() {
        let preview = ConventionalCommit::format_preview(
            CommitType::Feat,
            &Scope::empty(),
            &test_description("drop legacy API"),
            &"removes legacy endpoint".into(),
            &Body::default(),
            &References::default(),
        );
        assert_eq!(
            preview,
            "feat!: drop legacy API\n\nBREAKING CHANGE: removes legacy endpoint"
        );
    }

    /// format_preview() with scope and breaking-change note
    #[test]
    fn format_preview_breaking_change_with_scope_and_note() {
        let preview = ConventionalCommit::format_preview(
            CommitType::Fix,
            &test_scope("api"),
            &test_description("drop Node 6"),
            &"Node 6 is no longer supported".into(),
            &Body::default(),
            &References::default(),
        );
        assert_eq!(
            preview,
            "fix(api)!: drop Node 6\n\nBREAKING CHANGE: Node 6 is no longer supported"
        );
    }

    /// Breaking-change footer is separated from the header by exactly one blank line
    #[test]
    fn format_breaking_change_footer_separator() {
        let commit = test_commit(
            CommitType::Fix,
            Scope::empty(),
            test_description("drop old API"),
            "old API removed".into(),
        );
        let formatted = commit.format();
        let parts: Vec<&str> = formatted.splitn(2, "\n\n").collect();
        assert_eq!(
            parts.len(),
            2,
            "expected header and footer separated by \\n\\n"
        );
        assert_eq!(parts[0], "fix!: drop old API");
        assert_eq!(parts[1], "BREAKING CHANGE: old API removed");
    }

    /// format() output has no leading or trailing whitespace for any variant
    #[test]
    fn format_has_no_surrounding_whitespace() {
        let no_bc = test_commit(
            CommitType::Feat,
            Scope::empty(),
            test_description("add feature"),
            BreakingChange::No,
        );
        let f = no_bc.format();
        assert_eq!(
            f,
            f.trim(),
            "format() must not have surrounding whitespace (no breaking change)"
        );

        let with_note = test_commit(
            CommitType::Fix,
            Scope::empty(),
            test_description("fix bug"),
            "important migration required".into(),
        );
        let f2 = with_note.format();
        assert_eq!(
            f2,
            f2.trim(),
            "format() must not have surrounding whitespace (with note)"
        );
    }

    /// All commit types format correctly with breaking change and no note
    #[test]
    fn all_commit_types_format_with_breaking_change_no_note() {
        let desc = test_description("test change");

        let expected_formats = [
            (CommitType::Feat, "feat!: test change"),
            (CommitType::Fix, "fix!: test change"),
            (CommitType::Docs, "docs!: test change"),
            (CommitType::Style, "style!: test change"),
            (CommitType::Refactor, "refactor!: test change"),
            (CommitType::Perf, "perf!: test change"),
            (CommitType::Test, "test!: test change"),
            (CommitType::Build, "build!: test change"),
            (CommitType::Ci, "ci!: test change"),
            (CommitType::Chore, "chore!: test change"),
            (CommitType::Revert, "revert!: test change"),
        ];

        for (commit_type, expected) in expected_formats {
            let commit = test_commit(
                commit_type,
                Scope::empty(),
                desc.clone(),
                BreakingChange::Yes,
            );
            assert_eq!(
                commit.format(),
                expected,
                "Format should be correct for {:?} with breaking change",
                commit_type
            );
        }
    }

    // --- Body tests (these will fail until format_preview() is updated to use body) ---

    /// format() includes the body between the header and an empty footer
    ///
    /// Case: body = Some, footer = "" → "type: desc\n\ncontent"
    #[test]
    fn format_with_body_no_breaking_change() {
        let commit = ConventionalCommit::new(
            CommitType::Feat,
            Scope::empty(),
            test_description("add feature"),
            BreakingChange::No,
            Body::from("This explains the change."),
            References::default(),
        )
        .unwrap();
        assert_eq!(
            commit.format(),
            "feat: add feature\n\nThis explains the change."
        );
    }

    /// format() includes the body when a scope is also present
    #[test]
    fn format_with_body_and_scope() {
        let commit = ConventionalCommit::new(
            CommitType::Fix,
            test_scope("api"),
            test_description("handle null response"),
            BreakingChange::No,
            Body::from("Null responses were previously unhandled."),
            References::default(),
        )
        .unwrap();
        assert_eq!(
            commit.format(),
            "fix(api): handle null response\n\nNull responses were previously unhandled."
        );
    }

    /// format() preserves internal newlines in a multi-paragraph body
    #[test]
    fn format_with_multiline_body() {
        let commit = ConventionalCommit::new(
            CommitType::Docs,
            Scope::empty(),
            test_description("update README"),
            BreakingChange::No,
            Body::from("First paragraph.\n\nSecond paragraph."),
            References::default(),
        )
        .unwrap();
        assert_eq!(
            commit.format(),
            "docs: update README\n\nFirst paragraph.\n\nSecond paragraph."
        );
    }

    /// format() places the body between the header and the breaking-change footer
    ///
    /// Case: body = Some, footer = Some → "type: desc\n\nbody\n\nBREAKING CHANGE: note"
    #[test]
    fn format_with_body_and_breaking_change_note() {
        let commit = ConventionalCommit::new(
            CommitType::Feat,
            Scope::empty(),
            test_description("drop legacy API"),
            "removes legacy endpoint".into(),
            Body::from("The endpoint was deprecated in v2."),
            References::default(),
        )
        .unwrap();
        assert_eq!(
            commit.format(),
            "feat!: drop legacy API\n\nThe endpoint was deprecated in v2.\n\nBREAKING CHANGE: removes legacy endpoint"
        );
    }

    /// format_preview() includes the body in the output
    #[test]
    fn format_preview_with_body() {
        let preview = ConventionalCommit::format_preview(
            CommitType::Feat,
            &Scope::empty(),
            &test_description("add feature"),
            &BreakingChange::No,
            &Body::from("This explains the change."),
            &References::default(),
        );
        assert_eq!(preview, "feat: add feature\n\nThis explains the change.");
    }

    /// format_preview() with body and breaking-change note produces the full message
    ///
    /// Case: body = Some, footer = Some → "type: desc\n\nbody\n\nBREAKING CHANGE: note"
    #[test]
    fn format_preview_with_body_and_breaking_change() {
        let preview = ConventionalCommit::format_preview(
            CommitType::Fix,
            &Scope::empty(),
            &test_description("drop old API"),
            &"old API removed".into(),
            &Body::from("Migration guide: see CHANGELOG."),
            &References::default(),
        );
        assert_eq!(
            preview,
            "fix!: drop old API\n\nMigration guide: see CHANGELOG.\n\nBREAKING CHANGE: old API removed"
        );
    }
}