-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathconfig_test.go
More file actions
1371 lines (1192 loc) · 38.5 KB
/
Copy pathconfig_test.go
File metadata and controls
1371 lines (1192 loc) · 38.5 KB
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
package config
import (
"os"
"path/filepath"
"testing"
"github.com/jeduden/mdsmith/internal/rule"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gopkg.in/yaml.v3"
// Import all rule packages so their init() functions register rules.
_ "github.com/jeduden/mdsmith/internal/rules/blanklinearoundfencedcode"
_ "github.com/jeduden/mdsmith/internal/rules/blanklinearoundheadings"
_ "github.com/jeduden/mdsmith/internal/rules/blanklinearoundlists"
_ "github.com/jeduden/mdsmith/internal/rules/catalog"
_ "github.com/jeduden/mdsmith/internal/rules/concisenessscoring"
_ "github.com/jeduden/mdsmith/internal/rules/crossfilereferenceintegrity"
_ "github.com/jeduden/mdsmith/internal/rules/directorystructure"
_ "github.com/jeduden/mdsmith/internal/rules/emptysectionbody"
_ "github.com/jeduden/mdsmith/internal/rules/fencedcodelanguage"
_ "github.com/jeduden/mdsmith/internal/rules/fencedcodestyle"
_ "github.com/jeduden/mdsmith/internal/rules/firstlineheading"
_ "github.com/jeduden/mdsmith/internal/rules/headingincrement"
_ "github.com/jeduden/mdsmith/internal/rules/headingstyle"
_ "github.com/jeduden/mdsmith/internal/rules/include"
_ "github.com/jeduden/mdsmith/internal/rules/linelength"
_ "github.com/jeduden/mdsmith/internal/rules/listindent"
_ "github.com/jeduden/mdsmith/internal/rules/maxfilelength"
_ "github.com/jeduden/mdsmith/internal/rules/maxsectionlength"
_ "github.com/jeduden/mdsmith/internal/rules/nobareurls"
_ "github.com/jeduden/mdsmith/internal/rules/noduplicateheadings"
_ "github.com/jeduden/mdsmith/internal/rules/noemphasisasheading"
_ "github.com/jeduden/mdsmith/internal/rules/nohardtabs"
_ "github.com/jeduden/mdsmith/internal/rules/nomultipleblanks"
_ "github.com/jeduden/mdsmith/internal/rules/notrailingpunctuation"
_ "github.com/jeduden/mdsmith/internal/rules/notrailingspaces"
_ "github.com/jeduden/mdsmith/internal/rules/paragraphreadability"
_ "github.com/jeduden/mdsmith/internal/rules/paragraphstructure"
_ "github.com/jeduden/mdsmith/internal/rules/requiredstructure"
_ "github.com/jeduden/mdsmith/internal/rules/singletrailingnewline"
_ "github.com/jeduden/mdsmith/internal/rules/tableformat"
_ "github.com/jeduden/mdsmith/internal/rules/tablereadability"
_ "github.com/jeduden/mdsmith/internal/rules/tokenbudget"
)
func expectedDefaultEnabled(r rule.Rule) bool {
d, ok := r.(rule.Defaultable)
if !ok {
return true
}
return d.EnabledByDefault()
}
// --- YAML parsing tests ---
func TestParseValidYAML(t *testing.T) {
cfg := loadValidYAMLFixture(t)
t.Run("rules", func(t *testing.T) {
require.Len(t, cfg.Rules, 3, "expected 3 rules, got %d", len(cfg.Rules))
assert.True(t, cfg.Rules["line-length"].Enabled, "line-length should be enabled")
assert.False(t, cfg.Rules["heading-style"].Enabled, "heading-style should be disabled")
assert.True(t, cfg.Rules["no-multiple-blanks"].Enabled, "no-multiple-blanks should be enabled")
if cfg.Rules["no-multiple-blanks"].Settings["max"] != 2 {
t.Errorf("no-multiple-blanks max: expected 2, got %v", cfg.Rules["no-multiple-blanks"].Settings["max"])
}
})
t.Run("ignore", func(t *testing.T) {
require.Len(t, cfg.Ignore, 2, "expected 2 ignore patterns, got %d", len(cfg.Ignore))
if cfg.Ignore[0] != "vendor/**" {
t.Errorf("expected vendor/**, got %s", cfg.Ignore[0])
}
})
t.Run("overrides", func(t *testing.T) {
require.Len(t, cfg.Overrides, 2, "expected 2 overrides, got %d", len(cfg.Overrides))
if cfg.Overrides[0].Files[0] != "CHANGELOG.md" {
t.Errorf("expected CHANGELOG.md, got %s", cfg.Overrides[0].Files[0])
}
assert.False(t, cfg.Overrides[0].Rules["no-duplicate-headings"].Enabled,
"no-duplicate-headings should be disabled in override")
assert.True(t, cfg.Overrides[1].Rules["line-length"].Enabled, "line-length should be enabled in override")
if cfg.Overrides[1].Rules["line-length"].Settings["max"] != 120 {
t.Errorf("line-length max in override: expected 120, got %v",
cfg.Overrides[1].Rules["line-length"].Settings["max"])
}
})
}
func loadValidYAMLFixture(t *testing.T) *Config {
t.Helper()
yml := `
rules:
line-length: true
heading-style: false
no-multiple-blanks:
max: 2
ignore:
- "vendor/**"
- "node_modules/**"
overrides:
- files:
- "CHANGELOG.md"
rules:
no-duplicate-headings: false
- files:
- "docs/**"
rules:
line-length:
max: 120
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
return cfg
}
func TestRuleCfgBoolFalse(t *testing.T) {
yml := `
rules:
line-length: false
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
rc := cfg.Rules["line-length"]
assert.False(t, rc.Enabled, "expected Enabled=false")
assert.Nil(t, rc.Settings, "expected Settings=nil")
}
func TestRuleCfgBoolTrue(t *testing.T) {
yml := `
rules:
line-length: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
rc := cfg.Rules["line-length"]
assert.True(t, rc.Enabled, "expected Enabled=true")
assert.Nil(t, rc.Settings, "expected Settings=nil")
}
func TestRuleCfgObject(t *testing.T) {
yml := `
rules:
line-length:
max: 120
strict: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
rc := cfg.Rules["line-length"]
assert.True(t, rc.Enabled, "expected Enabled=true")
require.NotNil(t, rc.Settings, "expected Settings to be non-nil")
if rc.Settings["max"] != 120 {
t.Errorf("expected max=120, got %v", rc.Settings["max"])
}
if rc.Settings["strict"] != true {
t.Errorf("expected strict=true, got %v", rc.Settings["strict"])
}
}
func TestInvalidYAMLReturnsError(t *testing.T) {
yml := `
rules:
line-length: [[[invalid
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
_, err := Load(cfgPath)
require.Error(t, err, "expected error for invalid YAML")
}
func TestLoadNonexistentFile(t *testing.T) {
_, err := Load("/nonexistent/path/.mdsmith.yml")
require.Error(t, err, "expected error for nonexistent file")
}
// --- Discovery tests ---
func TestDiscoverFindsInCurrentDir(t *testing.T) {
dir := t.TempDir()
cfgPath := filepath.Join(dir, configFileName)
if err := os.WriteFile(cfgPath, []byte("rules: {}"), 0o644); err != nil {
t.Fatal(err)
}
found, err := Discover(dir)
require.NoError(t, err, "Discover returned error: %v", err)
assert.Equal(t, cfgPath, found, "expected %s, got %s", cfgPath, found)
}
func TestDiscoverFindsInParentDir(t *testing.T) {
parent := t.TempDir()
child := filepath.Join(parent, "subdir")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
cfgPath := filepath.Join(parent, configFileName)
if err := os.WriteFile(cfgPath, []byte("rules: {}"), 0o644); err != nil {
t.Fatal(err)
}
found, err := Discover(child)
require.NoError(t, err, "Discover returned error: %v", err)
assert.Equal(t, cfgPath, found, "expected %s, got %s", cfgPath, found)
}
func TestDiscoverStopsAtGitBoundary(t *testing.T) {
// Setup: grandparent has config, parent has .git, child is startDir.
// Discover should NOT find the config above .git.
grandparent := t.TempDir()
parent := filepath.Join(grandparent, "repo")
child := filepath.Join(parent, "src")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
// Put .git in parent (the repo root)
gitDir := filepath.Join(parent, ".git")
if err := os.MkdirAll(gitDir, 0o755); err != nil {
t.Fatal(err)
}
// Put config in grandparent (above .git)
cfgPath := filepath.Join(grandparent, configFileName)
if err := os.WriteFile(cfgPath, []byte("rules: {}"), 0o644); err != nil {
t.Fatal(err)
}
found, err := Discover(child)
require.NoError(t, err, "Discover returned error: %v", err)
assert.Equal(t, "", found, "expected empty string (stopped at .git), got %s", found)
}
func TestDiscoverStopsAtGitBoundaryWithConfigInRepo(t *testing.T) {
// Config in same dir as .git should be found.
repoRoot := t.TempDir()
child := filepath.Join(repoRoot, "src")
if err := os.MkdirAll(child, 0o755); err != nil {
t.Fatal(err)
}
gitDir := filepath.Join(repoRoot, ".git")
if err := os.MkdirAll(gitDir, 0o755); err != nil {
t.Fatal(err)
}
cfgPath := filepath.Join(repoRoot, configFileName)
if err := os.WriteFile(cfgPath, []byte("rules: {}"), 0o644); err != nil {
t.Fatal(err)
}
found, err := Discover(child)
require.NoError(t, err, "Discover returned error: %v", err)
assert.Equal(t, cfgPath, found, "expected %s, got %s", cfgPath, found)
}
func TestDiscoverReturnsEmptyWhenNotFound(t *testing.T) {
dir := t.TempDir()
// Put a .git so we don't walk out of the tmp dir
gitDir := filepath.Join(dir, ".git")
if err := os.MkdirAll(gitDir, 0o755); err != nil {
t.Fatal(err)
}
found, err := Discover(dir)
require.NoError(t, err, "Discover returned error: %v", err)
assert.Equal(t, "", found, "expected empty string, got %s", found)
}
// --- Defaults tests ---
func TestDefaultsRuleEnablement(t *testing.T) {
cfg := Defaults()
all := rule.All()
require.Len(t, cfg.Rules, len(all), "expected %d rules, got %d", len(all), len(cfg.Rules))
for _, r := range all {
name := r.Name()
rc, ok := cfg.Rules[name]
if !ok {
t.Errorf("rule %q not found in defaults", name)
continue
}
wantEnabled := expectedDefaultEnabled(r)
if rc.Enabled != wantEnabled {
t.Errorf(
"rule %q enabled=%v, want %v",
name, rc.Enabled, wantEnabled,
)
}
assert.Nil(t, rc.Settings, "rule %q should have nil settings by default", name)
}
}
// --- Merge tests ---
func TestMergeNilLoaded(t *testing.T) {
defaults := Defaults()
merged := Merge(defaults, nil)
require.Len(t, merged.Rules, len(rule.All()), "expected %d rules, got %d", len(rule.All()), len(merged.Rules))
for _, r := range rule.All() {
name := r.Name()
rc := merged.Rules[name]
wantEnabled := expectedDefaultEnabled(r)
if rc.Enabled != wantEnabled {
t.Errorf(
"rule %q enabled=%v, want %v",
name, rc.Enabled, wantEnabled,
)
}
}
}
func TestMergeDisabledRule(t *testing.T) {
defaults := Defaults()
loaded := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: false},
},
}
merged := Merge(defaults, loaded)
assert.False(t, merged.Rules["line-length"].Enabled, "line-length should be disabled after merge")
// Other rules should still be enabled
assert.True(t, merged.Rules["heading-style"].Enabled, "heading-style should remain enabled")
assert.True(t, merged.Rules["no-trailing-spaces"].Enabled, "no-trailing-spaces should remain enabled")
}
func TestMergeCustomSettings(t *testing.T) {
defaults := Defaults()
loaded := &Config{
Rules: map[string]RuleCfg{
"line-length": {
Enabled: true,
Settings: map[string]any{"max": 120},
},
},
}
merged := Merge(defaults, loaded)
rc := merged.Rules["line-length"]
assert.True(t, rc.Enabled, "line-length should be enabled")
if rc.Settings["max"] != 120 {
t.Errorf("expected max=120, got %v", rc.Settings["max"])
}
}
func TestMergePreservesIgnoreAndOverrides(t *testing.T) {
defaults := Defaults()
loaded := &Config{
Ignore: []string{"vendor/**"},
Overrides: []Override{
{
Files: []string{"CHANGELOG.md"},
Rules: map[string]RuleCfg{
"no-duplicate-headings": {Enabled: false},
},
},
},
}
merged := Merge(defaults, loaded)
if len(merged.Ignore) != 1 || merged.Ignore[0] != "vendor/**" {
t.Errorf("ignore not preserved: %v", merged.Ignore)
}
require.Len(t, merged.Overrides, 1, "expected 1 override, got %d", len(merged.Overrides))
}
// --- Effective tests ---
func TestEffectiveWithoutOverrides(t *testing.T) {
cfg := Defaults()
eff := Effective(cfg, "README.md")
require.Len(t, eff, len(rule.All()), "expected %d rules, got %d", len(rule.All()), len(eff))
for _, r := range rule.All() {
name := r.Name()
rc := eff[name]
wantEnabled := expectedDefaultEnabled(r)
if rc.Enabled != wantEnabled {
t.Errorf(
"rule %q enabled=%v, want %v",
name, rc.Enabled, wantEnabled,
)
}
}
}
func TestEffectiveOverrideAppliesPerFile(t *testing.T) {
cfg := Defaults()
cfg.Overrides = []Override{
{
Files: []string{"CHANGELOG.md"},
Rules: map[string]RuleCfg{
"no-duplicate-headings": {Enabled: false},
},
},
}
// CHANGELOG.md should have no-duplicate-headings disabled
eff := Effective(cfg, "CHANGELOG.md")
assert.False(t, eff["no-duplicate-headings"].Enabled, "no-duplicate-headings should be disabled for CHANGELOG.md")
assert.True(t, eff["line-length"].Enabled, "line-length should remain enabled for CHANGELOG.md")
// README.md should NOT be affected
eff2 := Effective(cfg, "README.md")
assert.True(t, eff2["no-duplicate-headings"].Enabled, "no-duplicate-headings should remain enabled for README.md")
}
func TestEffectiveLaterOverridesWin(t *testing.T) {
cfg := Defaults()
cfg.Overrides = []Override{
{
Files: []string{"docs/**"},
Rules: map[string]RuleCfg{
"line-length": {
Enabled: true,
Settings: map[string]any{"max": 100},
},
},
},
{
Files: []string{"docs/api/**"},
Rules: map[string]RuleCfg{
"line-length": {
Enabled: true,
Settings: map[string]any{"max": 200},
},
},
},
}
// docs/api/foo.md matches both overrides; second should win
eff := Effective(cfg, "docs/api/foo.md")
rc := eff["line-length"]
assert.True(t, rc.Enabled, "line-length should be enabled")
if rc.Settings["max"] != 200 {
t.Errorf("expected max=200 (later override wins), got %v", rc.Settings["max"])
}
}
func TestFrontMatterParsing(t *testing.T) {
yml := `
front-matter: true
rules:
line-length: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
require.NotNil(t, cfg.FrontMatter, "expected FrontMatter to be non-nil")
assert.True(t, *cfg.FrontMatter, "expected FrontMatter to be true")
}
func TestFrontMatterFalse(t *testing.T) {
yml := `
front-matter: false
rules:
line-length: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
require.NotNil(t, cfg.FrontMatter, "expected FrontMatter to be non-nil")
assert.False(t, *cfg.FrontMatter, "expected FrontMatter to be false")
}
func TestFrontMatterOmitted(t *testing.T) {
yml := `
rules:
line-length: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
assert.Nil(t, cfg.FrontMatter, "expected FrontMatter nil when omitted")
}
func TestMergeFrontMatter(t *testing.T) {
defaults := Defaults()
// Loaded config sets front-matter: false
fm := false
loaded := &Config{
FrontMatter: &fm,
}
merged := Merge(defaults, loaded)
if merged.FrontMatter == nil || *merged.FrontMatter {
t.Error("expected FrontMatter=false after merge")
}
// Loaded config omits front-matter — defaults should apply
loaded2 := &Config{}
merged2 := Merge(defaults, loaded2)
assert.Nil(t, merged2.FrontMatter, "expected FrontMatter=nil when not set in loaded config")
}
// TestEffectiveOverrideMatchesBasename verifies that an override pattern
// without path separators (e.g. "slides.md") matches files in subdirectories
// via basename matching, consistent with how ignore patterns work (issue #40).
func TestEffectiveOverrideMatchesBasename(t *testing.T) {
cfg := Defaults()
cfg.Overrides = []Override{
{
Files: []string{"slides.md"},
Rules: map[string]RuleCfg{
"first-line-heading": {Enabled: false},
},
},
}
// slides.md at root should match.
eff := Effective(cfg, "slides.md")
assert.False(t, eff["first-line-heading"].Enabled, "first-line-heading should be disabled for slides.md")
// docs/slides.md should also match via basename (issue #40).
eff2 := Effective(cfg, "docs/slides.md")
assert.False(t, eff2["first-line-heading"].Enabled,
"first-line-heading should be disabled for docs/slides.md via basename match")
// other.md should NOT match.
eff3 := Effective(cfg, "other.md")
assert.True(t, eff3["first-line-heading"].Enabled, "first-line-heading should remain enabled for other.md")
}
func TestEffectiveGlobPatternMatch(t *testing.T) {
cfg := Defaults()
cfg.Overrides = []Override{
{
Files: []string{"vendor/**"},
Rules: map[string]RuleCfg{
"line-length": {Enabled: false},
},
},
}
eff := Effective(cfg, "vendor/foo/bar.md")
assert.False(t, eff["line-length"].Enabled, "line-length should be disabled for vendor/foo/bar.md")
// Non-matching file
eff2 := Effective(cfg, "src/main.md")
assert.True(t, eff2["line-length"].Enabled, "line-length should remain enabled for src/main.md")
}
// --- MarshalYAML tests ---
func TestMarshalYAML_DisabledRule(t *testing.T) {
rc := RuleCfg{Enabled: false}
data, err := yaml.Marshal(rc)
require.NoError(t, err, "marshal error: %v", err)
if string(data) != "false\n" {
t.Errorf("expected 'false\\n', got %q", string(data))
}
}
func TestMarshalYAML_EnabledNoSettings(t *testing.T) {
rc := RuleCfg{Enabled: true}
data, err := yaml.Marshal(rc)
require.NoError(t, err, "marshal error: %v", err)
if string(data) != "true\n" {
t.Errorf("expected 'true\\n', got %q", string(data))
}
}
func TestMarshalYAML_EnabledWithSettings(t *testing.T) {
rc := RuleCfg{Enabled: true, Settings: map[string]any{"max": 80}}
data, err := yaml.Marshal(rc)
require.NoError(t, err, "marshal error: %v", err)
// Should serialize as the map, not as "true".
var m map[string]any
if err := yaml.Unmarshal(data, &m); err != nil {
t.Fatalf("unmarshal error: %v", err)
}
if m["max"] != 80 {
t.Errorf("expected max=80, got %v", m["max"])
}
}
func TestMarshalYAML_RoundTrip(t *testing.T) {
original := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: true, Settings: map[string]any{"max": 120}},
"heading-style": {Enabled: false},
"no-hard-tabs": {Enabled: true},
},
}
data, err := yaml.Marshal(original)
require.NoError(t, err, "marshal error: %v", err)
var parsed Config
if err := yaml.Unmarshal(data, &parsed); err != nil {
t.Fatalf("unmarshal error: %v", err)
}
// line-length should be enabled with max=120.
rc := parsed.Rules["line-length"]
assert.True(t, rc.Enabled, "line-length should be enabled after round-trip")
if rc.Settings["max"] != 120 {
t.Errorf("expected max=120, got %v", rc.Settings["max"])
}
// heading-style should be disabled.
assert.False(t, parsed.Rules["heading-style"].Enabled, "heading-style should be disabled after round-trip")
// no-hard-tabs should be enabled with no settings.
rc2 := parsed.Rules["no-hard-tabs"]
assert.True(t, rc2.Enabled, "no-hard-tabs should be enabled after round-trip")
assert.Nil(t, rc2.Settings, "no-hard-tabs should have nil settings, got %v", rc2.Settings)
}
// --- DumpDefaults tests ---
func TestDumpDefaults_AllRulesPresent(t *testing.T) {
cfg := DumpDefaults()
all := rule.All()
require.Len(t, cfg.Rules, len(all), "expected %d rules, got %d", len(all), len(cfg.Rules))
for _, r := range all {
rc, ok := cfg.Rules[r.Name()]
if !ok {
t.Errorf("rule %q not found in DumpDefaults", r.Name())
continue
}
wantEnabled := expectedDefaultEnabled(r)
if rc.Enabled != wantEnabled {
t.Errorf(
"rule %q enabled=%v, want %v",
r.Name(), rc.Enabled, wantEnabled,
)
}
}
}
func TestDumpDefaults_ConfigurableRulesHaveSettings(t *testing.T) {
cfg := DumpDefaults()
// These rules should have settings.
configurableRules := []string{
"line-length",
"heading-style",
"first-line-heading",
"no-multiple-blanks",
"fenced-code-style",
"list-indent",
"cross-file-reference-integrity",
"token-budget",
}
for _, name := range configurableRules {
rc, ok := cfg.Rules[name]
if !ok {
t.Errorf("rule %q not found", name)
continue
}
assert.NotNil(t, rc.Settings, "rule %q should have non-nil settings", name)
}
}
func TestDumpDefaults_DisabledConfigurableRulesHaveNoSettings(t *testing.T) {
cfg := DumpDefaults()
rc, ok := cfg.Rules["conciseness-scoring"]
require.True(t, ok, "rule conciseness-scoring not found")
assert.False(t, rc.Enabled, "conciseness-scoring should be disabled by default")
if rc.Settings != nil {
t.Errorf(
"conciseness-scoring should have nil settings when disabled, got %v",
rc.Settings,
)
}
}
func TestDumpDefaults_NonConfigurableRulesHaveNoSettings(t *testing.T) {
cfg := DumpDefaults()
// These rules should NOT have settings.
nonConfigurableRules := []string{
"heading-increment",
"no-duplicate-headings",
"no-trailing-spaces",
"no-hard-tabs",
"single-trailing-newline",
"fenced-code-language",
"no-bare-urls",
"blank-line-around-headings",
"blank-line-around-lists",
"blank-line-around-fenced-code",
"no-trailing-punctuation-in-heading",
"no-emphasis-as-heading",
"catalog",
}
for _, name := range nonConfigurableRules {
rc, ok := cfg.Rules[name]
if !ok {
t.Errorf("rule %q not found", name)
continue
}
assert.Nil(t, rc.Settings, "rule %q should have nil settings, got %v", name, rc.Settings)
}
}
func TestDumpDefaults_LineLengthSettings(t *testing.T) {
cfg := DumpDefaults()
rc := cfg.Rules["line-length"]
if rc.Settings["max"] != 80 {
t.Errorf("expected line-length max=80, got %v", rc.Settings["max"])
}
exclude, ok := rc.Settings["exclude"].([]string)
require.True(t, ok, "expected exclude to be []string, got %T", rc.Settings["exclude"])
assert.Len(t, exclude, 3, "expected 3 exclude items, got %d", len(exclude))
}
func TestDumpDefaults_MarshalRoundTrip(t *testing.T) {
cfg := DumpDefaults()
data, err := yaml.Marshal(cfg)
require.NoError(t, err, "marshal error: %v", err)
var parsed Config
if err := yaml.Unmarshal(data, &parsed); err != nil {
t.Fatalf("unmarshal error: %v", err)
}
// Check that line-length round-trips with settings.
rc := parsed.Rules["line-length"]
assert.True(t, rc.Enabled, "line-length should be enabled after round-trip")
if rc.Settings["max"] != 80 {
t.Errorf("expected max=80 after round-trip, got %v", rc.Settings["max"])
}
}
// --- Categories tests ---
func TestLoadCategoriesFromYAML(t *testing.T) {
yml := `
categories:
heading: false
whitespace: true
code: false
rules:
line-length: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
require.Len(t, cfg.Categories, 3, "expected 3 categories, got %d", len(cfg.Categories))
if cfg.Categories["heading"] != false {
t.Error("heading should be false")
}
if cfg.Categories["whitespace"] != true {
t.Error("whitespace should be true")
}
if cfg.Categories["code"] != false {
t.Error("code should be false")
}
}
func TestCategoriesOmittedDefaultToTrue(t *testing.T) {
yml := `
rules:
line-length: true
`
dir := t.TempDir()
cfgPath := filepath.Join(dir, ".mdsmith.yml")
if err := os.WriteFile(cfgPath, []byte(yml), 0o644); err != nil {
t.Fatal(err)
}
cfg, err := Load(cfgPath)
require.NoError(t, err, "Load returned error: %v", err)
assert.Nil(t, cfg.Categories, "expected nil categories when omitted, got %v", cfg.Categories)
// EffectiveCategories should default all to true.
cats := EffectiveCategories(cfg, "README.md")
for _, name := range ValidCategories {
assert.True(t, cats[name], "category %q should default to true", name)
}
}
func TestMergeCategories(t *testing.T) {
defaults := Defaults()
loaded := &Config{
Categories: map[string]bool{
"heading": false,
},
}
merged := Merge(defaults, loaded)
require.NotNil(t, merged.Categories, "expected categories to be non-nil after merge")
if merged.Categories["heading"] != false {
t.Error("heading should be false after merge")
}
}
func TestMergeCategoriesNilLoaded(t *testing.T) {
defaults := Defaults()
merged := Merge(defaults, nil)
// Defaults have nil categories.
assert.Nil(t, merged.Categories, "expected nil categories when merging with nil loaded, got %v", merged.Categories)
}
func TestMergeCategoriesBothSet(t *testing.T) {
defaults := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: true},
},
Categories: map[string]bool{
"heading": true,
"code": true,
},
}
loaded := &Config{
Categories: map[string]bool{
"heading": false,
"list": false,
},
}
merged := Merge(defaults, loaded)
if merged.Categories["heading"] != false {
t.Error("heading should be false (overridden by loaded)")
}
if merged.Categories["code"] != true {
t.Error("code should remain true from defaults")
}
if merged.Categories["list"] != false {
t.Error("list should be false from loaded")
}
}
func TestMergeTracksExplicitRules(t *testing.T) {
defaults := Defaults()
loaded := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: true},
"heading-style": {Enabled: false},
},
}
merged := Merge(defaults, loaded)
assert.True(t, merged.ExplicitRules["line-length"], "line-length should be explicit")
assert.True(t, merged.ExplicitRules["heading-style"], "heading-style should be explicit")
assert.False(t, merged.ExplicitRules["no-hard-tabs"], "no-hard-tabs should not be explicit (not in loaded config)")
}
func TestEffectiveCategoriesTopLevel(t *testing.T) {
cfg := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: true},
},
Categories: map[string]bool{
"heading": false,
},
}
cats := EffectiveCategories(cfg, "README.md")
if cats["heading"] != false {
t.Error("heading should be false")
}
// Other categories should default to true.
if cats["whitespace"] != true {
t.Error("whitespace should default to true")
}
if cats["code"] != true {
t.Error("code should default to true")
}
}
func TestEffectiveCategoriesOverride(t *testing.T) {
cfg := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: true},
},
Categories: map[string]bool{
"heading": true,
},
Overrides: []Override{
{
Files: []string{"CHANGELOG.md"},
Categories: map[string]bool{
"heading": false,
},
},
},
}
// CHANGELOG.md should have heading disabled via override.
cats := EffectiveCategories(cfg, "CHANGELOG.md")
if cats["heading"] != false {
t.Error("heading should be false for CHANGELOG.md")
}
// README.md should keep heading enabled.
cats2 := EffectiveCategories(cfg, "README.md")
if cats2["heading"] != true {
t.Error("heading should be true for README.md")
}
}
func TestEffectiveExplicitRulesFromOverrides(t *testing.T) {
cfg := &Config{
Rules: map[string]RuleCfg{
"line-length": {Enabled: true},
},
ExplicitRules: map[string]bool{
"line-length": true,
},
Overrides: []Override{
{
Files: []string{"docs/**"},
Rules: map[string]RuleCfg{
"heading-style": {Enabled: true},
},
},
},
}
explicit := EffectiveExplicitRules(cfg, "docs/guide.md")
assert.True(t, explicit["line-length"], "line-length should be explicit (from top-level)")
assert.True(t, explicit["heading-style"], "heading-style should be explicit (from matching override)")
// Non-matching file should not get override rules.
explicit2 := EffectiveExplicitRules(cfg, "README.md")
assert.False(t, explicit2["heading-style"], "heading-style should not be explicit for README.md")
}
func TestApplyCategoriesDisablesRulesInCategory(t *testing.T) {
rules := map[string]RuleCfg{
"heading-style": {Enabled: true},
"heading-increment": {Enabled: true},
"line-length": {Enabled: true},
}
categories := map[string]bool{
"heading": false,
"line": true,
}
ruleCategory := func(name string) string {