-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
markdownlint-cli2.js
executable file
·1102 lines (1046 loc) · 32.2 KB
/
markdownlint-cli2.js
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
#!/usr/bin/env node
// @ts-check
"use strict";
// @ts-ignore
// eslint-disable-next-line camelcase, no-inline-comments, no-undef
const dynamicRequire = (typeof __non_webpack_require__ === "undefined") ? require : /* c8 ignore next */ __non_webpack_require__;
// Capture native require implementation for dynamic loading of modules
// Requires
const pathDefault = require("node:path");
const pathPosix = pathDefault.posix;
const { pathToFileURL } = require("node:url");
const markdownlintLibrary = require("markdownlint");
const {
markdownlint,
"extendConfig": markdownlintExtendConfig,
"readConfig": markdownlintReadConfig
} = markdownlintLibrary.promises;
const markdownlintRuleHelpers = require("markdownlint/helpers");
const appendToArray = require("./append-to-array");
const mergeOptions = require("./merge-options");
const resolveAndRequire = require("./resolve-and-require");
// Variables
const packageName = "markdownlint-cli2";
const packageVersion = "0.14.0";
const libraryName = "markdownlint";
const libraryVersion = markdownlintLibrary.getVersion();
const bannerMessage = `${packageName} v${packageVersion} (${libraryName} v${libraryVersion})`;
const dotOnlySubstitute = "*.{md,markdown}";
const utf8 = "utf8";
// No-op function
const noop = () => null;
// Gets a JSONC parser
const getJsoncParse = () => require("./parsers/jsonc-parse.js");
// Gets a YAML parser
const getYamlParse = () => require("./parsers/yaml-parse.js");
// Gets an ordered array of parsers
const getParsers = () => require("./parsers/parsers.js");
// Negates a glob
const negateGlob = (glob) => `!${glob}`;
// Throws a meaningful exception for an unusable configuration file
const throwForConfigurationFile = (file, error) => {
throw new Error(
`Unable to use configuration file '${file}'; ${error?.message}`,
// @ts-ignore
{ "cause": error }
);
};
// Return a posix path (even on Windows)
const posixPath = (p) => p.split(pathDefault.sep).join(pathPosix.sep);
// Expands a path with a tilde to an absolute path
const expandTildePath = (id) => (
markdownlintRuleHelpers.expandTildePath(id, require("node:os"))
);
// Resolves module paths relative to the specified directory
const resolveModulePaths = (dir, modulePaths) => (
modulePaths.map((path) => pathDefault.resolve(dir, expandTildePath(path)))
);
// Read a JSON(C) or YAML file and return the object
const readConfig = (fs, dir, name, otherwise) => () => {
const file = pathPosix.join(dir, name);
return fs.promises.access(file).
then(
() => markdownlintReadConfig(
file,
getParsers(),
fs
),
otherwise
);
};
// Import or resolve/require a module ID with a custom directory in the path
const importOrRequireResolve = async (dirOrDirs, id, noRequire) => {
if (typeof id === "string") {
if (noRequire) {
return null;
}
const dirs = Array.isArray(dirOrDirs) ? dirOrDirs : [ dirOrDirs ];
const expandId = expandTildePath(id);
const errors = [];
try {
return resolveAndRequire(dynamicRequire, expandId, dirs);
} catch (error) {
errors.push(error);
}
try {
// eslint-disable-next-line n/no-unsupported-features/node-builtins
const isURL = !pathDefault.isAbsolute(expandId) && URL.canParse(expandId);
const urlString = (
isURL ? new URL(expandId) : pathToFileURL(pathDefault.resolve(dirs[0], expandId))
).toString();
// eslint-disable-next-line no-inline-comments
const module = await import(/* webpackIgnore: true */ urlString);
return module.default;
} catch (error) {
errors.push(error);
}
// @ts-ignore
throw new AggregateError(
errors,
`Unable to require or import module '${id}'.`
);
}
return id;
};
// Import or require an array of modules by ID
const importOrRequireIds = (dirs, ids, noRequire) => (
Promise.all(
ids.map(
(id) => importOrRequireResolve(dirs, id, noRequire)
)
).then((results) => results.filter(Boolean))
);
// Import or require an array of modules by ID (preserving parameters)
const importOrRequireIdsAndParams = (dirs, idsAndParams, noRequire) => (
Promise.all(
idsAndParams.map(
(idAndParams) => importOrRequireResolve(dirs, idAndParams[0], noRequire).
then((module) => module && [ module, ...idAndParams.slice(1) ])
)
).then((results) => results.filter(Boolean))
);
// Import or require a JavaScript file and return the exported object
const importOrRequireConfig = (fs, dir, name, noRequire, otherwise) => () => {
const file = pathPosix.join(dir, name);
return fs.promises.access(file).
then(
() => importOrRequireResolve(dir, name, noRequire),
otherwise
);
};
// Extend a config object if it has 'extends' property
const getExtendedConfig = (config, configPath, fs) => {
if (config.extends) {
return markdownlintExtendConfig(
config,
configPath,
getParsers(),
fs
);
}
return Promise.resolve(config);
};
// Read an options or config file in any format and return the object
const readOptionsOrConfig = async (configPath, fs, noRequire) => {
const basename = pathPosix.basename(configPath);
const dirname = pathPosix.dirname(configPath);
let options = null;
let config = null;
try {
if (basename.endsWith(".markdownlint-cli2.jsonc")) {
options = getJsoncParse()(await fs.promises.readFile(configPath, utf8));
} else if (basename.endsWith(".markdownlint-cli2.yaml")) {
options = getYamlParse()(await fs.promises.readFile(configPath, utf8));
} else if (
basename.endsWith(".markdownlint-cli2.cjs") ||
basename.endsWith(".markdownlint-cli2.mjs")
) {
options = await importOrRequireResolve(dirname, basename, noRequire);
} else if (
basename.endsWith(".markdownlint.jsonc") ||
basename.endsWith(".markdownlint.json") ||
basename.endsWith(".markdownlint.yaml") ||
basename.endsWith(".markdownlint.yml")
) {
config = await markdownlintReadConfig(configPath, getParsers(), fs);
} else if (
basename.endsWith(".markdownlint.cjs") ||
basename.endsWith(".markdownlint.mjs")
) {
config = await importOrRequireResolve(dirname, basename, noRequire);
} else {
throw new Error(
"File name should be (or end with) one of the supported types " +
"(e.g., '.markdownlint.json' or 'example.markdownlint-cli2.jsonc')."
);
}
} catch (error) {
throwForConfigurationFile(configPath, error);
}
if (options) {
if (options.config) {
options.config = await getExtendedConfig(options.config, configPath, fs);
}
return options;
}
config = await getExtendedConfig(config, configPath, fs);
return { config };
};
// Filter a list of files to ignore by glob
const removeIgnoredFiles = (dir, files, ignores) => {
const micromatch = require("micromatch");
return micromatch(
files.map((file) => pathPosix.relative(dir, file)),
ignores
).map((file) => pathPosix.join(dir, file));
};
// Process/normalize command-line arguments and return glob patterns
const processArgv = (argv) => {
const globPatterns = argv.map(
(glob) => {
if (glob.startsWith(":")) {
return glob;
}
// Escape RegExp special characters recognized by fast-glob
// https://github.com/mrmlnc/fast-glob#advanced-syntax
const specialCharacters = /\\(?![$()*+?[\]^])/gu;
if (glob.startsWith("\\:")) {
return `\\:${glob.slice(2).replace(specialCharacters, "/")}`;
}
return (glob.startsWith("#") ? `!${glob.slice(1)}` : glob).
replace(specialCharacters, "/");
}
);
if ((globPatterns.length === 1) && (globPatterns[0] === ".")) {
// Substitute a more reasonable pattern
globPatterns[0] = dotOnlySubstitute;
}
return globPatterns;
};
// Show help if missing arguments
const showHelp = (logMessage, showBanner) => {
if (showBanner) {
logMessage(bannerMessage);
}
logMessage(`https://github.com/DavidAnson/markdownlint-cli2
Syntax: markdownlint-cli2 glob0 [glob1] [...] [globN] [--config file] [--fix] [--help]
Glob expressions (from the globby library):
- * matches any number of characters, but not /
- ? matches a single character, but not /
- ** matches any number of characters, including /
- {} allows for a comma-separated list of "or" expressions
- ! or # at the beginning of a pattern negate the match
- : at the beginning identifies a literal file path
Dot-only glob:
- The command "markdownlint-cli2 ." would lint every file in the current directory tree which is probably not intended
- Instead, it is mapped to "markdownlint-cli2 ${dotOnlySubstitute}" which lints all Markdown files in the current directory
- To lint every file in the current directory tree, the command "markdownlint-cli2 **" can be used instead
Optional parameters:
- --config specifies the path to a configuration file to define the base configuration
- --fix updates files to resolve fixable issues (can be overridden in configuration)
- --help writes this message to the console and exits without doing anything else
- --no-globs ignores the "globs" property if present in the top-level options object
Configuration via:
- .markdownlint-cli2.jsonc
- .markdownlint-cli2.yaml
- .markdownlint-cli2.cjs or .markdownlint-cli2.mjs
- .markdownlint.jsonc or .markdownlint.json
- .markdownlint.yaml or .markdownlint.yml
- .markdownlint.cjs or .markdownlint.mjs
- package.json
Cross-platform compatibility:
- UNIX and Windows shells expand globs according to different rules; quoting arguments is recommended
- Some Windows shells don't handle single-quoted (') arguments well; double-quote (") is recommended
- Shells that expand globs do not support negated patterns (!node_modules); quoting is required here
- Some UNIX shells parse exclamation (!) in double-quotes; hashtag (#) is recommended in these cases
- The path separator is forward slash (/) on all platforms; backslash (\\) is automatically converted
- On any platform, passing the parameter "--" causes all remaining parameters to be treated literally
The most compatible syntax for cross-platform support:
$ markdownlint-cli2 "**/*.md" "#node_modules"`
);
return 2;
};
// Get (creating if necessary) and process a directory's info object
const getAndProcessDirInfo = (
fs,
tasks,
dirToDirInfo,
dir,
relativeDir,
noRequire,
allowPackageJson
) => {
// Create dirInfo
let dirInfo = dirToDirInfo[dir];
if (!dirInfo) {
dirInfo = {
dir,
relativeDir,
"parent": null,
"files": [],
"markdownlintConfig": null,
"markdownlintOptions": null
};
dirToDirInfo[dir] = dirInfo;
// Load markdownlint-cli2 object(s)
const markdownlintCli2Jsonc = pathPosix.join(dir, ".markdownlint-cli2.jsonc");
const markdownlintCli2Yaml = pathPosix.join(dir, ".markdownlint-cli2.yaml");
const markdownlintCli2Cjs = pathPosix.join(dir, ".markdownlint-cli2.cjs");
const markdownlintCli2Mjs = pathPosix.join(dir, ".markdownlint-cli2.mjs");
const packageJson = pathPosix.join(dir, "package.json");
let file = "[UNKNOWN]";
// eslint-disable-next-line no-return-assign
const captureFile = (f) => file = f;
tasks.push(
fs.promises.access(captureFile(markdownlintCli2Jsonc)).
then(
() => fs.promises.readFile(file, utf8).then(getJsoncParse()),
() => fs.promises.access(captureFile(markdownlintCli2Yaml)).
then(
() => fs.promises.readFile(file, utf8).then(getYamlParse()),
() => fs.promises.access(captureFile(markdownlintCli2Cjs)).
then(
() => importOrRequireResolve(dir, file, noRequire),
() => fs.promises.access(captureFile(markdownlintCli2Mjs)).
then(
() => importOrRequireResolve(dir, file, noRequire),
() => (allowPackageJson
? fs.promises.access(captureFile(packageJson))
// eslint-disable-next-line prefer-promise-reject-errors
: Promise.reject()
).
then(
() => fs.promises.
readFile(file, utf8).
then(getJsoncParse()).
then((obj) => obj[packageName]),
noop
)
)
)
)
).
then((options) => {
dirInfo.markdownlintOptions = options;
return options &&
options.config &&
getExtendedConfig(
options.config,
// Just need to identify a file in the right directory
markdownlintCli2Jsonc,
fs
).
then((config) => {
options.config = config;
});
}).
catch((error) => {
throwForConfigurationFile(file, error);
})
);
// Load markdownlint object(s)
const readConfigs =
readConfig(
fs,
dir,
".markdownlint.jsonc",
readConfig(
fs,
dir,
".markdownlint.json",
readConfig(
fs,
dir,
".markdownlint.yaml",
readConfig(
fs,
dir,
".markdownlint.yml",
importOrRequireConfig(
fs,
dir,
".markdownlint.cjs",
noRequire,
importOrRequireConfig(
fs,
dir,
".markdownlint.mjs",
noRequire,
noop
)
)
)
)
)
);
tasks.push(
readConfigs().
then((config) => {
dirInfo.markdownlintConfig = config;
})
);
}
// Return dirInfo
return dirInfo;
};
// Get base markdownlint-cli2 options object
const getBaseOptions = async (
fs,
baseDir,
relativeDir,
globPatterns,
options,
fixDefault,
noGlobs,
noRequire
) => {
const tasks = [];
const dirToDirInfo = {};
getAndProcessDirInfo(
fs,
tasks,
dirToDirInfo,
baseDir,
relativeDir,
noRequire,
true
);
await Promise.all(tasks);
// eslint-disable-next-line no-multi-assign
const baseMarkdownlintOptions = dirToDirInfo[baseDir].markdownlintOptions =
mergeOptions(
mergeOptions(
{ "fix": fixDefault },
options
),
dirToDirInfo[baseDir].markdownlintOptions
);
if (!noGlobs) {
// Append any globs specified in markdownlint-cli2 configuration
const globs = baseMarkdownlintOptions.globs || [];
appendToArray(globPatterns, globs);
}
// Pass base ignore globs as globby patterns (best performance)
const ignorePatterns =
// eslint-disable-next-line unicorn/no-array-callback-reference
(baseMarkdownlintOptions.ignores || []).map(negateGlob);
appendToArray(globPatterns, ignorePatterns);
return {
baseMarkdownlintOptions,
dirToDirInfo
};
};
// Enumerate files from globs and build directory infos
const enumerateFiles = async (
fs,
baseDirSystem,
baseDir,
globPatterns,
dirToDirInfo,
gitignore,
ignoreFiles,
noRequire
) => {
const tasks = [];
/** @type {import("globby").Options} */
const globbyOptions = {
"absolute": true,
"cwd": baseDir,
"dot": true,
"expandDirectories": false,
gitignore,
ignoreFiles,
"suppressErrors": true,
fs
};
// Special-case literal files
const literalFiles = [];
const filteredGlobPatterns = globPatterns.filter(
(globPattern) => {
if (globPattern.startsWith(":")) {
literalFiles.push(
posixPath(pathDefault.resolve(baseDirSystem, globPattern.slice(1)))
);
return false;
}
return true;
}
).map((globPattern) => globPattern.replace(/^\\:/u, ":"));
const baseMarkdownlintOptions = dirToDirInfo[baseDir].markdownlintOptions;
const globsForIgnore =
(baseMarkdownlintOptions.globs || []).
filter((glob) => glob.startsWith("!"));
const filteredLiteralFiles =
((literalFiles.length > 0) && (globsForIgnore.length > 0))
? removeIgnoredFiles(baseDir, literalFiles, globsForIgnore)
: literalFiles;
// Manually expand directories to avoid globby call to dir-glob.sync
const expandedDirectories = await Promise.all(
filteredGlobPatterns.map((globPattern) => {
const barePattern =
globPattern.startsWith("!")
? globPattern.slice(1)
: globPattern;
const globPath = (
pathPosix.isAbsolute(barePattern) ||
pathDefault.isAbsolute(barePattern)
)
? barePattern
: pathPosix.join(baseDir, barePattern);
return fs.promises.stat(globPath).
then((stats) => (stats.isDirectory()
? pathPosix.join(globPattern, "**")
: globPattern)).
catch(() => globPattern);
})
);
// Process glob patterns
// eslint-disable-next-line no-inline-comments
const { globby } = await import(/* webpackMode: "eager" */ "globby");
const files = [
...await globby(expandedDirectories, globbyOptions),
...filteredLiteralFiles
];
for (const file of files) {
const dir = pathPosix.dirname(file);
const dirInfo = getAndProcessDirInfo(
fs,
tasks,
dirToDirInfo,
dir,
null,
noRequire,
false
);
dirInfo.files.push(file);
}
await Promise.all(tasks);
};
// Enumerate (possibly missing) parent directories and update directory infos
const enumerateParents = async (
fs,
baseDir,
dirToDirInfo,
noRequire
) => {
const tasks = [];
// Create a lookup of baseDir and parents
const baseDirParents = {};
let baseDirParent = baseDir;
do {
baseDirParents[baseDirParent] = true;
baseDirParent = pathPosix.dirname(baseDirParent);
} while (!baseDirParents[baseDirParent]);
// Visit parents of each dirInfo
for (let lastDirInfo of Object.values(dirToDirInfo)) {
let { dir } = lastDirInfo;
let lastDir = dir;
while (
!baseDirParents[dir] &&
(dir = pathPosix.dirname(dir)) &&
(dir !== lastDir)
) {
lastDir = dir;
const dirInfo =
getAndProcessDirInfo(
fs,
tasks,
dirToDirInfo,
dir,
null,
noRequire,
false
);
lastDirInfo.parent = dirInfo;
lastDirInfo = dirInfo;
}
// If dir not under baseDir, inject it as parent for configuration
if (dir !== baseDir) {
dirToDirInfo[dir].parent = dirToDirInfo[baseDir];
}
}
await Promise.all(tasks);
};
// Create directory info objects by enumerating file globs
const createDirInfos = async (
fs,
baseDirSystem,
baseDir,
globPatterns,
dirToDirInfo,
optionsOverride,
gitignore,
ignoreFiles,
noRequire
) => {
await enumerateFiles(
fs,
baseDirSystem,
baseDir,
globPatterns,
dirToDirInfo,
gitignore,
ignoreFiles,
noRequire
);
await enumerateParents(
fs,
baseDir,
dirToDirInfo,
noRequire
);
// Merge file lists with identical configuration
const dirs = Object.keys(dirToDirInfo);
dirs.sort((a, b) => b.length - a.length);
const dirInfos = [];
const noConfigDirInfo =
// eslint-disable-next-line unicorn/consistent-function-scoping
(dirInfo) => (
dirInfo.parent &&
!dirInfo.markdownlintConfig &&
!dirInfo.markdownlintOptions
);
const tasks = [];
for (const dir of dirs) {
const dirInfo = dirToDirInfo[dir];
if (noConfigDirInfo(dirInfo)) {
if (dirInfo.parent) {
appendToArray(dirInfo.parent.files, dirInfo.files);
}
dirToDirInfo[dir] = null;
} else {
const { markdownlintOptions, relativeDir } = dirInfo;
const effectiveDir = relativeDir || dir;
const effectiveModulePaths = resolveModulePaths(
effectiveDir,
(markdownlintOptions && markdownlintOptions.modulePaths) || []
);
if (markdownlintOptions && markdownlintOptions.customRules) {
tasks.push(
importOrRequireIds(
[ effectiveDir, ...effectiveModulePaths ],
markdownlintOptions.customRules,
noRequire
).then((customRules) => {
// Expand nested arrays (for packages that export multiple rules)
markdownlintOptions.customRules = customRules.flat();
})
);
}
if (markdownlintOptions && markdownlintOptions.markdownItPlugins) {
tasks.push(
importOrRequireIdsAndParams(
[ effectiveDir, ...effectiveModulePaths ],
markdownlintOptions.markdownItPlugins,
noRequire
).then((markdownItPlugins) => {
markdownlintOptions.markdownItPlugins = markdownItPlugins;
})
);
}
dirInfos.push(dirInfo);
}
}
await Promise.all(tasks);
for (const dirInfo of dirInfos) {
while (dirInfo.parent && !dirToDirInfo[dirInfo.parent.dir]) {
dirInfo.parent = dirInfo.parent.parent;
}
}
// Verify dirInfos is simplified
// if (
// dirInfos.filter(
// (di) => di.parent && !dirInfos.includes(di.parent)
// ).length > 0
// ) {
// throw new Error("Extra parent");
// }
// if (
// dirInfos.filter(
// (di) => !di.parent && (di.dir !== baseDir)
// ).length > 0
// ) {
// throw new Error("Missing parent");
// }
// if (
// dirInfos.filter(
// (di) => di.parent &&
// !((di.markdownlintConfig ? 1 : 0) ^ (di.markdownlintOptions ? 1 : 0))
// ).length > 0
// ) {
// throw new Error("Missing object");
// }
// if (dirInfos.filter((di) => di.dir === "/").length > 0) {
// throw new Error("Includes root");
// }
// Merge configuration by inheritance
for (const dirInfo of dirInfos) {
let markdownlintOptions = dirInfo.markdownlintOptions || {};
let { markdownlintConfig } = dirInfo;
let parent = dirInfo;
// eslint-disable-next-line prefer-destructuring
while ((parent = parent.parent)) {
if (parent.markdownlintOptions) {
markdownlintOptions = mergeOptions(
parent.markdownlintOptions,
markdownlintOptions
);
}
if (
!markdownlintConfig &&
parent.markdownlintConfig &&
!markdownlintOptions.config
) {
// eslint-disable-next-line prefer-destructuring
markdownlintConfig = parent.markdownlintConfig;
}
}
dirInfo.markdownlintOptions = mergeOptions(
markdownlintOptions,
optionsOverride
);
dirInfo.markdownlintConfig = markdownlintConfig;
}
return dirInfos;
};
// Lint files in groups by shared configuration
const lintFiles = (fs, dirInfos, fileContents) => {
const tasks = [];
// For each dirInfo
for (const dirInfo of dirInfos) {
const { dir, files, markdownlintConfig, markdownlintOptions } = dirInfo;
// Filter file/string inputs to only those in the dirInfo
let filesAfterIgnores = files;
if (
markdownlintOptions.ignores &&
(markdownlintOptions.ignores.length > 0)
) {
// eslint-disable-next-line unicorn/no-array-callback-reference
const ignores = markdownlintOptions.ignores.map(negateGlob);
filesAfterIgnores = removeIgnoredFiles(dir, files, ignores);
}
const filteredFiles = filesAfterIgnores.filter(
(file) => fileContents[file] === undefined
);
const filteredStrings = {};
for (const file of filesAfterIgnores) {
if (fileContents[file] !== undefined) {
filteredStrings[file] = fileContents[file];
}
}
// Create markdownlint options object
const options = {
"files": filteredFiles,
"strings": filteredStrings,
"config": markdownlintConfig || markdownlintOptions.config,
"configParsers": getParsers(),
"customRules": markdownlintOptions.customRules,
"frontMatter": markdownlintOptions.frontMatter
? new RegExp(markdownlintOptions.frontMatter, "u")
: undefined,
"handleRuleFailures": true,
"markdownItPlugins": markdownlintOptions.markdownItPlugins,
"noInlineConfig": Boolean(markdownlintOptions.noInlineConfig),
"resultVersion": 3,
fs
};
// Invoke markdownlint
// @ts-ignore
let task = markdownlint(options);
// For any fixable errors, read file, apply fixes, and write it back
if (markdownlintOptions.fix) {
task = task.then((results) => {
options.files = [];
const subTasks = [];
const errorFiles = Object.keys(results);
for (const fileName of errorFiles) {
const errorInfos = results[fileName].
filter((errorInfo) => errorInfo.fixInfo);
if (errorInfos.length > 0) {
delete results[fileName];
options.files.push(fileName);
subTasks.push(fs.promises.readFile(fileName, utf8).
then((original) => {
const fixed = markdownlintRuleHelpers.
applyFixes(original, errorInfos);
return fs.promises.writeFile(fileName, fixed, utf8);
})
);
}
}
return Promise.all(subTasks).
// @ts-ignore
then(() => markdownlint(options)).
then((fixResults) => ({
...results,
...fixResults
}));
});
}
// Queue tasks for this dirInfo
tasks.push(task);
}
// Return result of all tasks
return Promise.all(tasks);
};
// Create summary of results
const createSummary = (baseDir, taskResults) => {
const summary = [];
let counter = 0;
for (const results of taskResults) {
for (const fileName in results) {
const errorInfos = results[fileName];
for (const errorInfo of errorInfos) {
const fileNameRelative = pathPosix.relative(baseDir, fileName);
summary.push({
"fileName": fileNameRelative,
...errorInfo,
counter
});
counter++;
}
}
}
summary.sort((a, b) => (
a.fileName.localeCompare(b.fileName) ||
(a.lineNumber - b.lineNumber) ||
a.ruleNames[0].localeCompare(b.ruleNames[0]) ||
(a.counter - b.counter)
));
for (const result of summary) {
delete result.counter;
}
return summary;
};
// Output summary via formatters
const outputSummary = async (
baseDir,
relativeDir,
summary,
outputFormatters,
modulePaths,
logMessage,
logError,
noRequire
) => {
const errorsPresent = (summary.length > 0);
if (errorsPresent || outputFormatters) {
const formatterOptions = {
"directory": baseDir,
"results": summary,
logMessage,
logError
};
const dir = relativeDir || baseDir;
const dirs = [ dir, ...modulePaths ];
const formattersAndParams = outputFormatters
? await importOrRequireIdsAndParams(dirs, outputFormatters, noRequire)
: [ [ require("markdownlint-cli2-formatter-default") ] ];
await Promise.all(formattersAndParams.map((formatterAndParams) => {
const [ formatter, ...formatterParams ] = formatterAndParams;
return formatter(formatterOptions, ...formatterParams);
}));
}
return errorsPresent;
};
// Main function
const main = async (params) => {
// Capture parameters
const {
directory,
argv,
optionsDefault,
optionsOverride,
fileContents,
nonFileContents,
noRequire
} = params;
let {
noGlobs
} = params;
const logMessage = params.logMessage || noop;
const logError = params.logError || noop;
const fs = params.fs || require("node:fs");
const baseDirSystem =
(directory && pathDefault.resolve(directory)) ||
process.cwd();
const baseDir = posixPath(baseDirSystem);
// Merge and process args/argv
let fixDefault = false;
// eslint-disable-next-line unicorn/no-useless-undefined
let configPath = undefined;
let sawDashDash = false;
let shouldShowHelp = false;
const argvFiltered = (argv || []).filter((arg) => {
if (sawDashDash) {
return true;
} else if (configPath === null) {
configPath = arg;
// eslint-disable-next-line unicorn/prefer-switch
} else if (arg === "--") {
sawDashDash = true;
} else if (arg === "--config") {
configPath = null;
} else if (arg === "--fix") {
fixDefault = true;
} else if (arg === "--help") {
shouldShowHelp = true;
} else if (arg === "--no-globs") {
noGlobs = true;
} else {
return true;
}
return false;
});
if (shouldShowHelp) {
return showHelp(logMessage, true);
}
// Read argv configuration file (if relevant and present)
let optionsArgv = null;
let relativeDir = null;
let globPatterns = null;
let baseOptions = null;
try {
if (configPath) {
const resolvedConfigPath =
posixPath(pathDefault.resolve(baseDirSystem, configPath));
optionsArgv =
await readOptionsOrConfig(resolvedConfigPath, fs, noRequire);
relativeDir = pathPosix.dirname(resolvedConfigPath);
}
// Process arguments and get base options
globPatterns = processArgv(argvFiltered);
baseOptions = await getBaseOptions(
fs,
baseDir,
relativeDir,
globPatterns,
optionsArgv || optionsDefault,
fixDefault,
noGlobs,
noRequire
);
} finally {
if (!baseOptions?.baseMarkdownlintOptions.noBanner) {
logMessage(bannerMessage);
}
}
if (
((globPatterns.length === 0) && !nonFileContents) ||
(configPath === null)
) {
return showHelp(logMessage, false);
}
// Include any file overrides or non-file content
const { baseMarkdownlintOptions, dirToDirInfo } = baseOptions;
const resolvedFileContents = {};
for (const file in fileContents) {
const resolvedFile = posixPath(pathDefault.resolve(baseDirSystem, file));
resolvedFileContents[resolvedFile] =
fileContents[file];
}
for (const nonFile in nonFileContents) {
resolvedFileContents[nonFile] = nonFileContents[nonFile];
}
appendToArray(
dirToDirInfo[baseDir].files,
Object.keys(nonFileContents || {})