-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrule.go
More file actions
1760 lines (1642 loc) · 60.4 KB
/
Copy pathrule.go
File metadata and controls
1760 lines (1642 loc) · 60.4 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 catalog
import (
"bytes"
"errors"
"fmt"
"io/fs"
"path"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"github.com/bmatcuk/doublestar/v4"
"github.com/jeduden/mdsmith/internal/archetype/gensection"
"github.com/jeduden/mdsmith/internal/bytelimit"
"github.com/jeduden/mdsmith/internal/cuetemplate"
"github.com/jeduden/mdsmith/internal/fieldinterp"
"github.com/jeduden/mdsmith/internal/gitignore"
"github.com/jeduden/mdsmith/internal/globpath"
"github.com/jeduden/mdsmith/internal/lint"
"github.com/jeduden/mdsmith/internal/query"
"github.com/jeduden/mdsmith/internal/rule"
"github.com/jeduden/mdsmith/internal/rules/settings"
"github.com/jeduden/mdsmith/internal/rules/tablefmt"
"github.com/jeduden/mdsmith/internal/yamlutil"
)
// numericSortPrefix marks a sort spec whose key value should be
// parsed as an integer before comparison. The prefix follows any
// leading "-" descending marker — `-numeric:id`, not `numeric:-id`.
const numericSortPrefix = "numeric:"
// maxCatalogMatches is the upper bound on the number of files a single
// catalog directive may match. When the walk exceeds this limit the
// GlobWalk callback returns errCatalogCapExceeded to abort early, so at
// most maxCatalogMatches+1 entries are allocated before the diagnostic
// fires and the excess is discarded.
const maxCatalogMatches = 10_000
// errCatalogCapExceeded is the sentinel returned from the GlobWalk
// callback to abort the walk once maxCatalogMatches is exceeded.
var errCatalogCapExceeded = errors.New("catalog match cap exceeded")
func init() {
rule.Register(&Rule{Pad: 1, SeparatorStyle: tablefmt.SeparatorSpaced})
}
// Rule checks that generated sections match their directive output.
//
// engineOnce serialises the lazy initialisation of engine: the rule
// is a registered singleton and the LSP server may call Check from
// multiple goroutines, so a plain check-then-set on the engine
// field races. sync.Once gives both writers and readers a single
// happens-before edge.
//
// Pad and SeparatorStyle mirror MDS025 (table-format)'s knobs and
// govern only the tables this rule emits inside `<?catalog?>` bodies.
// Catalog carries its own copies — rather than reading MDS025's
// configured state — because the lint engine clones rules and applies
// settings per file in parallel; a process-global view of MDS025
// would race across workers. Set both rules to the same style when
// you want host-file tables and catalog-generated tables to share a
// canonical.
type Rule struct {
engineOnce sync.Once
engine *gensection.Engine
Pad int
SeparatorStyle tablefmt.SeparatorStyle
}
// ID implements rule.Rule.
func (r *Rule) ID() string { return "MDS019" }
// Name implements rule.Rule.
func (r *Rule) Name() string { return "catalog" }
// Category implements rule.Rule.
func (r *Rule) Category() string { return "directive" }
// RuleID implements gensection.Directive.
func (r *Rule) RuleID() string { return "MDS019" }
// RuleName implements gensection.Directive.
func (r *Rule) RuleName() string { return "catalog" }
// getEngine lazily initializes and returns the gensection engine.
func (r *Rule) getEngine() *gensection.Engine {
r.engineOnce.Do(func() {
r.engine = gensection.NewEngine(r)
})
return r.engine
}
// Check implements rule.Rule.
func (r *Rule) Check(f *lint.File) []lint.Diagnostic {
if f.FS == nil {
return nil
}
diags := r.getEngine().Check(f)
// Case-mismatch hints run a separate pass over directives. This
// re-reads front-matter but avoids coupling hints to the engine's
// fatal-diagnostic pipeline. Acceptable for typical catalog sizes.
diags = append(diags, r.checkCaseMismatches(f)...)
// Injection warnings are non-fatal and must not block generation,
// so they run as a separate pass outside the engine.
diags = append(diags, r.checkInjection(f)...)
return diags
}
// Fix implements rule.FixableRule.
func (r *Rule) Fix(f *lint.File) []byte {
if f.FS == nil {
return f.Source
}
return r.getEngine().Fix(f)
}
// Validate implements gensection.Directive.
func (r *Rule) Validate(filePath string, line int,
params map[string]string, columns map[string]gensection.ColumnConfig,
) []lint.Diagnostic {
return validateCatalogDirective(filePath, line, params, columns)
}
// Generate implements gensection.Directive.
func (r *Rule) Generate(f *lint.File, filePath string, line int,
params map[string]string, columns map[string]gensection.ColumnConfig,
) (string, []lint.Diagnostic) {
cols := fromGensectionColumns(columns)
// Read errors (e.g. "file too large") are fatal for generation:
// a partially-rendered catalog would silently hide missing rows,
// which is worse than failing loudly with a clear diagnostic.
entries, res, entryDiags := cachedCatalogEntries(f, params, filePath, line)
if len(entryDiags) > 0 {
return "", entryDiags
}
// Check if any matched file includes (directly or indirectly) the
// catalog-owning file. If so, the catalog body would contain itself.
if diags := checkCatalogIncludeCycle(f, filePath, line, entries, res); len(diags) > 0 {
return "", diags
}
hasRow := hasRowTemplate(params)
content, err := renderCatalogContent(params, entries, cols, hasRow)
if err != nil {
return "", []lint.Diagnostic{makeDiag(filePath, line,
fmt.Sprintf("generated section template execution failed: %v", err))}
}
// Defensive guard: refuse to silently empty a previously-populated
// catalog when the glob matched zero files and no `empty:` fallback
// applies. Emptying a non-empty section in that case is almost always
// a misconfiguration (a wrong working directory, a stale glob, or an
// ignore rule that swept up the whole tree) rather than an intentional
// edit, so destroying the rows would discard real content. Returning a
// diagnostic both surfaces the problem in `check` and, via the engine's
// generation-error path, leaves the body untouched in `fix`. An
// already-empty body is left alone (no rows to protect); an `empty:`
// fallback renders non-empty content and so never reaches this branch.
if len(entries) == 0 && content == "" && sectionBodyNonEmpty(f, line) {
return "", []lint.Diagnostic{makeDiag(filePath, line,
"catalog glob matched zero files but the section is non-empty; "+
"refusing to empty it — check the working directory, the glob, "+
"and ignore rules, or set an \"empty:\" fallback to clear it intentionally")}
}
// Format tables this rule generates using its own pad / separator
// settings; see Rule's doc comment for why catalog carries its own
// table-format knobs instead of consulting MDS025.
content = tablefmt.FormatStringWithConfig(content, tablefmt.Config{
Pad: r.Pad,
SeparatorStyle: r.SeparatorStyle,
})
return content, nil
}
// sectionBodyNonEmpty reports whether the catalog section whose start
// marker is on the given 1-based line currently has any non-whitespace
// body content. It powers the destructive-empty guard in Generate: a
// body of only blank lines (or no body at all) carries nothing worth
// protecting, so the guard must not fire for it. Returns false when the
// marker pair cannot be located, matching the conservative "nothing to
// protect" default.
func sectionBodyNonEmpty(f *lint.File, line int) bool {
pairs, _ := gensection.FindMarkerPairs(f, "catalog", "MDS019", "catalog")
for _, mp := range pairs {
if mp.StartLine != line {
continue
}
return strings.TrimSpace(gensection.ExtractContent(f, mp)) != ""
}
return false
}
// ApplySettings implements rule.Configurable.
func (r *Rule) ApplySettings(s map[string]any) error {
for k, v := range s {
switch k {
case "pad":
n, ok := settings.ToInt(v)
if !ok {
return fmt.Errorf("catalog: pad must be an integer, got %T", v)
}
if n < 0 {
return fmt.Errorf("catalog: pad must be non-negative, got %d", n)
}
r.Pad = n
case "separator-style":
style, err := tablefmt.ParseSeparatorStyle(v, "catalog")
if err != nil {
return err
}
r.SeparatorStyle = style
default:
return fmt.Errorf("catalog: unknown setting %q", k)
}
}
return nil
}
// DefaultSettings implements rule.Configurable.
func (r *Rule) DefaultSettings() map[string]any {
return map[string]any{
"pad": 1,
"separator-style": "spaced",
}
}
// hasRowTemplate reports whether the directive declared any
// per-file row template — either the placeholder-style `row:`
// or the CUE-expression `row-expr:`. Most catalog paths gate
// "do we render per-file" on this question.
func hasRowTemplate(params map[string]string) bool {
_, hasRow := params["row"]
_, hasRowExpr := params["row-expr"]
return hasRow || hasRowExpr
}
// validateCatalogDirective validates parameters specific to the catalog directive.
func validateCatalogDirective(
filePath string, line int,
params map[string]string,
columns map[string]gensection.ColumnConfig,
) []lint.Diagnostic {
if diags := validateRowParams(filePath, line, params); len(diags) > 0 {
return diags
}
if diags := validateGlob(filePath, line, params); len(diags) > 0 {
return diags
}
if gitignore, ok := params["gitignore"]; ok {
if gitignore != "true" && gitignore != "false" {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive has invalid "gitignore" value; must be "true" or "false"`)}
}
}
var diags []lint.Diagnostic
if sortVal, hasSort := params["sort"]; hasSort {
diags = append(diags, validateSort(filePath, line, sortVal)...)
}
diags = append(diags, validateRowExpressions(filePath, line, params)...)
if whereExpr := strings.TrimSpace(params["where"]); whereExpr != "" {
if _, err := query.Compile(whereExpr); err != nil {
diags = append(diags, makeDiag(filePath, line,
fmt.Sprintf(`generated section directive has invalid "where" expression: %v`, err)))
}
}
return diags
}
// validateRowParams checks the presence/exclusivity/emptiness
// rules for the `row:` and `row-expr:` parameters and the
// header/footer dependency on having some row form declared.
// A non-empty result is a hard failure that short-circuits
// later validation, matching the previous inline behaviour.
func validateRowParams(
filePath string, line int, params map[string]string,
) []lint.Diagnostic {
_, hasRow := params["row"]
_, hasRowExpr := params["row-expr"]
_, hasHeader := params["header"]
_, hasFooter := params["footer"]
if hasRow && hasRowExpr {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive sets both "row" and "row-expr"; choose one`)}
}
if (hasHeader || hasFooter) && !hasRow && !hasRowExpr {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section template missing required "row" or "row-expr" key`)}
}
if hasRow && strings.TrimSpace(params["row"]) == "" {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive has empty "row" value`)}
}
if hasRowExpr && strings.TrimSpace(params["row-expr"]) == "" {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive has empty "row-expr" value`)}
}
return nil
}
// validateRowExpressions returns diagnostics for malformed
// `row:` placeholder templates and `row-expr:` CUE
// expressions. Presence/exclusivity is already enforced by
// validateRowParams, so at most one of the two paths runs
// per directive.
func validateRowExpressions(
filePath string, line int, params map[string]string,
) []lint.Diagnostic {
var diags []lint.Diagnostic
if row, hasRow := params["row"]; hasRow {
if err := parseRowTemplate(row); err != nil {
diags = append(diags, makeDiag(filePath, line,
fmt.Sprintf("generated section has invalid template: %v", err)))
}
}
if rowExpr, hasRowExpr := params["row-expr"]; hasRowExpr {
if _, err := cuetemplate.Compile(
strings.TrimSpace(rowExpr)); err != nil {
diags = append(diags, makeDiag(filePath, line,
fmt.Sprintf(
`generated section directive has invalid "row-expr" expression: %v`,
err)))
}
}
return diags
}
// splitGlobs splits a possibly newline-joined glob parameter into individual
// patterns. A single-string glob returns a one-element slice.
func splitGlobs(glob string) []string {
return strings.Split(glob, "\n")
}
// validateGlob validates the glob parameter and returns diagnostics on failure.
// The glob value may be a single pattern or multiple newline-joined patterns
// (from a YAML list). Patterns prefixed with "!" are exclusion patterns.
//
// Path-traversal escapes and missing-root errors for ".." patterns are
// checked at generation time, where the project root is available; see
// resolveGlobFS.
func validateGlob(filePath string, line int, params map[string]string) []lint.Diagnostic {
glob, hasGlob := params["glob"]
if !hasGlob {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive missing required "glob" parameter`)}
}
hasInclude := false
for _, raw := range splitGlobs(glob) {
pattern := raw
isExclude := strings.HasPrefix(pattern, "!")
if isExclude {
pattern = pattern[1:]
}
if pattern == "" {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive has empty "glob" parameter`)}
}
if filepath.IsAbs(pattern) {
return []lint.Diagnostic{makeDiag(filePath, line,
"generated section directive has absolute glob path")}
}
if strings.Contains(pattern, "://") {
return []lint.Diagnostic{makeDiag(filePath, line,
"generated section directive has URL scheme in glob pattern")}
}
if !doublestar.ValidatePattern(pattern) {
return []lint.Diagnostic{makeDiag(filePath, line,
"generated section directive has invalid glob pattern: "+pattern)}
}
if containsDotDotInsideBraces(pattern) {
// path.Clean does not expand `{a,b}` alternatives, so a
// `..` segment inside braces would silently bypass the
// project-root containment check at resolve time.
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive has ".." inside brace expansion; rewrite as separate patterns`)}
}
if !isExclude {
hasInclude = true
}
}
if !hasInclude {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive "glob" parameter must include at least one non-negated pattern`)}
}
return nil
}
// validateSort validates the sort value and returns diagnostics.
func validateSort(filePath string, line int, sortVal string) []lint.Diagnostic {
if sortVal == "" {
return []lint.Diagnostic{makeDiag(filePath, line,
`generated section directive has empty "sort" value`)}
}
key := strings.TrimPrefix(sortVal, "-")
key = strings.TrimPrefix(key, numericSortPrefix)
if key == "" {
return []lint.Diagnostic{makeDiag(filePath, line,
fmt.Sprintf("generated section directive has invalid sort value %q", sortVal))}
}
// Built-in sort keys don't need CUE path validation.
if key == "path" || key == "filename" {
return nil
}
// Front-matter sort keys must be valid CUE paths.
if fieldinterp.ParseCUEPath(key) == nil {
return []lint.Diagnostic{makeDiag(filePath, line,
fmt.Sprintf("generated section directive has invalid sort key %q; "+
"non-identifier keys must be quoted, e.g. sort: '\"my-key\"'", key))}
}
return nil
}
// globResolution describes how a catalog directive's glob is rooted.
// It tells the caller which fs.FS to glob against, how to convert matched
// paths back into display paths for the catalog-owning file, the resolved
// include/exclude pattern lists, and where to anchor gitignore lookups.
type globResolution struct {
fs fs.FS
includes []string
excludes []string
gitignoreBase string // absolute directory matched paths are relative to; "" disables gitignore filtering
fileDir string // catalog-owning file's directory, slash-separated, project-root-relative; "" means at root
rootRelative bool // when true, matches are root-relative and need filepath.Rel for display
diags []lint.Diagnostic
}
// displayPath converts a doublestar match into a path relative to the
// catalog-owning file's directory.
func (r globResolution) displayPath(match string) string {
if !r.rootRelative {
return match
}
base := r.fileDir
if base == "" {
base = "."
}
rel, err := filepath.Rel(base, match)
if err != nil {
return match
}
return filepath.ToSlash(rel)
}
// resolveGlobFS resolves the catalog directive's glob scope. When the
// patterns contain ".." segments or when source-dir is set, globs resolve
// against the project root via RootFS; otherwise the catalog-owning file's
// own fs.FS is used. Patterns are rewritten to root-relative form when
// switching to RootFS; an "escapes project root" diagnostic is returned
// when any pattern would resolve outside the root.
func resolveGlobFS(f *lint.File, params map[string]string, filePath string, line int) globResolution {
rawPatterns := splitGlobs(params["glob"])
includes, excludes := globpath.SplitIncludeExclude(rawPatterns)
sourceDir := params["source-dir"]
hasDotDot := dotDotInPatterns(rawPatterns)
if sourceDir == "" && !hasDotDot {
return localFSResolution(f, includes, excludes)
}
if f.RootFS == nil {
if hasDotDot {
return missingRootDiag(filePath, line)
}
return localFSResolution(f, includes, excludes)
}
return resolveAgainstProjectRoot(f, sourceDir, hasDotDot, includes, excludes, filePath, line)
}
func missingRootDiag(filePath string, line int) globResolution {
return globResolution{diags: []lint.Diagnostic{makeDiag(
filePath, line,
`generated section directive glob contains ".." but project root is not configured`)}}
}
// outsideRootDiag reports a ".." pattern in a file whose path cannot be
// related to the configured project root (e.g. it lives on a different
// volume, or above the configured RootDir). Distinct from
// missingRootDiag so the user can tell which situation they're in.
func outsideRootDiag(filePath string, line int) globResolution {
return globResolution{diags: []lint.Diagnostic{makeDiag(
filePath, line,
`generated section directive catalog file is outside project root; ".." globs cannot be resolved`)}}
}
// resolveAgainstProjectRoot rewrites include/exclude patterns relative
// to the project root using RootFS. When the source-dir is invalid or
// fileDir cannot be related to the project root, it falls back to the
// file's fs.FS — except for ".." patterns, which still need a project
// root and surface the outside-root diagnostic instead of silently
// matching nothing on a fs.FS that rejects "..".
func resolveAgainstProjectRoot(
f *lint.File, sourceDir string, hasDotDot bool,
includes, excludes []string,
filePath string, line int,
) globResolution {
fileDir, ok := projectRelFileDir(f)
if !ok {
if hasDotDot {
return outsideRootDiag(filePath, line)
}
return localFSResolution(f, includes, excludes)
}
baseRel, ok := resolveBaseRel(fileDir, sourceDir)
if !ok {
if hasDotDot {
// The pattern needs root-aware resolution for its ".."
// segments; an invalid source-dir is ignored so we still
// catch escapes-root and report them.
baseRel = fileDir
} else {
return localFSResolution(f, includes, excludes)
}
}
resolvedIncludes, ok := resolvePatterns(baseRel, includes)
if !ok {
return escapeDiag(filePath, line)
}
resolvedExcludes, ok := resolvePatterns(baseRel, excludes)
if !ok {
return escapeDiag(filePath, line)
}
gitignoreBase := ""
if f.RootDir != "" {
if abs, err := filepath.Abs(f.RootDir); err == nil {
gitignoreBase = abs
}
}
return globResolution{
fs: f.RootFS,
includes: resolvedIncludes,
excludes: resolvedExcludes,
gitignoreBase: gitignoreBase,
fileDir: fileDir,
rootRelative: true,
}
}
// projectRelFileDir returns the catalog-owning file's directory as a
// slash-separated path relative to the project root, or ok=false when
// no relation can be computed (e.g. an absolute file path with no
// configured RootDir, or a file outside the configured root).
//
// The Runner passes file paths through verbatim from the command line,
// so a relative f.Path may be CWD-relative rather than root-relative
// (e.g. running `mdsmith check index.md` from a subdirectory). When
// RootDir is set, the file path is absolutized first so both absolute
// and any flavor of relative input land on the same root-relative
// string. Without RootDir, the path is assumed to already be
// root-relative.
//
// Returns "" for the project root itself.
func projectRelFileDir(f *lint.File) (string, bool) {
if f.RootDir == "" {
cleaned := path.Clean(filepath.ToSlash(filepath.Dir(f.Path)))
if cleaned == "." {
return "", true
}
if filepath.IsAbs(cleaned) {
return "", false
}
return cleaned, true
}
rootAbs, err := filepath.Abs(f.RootDir)
if err != nil {
return "", false
}
fileAbs := f.Path
if !filepath.IsAbs(fileAbs) {
fileAbs, err = filepath.Abs(fileAbs)
if err != nil {
return "", false
}
}
rel, err := filepath.Rel(rootAbs, filepath.Dir(fileAbs))
if err != nil {
return "", false
}
rel = filepath.ToSlash(rel)
if rel == "." {
return "", true
}
if rel == ".." || strings.HasPrefix(rel, "../") {
return "", false
}
return rel, true
}
func escapeDiag(filePath string, line int) globResolution {
return globResolution{diags: []lint.Diagnostic{makeDiag(
filePath, line,
"generated section directive glob escapes project root")}}
}
// containsDotDotInsideBraces reports whether p has a ".." segment inside
// a `{a,b}` brace alternative. doublestar expands braces lazily during
// matching, but path.Clean treats `{..,foo}` as a single opaque segment,
// so such a `..` would slip past the project-root containment check.
// Detecting it lets the validator reject the pattern up front instead of
// silently producing partial matches.
func containsDotDotInsideBraces(p string) bool {
depth := 0
n := len(p)
for i := 0; i < n; i++ {
switch p[i] {
case '{':
depth++
case '}':
if depth > 0 {
depth--
}
case '.':
if depth == 0 || i+1 >= n || p[i+1] != '.' {
continue
}
if !braceSegmentBoundary(p, i-1) || !braceSegmentBoundary(p, i+2) {
continue
}
return true
}
}
return false
}
// braceSegmentBoundary reports whether p[i] is at or past a delimiter
// that separates path segments inside a brace expansion: `/`, `,`, `{`,
// or `}`. Out-of-range positions are treated as boundaries so a `..`
// at the very edge of a brace block still matches.
func braceSegmentBoundary(p string, i int) bool {
if i < 0 || i >= len(p) {
return true
}
c := p[i]
return c == '/' || c == ',' || c == '{' || c == '}'
}
// dotDotInPatterns reports whether any pattern contains a ".." segment.
func dotDotInPatterns(patterns []string) bool {
for _, p := range patterns {
if globpath.ContainsDotDotSegment(strings.TrimPrefix(p, "!")) {
return true
}
}
return false
}
// localFSResolution builds the fast-path resolution that globs from the
// catalog-owning file's own fs.FS. Used when no source-dir is set and the
// patterns contain no ".." segments, or as a fallback when the project
// root is not configured.
//
// gitignoreBase is left empty when absBaseDir cannot derive an absolute
// path. A relative "" or "." base would otherwise leak into
// absMatchedPath as a non-absolute cache key, breaking the LSP
// invalidation contract (which keys by absolute doc.path). Empty base
// opts the resolution out of both run-cache use and gitignore
// anchoring, matching the legacy pre-cache behavior.
func localFSResolution(f *lint.File, includes, excludes []string) globResolution {
base := ""
if abs, ok := absBaseDir(f); ok {
base = abs
}
return globResolution{
fs: f.FS,
includes: includes,
excludes: excludes,
gitignoreBase: base,
}
}
// absBaseDir returns the absolute filesystem directory f.FS is rooted
// at — i.e. the absolute equivalent of "where doublestar matches
// resolve from for this file". Three resolution strategies, picked in
// order:
//
// 1. f.Path is already absolute → use filepath.Dir(f.Path) directly.
// 2. f.RootDir is set (the LSP path: doc paths arrive workspace-
// relative but the workspace root is configured, and f.FS is
// wired from the document's absolute directory) → anchor at
// RootDir + Dir(f.Path) so cache keys align with the absolute
// doc.path the LSP's Server.invalidateCachedRead uses.
// 3. Otherwise → filepath.Abs(Dir(f.Path)), which falls back to the
// process CWD (matches the legacy CLI behavior).
//
// Without strategy 2 the LSP would key cache entries by /cwd/X.md
// while invalidating by /workspace/X.md, so a didChange / didSave on
// a target would silently miss the cached entry and stale catalog
// bodies would persist.
func absBaseDir(f *lint.File) (string, bool) {
dir := filepath.Dir(f.Path)
if filepath.IsAbs(dir) {
return filepath.Clean(dir), true
}
if f.RootDir != "" {
root, err := filepath.Abs(f.RootDir)
if err == nil {
return filepath.Clean(filepath.Join(root, dir)), true
}
}
abs, err := filepath.Abs(dir)
return filepath.Clean(abs), err == nil
}
// resolveBaseRel returns the project-root-relative directory glob patterns
// resolve against. When sourceDir is set it overrides the file's own
// directory; an absolute or escaping sourceDir signals failure (ok=false).
func resolveBaseRel(fileDir, sourceDir string) (string, bool) {
if sourceDir == "" {
return fileDir, true
}
sd := path.Clean(sourceDir)
if sd == "." {
sd = ""
}
if sd == ".." || strings.HasPrefix(sd, "../") || filepath.IsAbs(sd) {
return "", false
}
return sd, true
}
// resolvePatterns rewrites each pattern relative to baseRel; ok is false
// when any pattern would resolve outside the project root.
func resolvePatterns(baseRel string, patterns []string) ([]string, bool) {
resolved := make([]string, 0, len(patterns))
for _, p := range patterns {
r, escapes := globpath.ResolveAgainstRoot(baseRel, p)
if escapes {
return nil, false
}
resolved = append(resolved, r)
}
return resolved, true
}
// catalogEntries holds one buildCatalogEntries result so f.Memo can
// cache the (entries, resolution, diags) triple behind a single key.
// The resolution flows through to the include-cycle scan: catalogs
// resolved via RootFS need the scan to walk through f.RootFS with
// root-relative paths so cross-directory cycles are still detected.
type catalogEntries struct {
entries []fileEntry
res globResolution
diags []lint.Diagnostic
}
// cachedCatalogEntries returns buildCatalogEntries' result, computed
// once per directive per Check. A directive is identified by its file
// and start line, which the generate, injection, and case-mismatch
// passes all pass identically for the same marker pair, so without
// this memo every matched file's glob + front-matter read ran three
// times per directive. The result is read-only for every caller
// (entries are already sorted by buildCatalogEntries). The memo lives
// on the per-Check *lint.File, so nothing is cached across files or
// runs.
func cachedCatalogEntries(
f *lint.File, params map[string]string, filePath string, line int,
) ([]fileEntry, globResolution, []lint.Diagnostic) {
key := "catalog.entries:" + filePath + "#" + strconv.Itoa(line)
v := f.Memo(key, func() any {
e, res, d := buildCatalogEntries(f, params, filePath, line)
return catalogEntries{entries: e, res: res, diags: d}
})
r := v.(catalogEntries)
return r.entries, r.res, r.diags
}
// buildCatalogEntries resolves glob matches, reads front matter, and
// returns sorted file entries for the catalog directive. Read errors
// (notably "file too large") are returned as diagnostics attached to
// the directive's file+line. Callers in the Generate path treat any
// returned diagnostic as fatal to avoid producing an incomplete catalog;
// check-only callers (checkInjection, checkCaseMismatches) discard the
// diagnostics because Generate already surfaces them. Callers reached
// during Check go through cachedCatalogEntries so the three passes do
// not each rebuild the same directive's entries.
func buildCatalogEntries(
f *lint.File, params map[string]string, filePath string, line int,
) ([]fileEntry, globResolution, []lint.Diagnostic) {
res := resolveGlobFS(f, params, filePath, line)
if len(res.diags) > 0 {
return nil, res, res.diags
}
files := cachedGlobMatches(res, f, params)
if len(files) > maxCatalogMatches {
return nil, res, []lint.Diagnostic{makeDiag(filePath, line,
fmt.Sprintf("catalog matched too many files (%d); limit is %d",
len(files), maxCatalogMatches))}
}
sortKey, descending, numeric := parseSort(params)
hasRow := hasRowTemplate(params)
whereExpr := strings.TrimSpace(params["where"])
needFM := hasRow || whereExpr != "" || (sortKey != "path" && sortKey != "filename")
var matcher *query.Matcher
if whereExpr != "" {
m, err := query.Compile(whereExpr)
if err != nil {
// Validate already reports this; skip filtering rather than
// silently drop every file when the expression is broken.
matcher = nil
} else {
matcher = m
}
}
var diags []lint.Diagnostic
entries := make([]fileEntry, 0, len(files))
for _, p := range files {
displayPath := res.displayPath(p)
fields := map[string]any{"filename": displayPath}
var fm map[string]any
if needFM {
var err error
absPath, _ := absMatchedPath(res, p)
fm, err = cachedFrontMatter(f, res.fs, p, absPath, f.MaxInputBytes)
if err != nil {
diags = append(diags, makeDiag(filePath, line,
fmt.Sprintf("cannot read front matter from %q: %v", displayPath, err)))
continue
}
for k, v := range fm {
fields[k] = v
}
}
if matcher != nil && !matcher.Match(fm) {
continue
}
entries = append(entries, fileEntry{fields: fields, matchPath: p})
}
sortEntries(entries, sortKey, descending, numeric)
return entries, res, diags
}
// resolveGlobMatchesFrom expands include patterns using the resolved
// fs.FS, filters out exclude and gitignore matches, and returns
// deduplicated file paths.
// cachedGlobMatches resolves the directive's glob matches through the
// run-wide RunCache when the resolution tree is identifiable: the
// directory walk and per-match stat/exclude/gitignore filtering are a
// pure function of the resolution base and the pattern set, yet they
// re-ran for every host file whose catalogs glob the same tree (the
// dominant cost of a catalog-heavy check). A resolution with no
// gitignoreBase has no stable identity for its fs.FS, so it bypasses
// the cache. Content edits never change a match list; tree-shape
// changes drop the slots via RunCache.InvalidateGlobMatches (wired to
// the LSP's watched-files create/delete path).
func cachedGlobMatches(res globResolution, f *lint.File, params map[string]string) []string {
if f.RunCache == nil || res.gitignoreBase == "" {
return resolveGlobMatchesFrom(res, f, params)
}
return f.RunCache.GlobMatches(globMatchesKey(res, params), func() []string {
return resolveGlobMatchesFrom(res, f, params)
})
}
// globMatchesKey encodes the resolution identity unambiguously:
// every variable-length component is length-prefixed, so a pattern or
// path containing separator-like bytes (reachable through directive
// params in hostile markdown) cannot make two different
// configurations collide on one cache slot.
func globMatchesKey(res globResolution, params map[string]string) string {
var key strings.Builder
key.Grow(64)
writeKeyPart := func(s string) {
key.WriteString(strconv.Itoa(len(s)))
key.WriteByte(':')
key.WriteString(s)
}
writeKeyPart(res.gitignoreBase)
writeKeyPart(res.fileDir)
if res.rootRelative {
key.WriteString("r1")
}
if params["gitignore"] == "false" {
key.WriteString("g0")
}
key.WriteString(strconv.Itoa(len(res.includes)))
for _, p := range res.includes {
writeKeyPart(p)
}
for _, p := range res.excludes {
writeKeyPart(p)
}
return key.String()
}
func resolveGlobMatchesFrom(res globResolution, f *lint.File, params map[string]string) []string {
matcher := resolveGitignoreMatcher(f, params)
base := res.gitignoreBase
if matcher == nil {
base = ""
}
// 8 is a rough heuristic: each glob pattern typically matches several
// files, so pre-sizing avoids the first few growth doublings.
seen := make(map[string]struct{}, len(res.includes)*8)
var dirVerdicts map[string]bool
if matcher != nil && base != "" {
dirVerdicts = make(map[string]bool, 16)
}
var files []string
for _, pattern := range res.includes {
// GlobWalk hands over the walk's own DirEntry, so the
// regular-file check below costs no follow-up stat through
// res.fs — the former per-match fs.Stat was several syscalls
// per matched file through the os.Root-backed DirFS. Only
// symlink entries still stat, to keep the old follow
// semantics: a symlink to a file is included, a symlink to a
// directory (or a broken one) is skipped.
_ = doublestar.GlobWalk(res.fs, pattern,
func(m string, d fs.DirEntry) error {
if _, ok := seen[m]; ok {
return nil
}
if d.IsDir() {
return nil
}
if d.Type()&fs.ModeSymlink != 0 {
info, err := fs.Stat(res.fs, m)
if err != nil || info.IsDir() {
return nil
}
}
if isExcluded(m, res.excludes) {
return nil
}
if matcher != nil && base != "" && isGitignoredMemo(matcher, base, m, dirVerdicts) {
return nil
}
seen[m] = struct{}{}
files = append(files, m)
if len(files) > maxCatalogMatches {
return errCatalogCapExceeded
}
return nil
})
if len(files) > maxCatalogMatches {
break
}
}
return files
}
// resolveGitignoreMatcher returns the gitignore matcher to use for
// filtering, or nil when gitignore filtering is disabled or no matcher
// is available. The absolute base directory matched paths are anchored
// to is supplied separately by resolveGlobFS as part of globResolution.
func resolveGitignoreMatcher(f *lint.File, params map[string]string) *gitignore.Matcher {
if params["gitignore"] == "false" {
return nil
}
return f.GetGitignore()
}
// checkCatalogInjection warns when interpolated front-matter values contain
// embedded newlines or "](" sequences that could inject Markdown
// structure into the generated catalog section.
func checkCatalogInjection(filePath string, line int, entries []fileEntry) []lint.Diagnostic {
var diags []lint.Diagnostic
for _, entry := range entries {
entryPath := fieldinterp.Stringify(entry.fields["filename"])
// Iterate keys in sorted order for deterministic diagnostic ordering.
keys := make([]string, 0, len(entry.fields))
for k := range entry.fields {
if k != "filename" {
keys = append(keys, k)
}
}
sort.Strings(keys)
for _, key := range keys {
val := entry.fields[key]
s := fieldinterp.Stringify(val)
if strings.ContainsAny(s, "\n\r") {
diags = append(diags, lint.Diagnostic{
File: filePath,
Line: line,
Column: 1,
RuleID: "MDS019",
RuleName: "catalog",
Severity: lint.Warning,
Message: fmt.Sprintf(
"front-matter field %q in %q contains embedded newlines; "+
"this may inject unexpected Markdown into the catalog",
key, entryPath),
})
}
if strings.Contains(s, "](") {
diags = append(diags, lint.Diagnostic{
File: filePath,
Line: line,
Column: 1,
RuleID: "MDS019",