markdownlint-cli 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +13 -4
  2. package/markdownlint.js +79 -100
  3. package/package.json +27 -22
package/README.md CHANGED
@@ -42,6 +42,12 @@ markdownlint --help
42
42
  -h, --help display help for command
43
43
  ```
44
44
 
45
+ Or run using [Docker](https://www.docker.com) and [GitHub Packages](https://github.com/features/packages):
46
+
47
+ ```bash
48
+ docker run -v $PWD:/workdir ghcr.io/igorshubovych/markdownlint-cli:latest "*.md"
49
+ ```
50
+
45
51
  ### Globbing
46
52
 
47
53
  `markdownlint-cli` supports advanced globbing patterns like `**/*.md` ([more information][globprimer]).
@@ -96,10 +102,11 @@ A sample configuration file:
96
102
  For more examples, see [.markdownlint.jsonc][markdownlint-jsonc], [.markdownlint.yaml][markdownlint-yaml], or the [style folder][style-folder].
97
103
 
98
104
  The CLI argument `--config` is not required.
99
- If it is not provided, `markdownlint-cli` looks for the file `.markdownlint.json`/`.markdownlint.yaml`/`.markdownlint.yml` in current folder, or for the file `.markdownlintrc` in the current or all parent folders.
105
+ If it is not provided, `markdownlint-cli` looks for the file `.markdownlint.jsonc`/`.markdownlint.json`/`.markdownlint.yaml`/`.markdownlint.yml` in current folder, or for the file `.markdownlintrc` in the current or all parent folders.
100
106
  The algorithm is described in detail on the [`rc` package page][rc-standards].
101
107
  If the `--config` argument is provided, the file must be valid JSON, JSONC, JS, or YAML.
102
- JS configuration files contain JavaScript code, must have the `.js` extension, and must export (via `module.exports = ...`) a configuration object of the form shown above.
108
+ JS configuration files contain JavaScript code, must have the `.js` or `.cjs` file extension, and must export (via `module.exports = ...`) a configuration object of the form shown above.
109
+ If your workspace _(project)_ is [ESM-only] _(`"type": "module"` set in the root `package.json` file)_, then the configuration file **should end with `.cjs` file extension**.
103
110
  A JS configuration file may internally `require` one or more npm packages as a way of reusing configuration across projects.
104
111
 
105
112
  `--enable` and `--disable` override configuration files; if a configuration file disables `MD002` and you pass `--enable MD002`, it will be enabled.
@@ -112,9 +119,10 @@ If a rule is passed to both `--enable` and `--disable`, it will be disabled.
112
119
  `markdownlint-cli` returns one of the following exit codes:
113
120
 
114
121
  - `0`: Program ran successfully
115
- - `1`: Linting errors / bad parameter
122
+ - `1`: Linting errors
116
123
  - `2`: Unable to write `-o`/`--output` output file
117
124
  - `3`: Unable to load `-r`/`--rules` custom rule
125
+ - `4`: Unexpected error (e.g. malformed config)
118
126
 
119
127
  ## Use with pre-commit
120
128
 
@@ -122,7 +130,7 @@ To run `markdownlint-cli` as part of a [pre-commit][pre-commit] workflow, add so
122
130
 
123
131
  ```yaml
124
132
  - repo: https://github.com/igorshubovych/markdownlint-cli
125
- rev: v0.30.0
133
+ rev: v0.32.0
126
134
  hooks:
127
135
  - id: markdownlint
128
136
  ```
@@ -154,3 +162,4 @@ MIT © Igor Shubovych
154
162
  [gitignore]: https://git-scm.com/docs/gitignore
155
163
  [pre-commit]: https://pre-commit.com/
156
164
  [pre-commit-version]: https://pre-commit.com/#overriding-language-version
165
+ [ESM-only]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
package/markdownlint.js CHANGED
@@ -10,15 +10,16 @@ const process = require('process');
10
10
  const program = require('commander');
11
11
 
12
12
  const options = program.opts();
13
- const differenceWith = require('lodash.differencewith');
14
- const flatten = require('lodash.flatten');
13
+ const glob = require('glob');
15
14
  const markdownlint = require('markdownlint');
16
15
  const rc = require('run-con');
17
- const glob = require('glob');
18
16
  const minimatch = require('minimatch');
19
- const minimist = require('minimist');
20
17
  const pkg = require('./package.json');
21
18
 
19
+ function posixPath(p) {
20
+ return p.split(path.sep).join(path.posix.sep);
21
+ }
22
+
22
23
  function jsoncParse(text) {
23
24
  return JSON.parse(require('jsonc-parser').stripComments(text));
24
25
  }
@@ -27,51 +28,43 @@ function jsYamlSafeLoad(text) {
27
28
  return require('js-yaml').load(text);
28
29
  }
29
30
 
30
- const projectConfigFiles = [
31
- '.markdownlint.json',
32
- '.markdownlint.yaml',
33
- '.markdownlint.yml'
34
- ];
31
+ const exitCodes = {
32
+ lintFindings: 1,
33
+ failedToWriteOutputFile: 2,
34
+ failedToLoadCustomRules: 3,
35
+ unexpectedError: 4
36
+ };
37
+
38
+ const projectConfigFiles = ['.markdownlint.jsonc', '.markdownlint.json', '.markdownlint.yaml', '.markdownlint.yml'];
35
39
  const configFileParsers = [jsoncParse, jsYamlSafeLoad];
36
40
  const fsOptions = {encoding: 'utf8'};
37
41
  const processCwd = process.cwd();
38
42
 
39
43
  function readConfiguration(userConfigFile) {
40
- const jsConfigFile = /\.js$/i.test(userConfigFile);
41
- const rcArgv = minimist(process.argv.slice(2));
42
- if (jsConfigFile) {
43
- // Prevent rc package from parsing .js config file as INI
44
- delete rcArgv.config;
45
- }
44
+ const jsConfigFile = /\.c?js$/i.test(userConfigFile);
46
45
 
47
46
  // Load from well-known config files
48
- let config = rc('markdownlint', {}, rcArgv);
47
+ let config = rc('markdownlint', {});
49
48
  for (const projectConfigFile of projectConfigFiles) {
50
49
  try {
51
50
  fs.accessSync(projectConfigFile, fs.R_OK);
52
51
  const projectConfig = markdownlint.readConfigSync(projectConfigFile, configFileParsers);
53
- config = require('deep-extend')(config, projectConfig);
52
+ config = {...config, ...projectConfig};
54
53
  break;
55
54
  } catch {
56
55
  // Ignore failure
57
56
  }
58
57
  }
59
58
 
60
- // Normally parsing this file is not needed,
61
- // because it is already parsed by rc package.
62
- // However I have to do it to overwrite configuration
63
- // from .markdownlint.{json,yaml,yml}.
59
+ // Normally parsing this file is not needed, because it is already parsed by rc package.
60
+ // However I have to do it to overwrite configuration from .markdownlint.{json,yaml,yml}.
64
61
  if (userConfigFile) {
65
62
  try {
66
- const userConfig = jsConfigFile
67
- // Evaluate .js configuration file as code
68
- ? require(path.resolve(processCwd, userConfigFile))
69
- // Load JSON/YAML configuration as data
70
- : markdownlint.readConfigSync(userConfigFile, configFileParsers);
63
+ const userConfig = jsConfigFile ? require(path.resolve(processCwd, userConfigFile)) : markdownlint.readConfigSync(userConfigFile, configFileParsers);
71
64
  config = require('deep-extend')(config, userConfig);
72
65
  } catch (error) {
73
66
  console.error(`Cannot read or parse config file '${userConfigFile}': ${error.message}`);
74
- process.exitCode = 1;
67
+ process.exitCode = exitCodes.unexpectedError;
75
68
  }
76
69
  }
77
70
 
@@ -91,31 +84,22 @@ function prepareFileList(files, fileExtensions, previousResults) {
91
84
  extensionGlobPart += '{' + fileExtensions.join(',') + '}';
92
85
  }
93
86
 
94
- files = files.map(function (file) {
87
+ files = files.map(file => {
95
88
  try {
96
89
  if (fs.lstatSync(file).isDirectory()) {
97
90
  // Directory (file falls through to below)
98
91
  if (previousResults) {
99
- const matcher = new minimatch.Minimatch(
100
- path.resolve(processCwd, path.join(file, '**', extensionGlobPart)), globOptions);
101
- return previousResults.filter(function (fileInfo) {
102
- return matcher.match(fileInfo.absolute);
103
- }).map(function (fileInfo) {
104
- return fileInfo.original;
105
- });
92
+ const matcher = new minimatch.Minimatch(posixPath(path.resolve(processCwd, path.join(file, '**', extensionGlobPart))), globOptions);
93
+ return previousResults.filter(fileInfo => matcher.match(fileInfo.absolute)).map(fileInfo => fileInfo.original);
106
94
  }
107
95
 
108
- return glob.sync(path.join(file, '**', extensionGlobPart), globOptions);
96
+ return glob.sync(posixPath(path.join(file, '**', extensionGlobPart)), globOptions);
109
97
  }
110
98
  } catch {
111
99
  // Not a directory, not a file, may be a glob
112
100
  if (previousResults) {
113
- const matcher = new minimatch.Minimatch(path.resolve(processCwd, file), globOptions);
114
- return previousResults.filter(function (fileInfo) {
115
- return matcher.match(fileInfo.absolute);
116
- }).map(function (fileInfo) {
117
- return fileInfo.original;
118
- });
101
+ const matcher = new minimatch.Minimatch(posixPath(path.resolve(processCwd, file)), globOptions);
102
+ return previousResults.filter(fileInfo => matcher.match(fileInfo.absolute)).map(fileInfo => fileInfo.original);
119
103
  }
120
104
 
121
105
  return glob.sync(file, globOptions);
@@ -124,50 +108,48 @@ function prepareFileList(files, fileExtensions, previousResults) {
124
108
  // File
125
109
  return file;
126
110
  });
127
- return flatten(files).map(function (file) {
128
- return {
129
- original: file,
130
- relative: path.relative(processCwd, file),
131
- absolute: path.resolve(file)
132
- };
133
- });
111
+ return files.flat().map(file => ({
112
+ original: file,
113
+ relative: path.relative(processCwd, file),
114
+ absolute: path.resolve(file)
115
+ }));
134
116
  }
135
117
 
136
118
  function printResult(lintResult) {
137
- const results = flatten(Object.keys(lintResult).map(file => lintResult[file].map(result => {
138
- if (options.json) {
119
+ const results = Object.keys(lintResult).flatMap(file =>
120
+ lintResult[file].map(result => {
121
+ if (options.json) {
122
+ return {
123
+ fileName: file,
124
+ ...result
125
+ };
126
+ }
127
+
139
128
  return {
140
- fileName: file,
141
- ...result
129
+ file: file,
130
+ lineNumber: result.lineNumber,
131
+ column: (result.errorRange && result.errorRange[0]) || 0,
132
+ names: result.ruleNames.join('/'),
133
+ description: result.ruleDescription + (result.errorDetail ? ' [' + result.errorDetail + ']' : '') + (result.errorContext ? ' [Context: "' + result.errorContext + '"]' : '')
142
134
  };
143
- }
144
-
145
- return {
146
- file: file,
147
- lineNumber: result.lineNumber,
148
- column: (result.errorRange && result.errorRange[0]) || 0,
149
- names: result.ruleNames.join('/'),
150
- description: result.ruleDescription
151
- + (result.errorDetail ? ' [' + result.errorDetail + ']' : '')
152
- + (result.errorContext ? ' [Context: "' + result.errorContext + '"]' : '')
153
- };
154
- })));
135
+ })
136
+ );
155
137
 
156
138
  let lintResultString = '';
157
139
  if (results.length > 0) {
158
140
  if (options.json) {
159
- results.sort((a, b) => a.fileName.localeCompare(b.fileName) || a.lineNumber - b.lineNumber
160
- || a.ruleDescription.localeCompare(b.ruleDescription));
141
+ results.sort((a, b) => a.fileName.localeCompare(b.fileName) || a.lineNumber - b.lineNumber || a.ruleDescription.localeCompare(b.ruleDescription));
161
142
  lintResultString = JSON.stringify(results, null, 2);
162
143
  } else {
163
- results.sort((a, b) => a.file.localeCompare(b.file) || a.lineNumber - b.lineNumber
164
- || a.names.localeCompare(b.names) || a.description.localeCompare(b.description));
165
-
166
- lintResultString = results.map(result => {
167
- const {file, lineNumber, column, names, description} = result;
168
- const columnText = column ? `:${column}` : '';
169
- return `${file}:${lineNumber}${columnText} ${names} ${description}`;
170
- }).join('\n');
144
+ results.sort((a, b) => a.file.localeCompare(b.file) || a.lineNumber - b.lineNumber || a.names.localeCompare(b.names) || a.description.localeCompare(b.description));
145
+
146
+ lintResultString = results
147
+ .map(result => {
148
+ const {file, lineNumber, column, names, description} = result;
149
+ const columnText = column ? `:${column}` : '';
150
+ return `${file}:${lineNumber}${columnText} ${names} ${description}`;
151
+ })
152
+ .join('\n');
171
153
  }
172
154
 
173
155
  // Note: process.exit(1) will end abruptly, interrupting asynchronous IO
@@ -175,18 +157,16 @@ function printResult(lintResult) {
175
157
  // and let the program terminate normally.
176
158
  // @see {@link https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_exit_code}
177
159
  // @see {@link https://github.com/igorshubovych/markdownlint-cli/pull/29#issuecomment-343535291}
178
- process.exitCode = 1;
160
+ process.exitCode = exitCodes.lintFindings;
179
161
  }
180
162
 
181
163
  if (options.output) {
182
- lintResultString = lintResultString.length > 0
183
- ? lintResultString + os.EOL
184
- : lintResultString;
164
+ lintResultString = lintResultString.length > 0 ? lintResultString + os.EOL : lintResultString;
185
165
  try {
186
166
  fs.writeFileSync(options.output, lintResultString);
187
167
  } catch (error) {
188
168
  console.warn('Cannot write to output file ' + options.output + ': ' + error.message);
189
- process.exitCode = 2;
169
+ process.exitCode = exitCodes.failedToWriteOutputFile;
190
170
  }
191
171
  } else if (lintResultString && !options.quiet) {
192
172
  console.error(lintResultString);
@@ -241,12 +221,10 @@ function tryResolvePath(filepath) {
241
221
  }
242
222
 
243
223
  function loadCustomRules(rules) {
244
- return flatten(rules.map(function (rule) {
224
+ return rules.flatMap(rule => {
245
225
  try {
246
226
  const resolvedPath = [tryResolvePath(rule)];
247
- const fileList = flatten(prepareFileList(resolvedPath, ['js']).map(function (filepath) {
248
- return require(filepath.absolute);
249
- }));
227
+ const fileList = prepareFileList(resolvedPath, ['js']).flatMap(filepath => require(filepath.absolute));
250
228
  if (fileList.length === 0) {
251
229
  throw new Error('No such rule');
252
230
  }
@@ -254,9 +232,9 @@ function loadCustomRules(rules) {
254
232
  return fileList;
255
233
  } catch (error) {
256
234
  console.error('Cannot load custom rule ' + rule + ': ' + error.message);
257
- return process.exit(3);
235
+ return process.exit(exitCodes.failedToLoadCustomRules);
258
236
  }
259
- }));
237
+ });
260
238
  }
261
239
 
262
240
  let ignorePath = '.markdownlintignore';
@@ -274,15 +252,10 @@ if (existsSync(ignorePath)) {
274
252
  ignoreFilter = fileInfo => !ignoreInstance.ignores(fileInfo.relative);
275
253
  }
276
254
 
277
- const files = prepareFileList(program.args, ['md', 'markdown'])
278
- .filter(value => ignoreFilter(value));
255
+ const files = prepareFileList(program.args, ['md', 'markdown']).filter(value => ignoreFilter(value));
279
256
  const ignores = prepareFileList(options.ignore, ['md', 'markdown'], files);
280
257
  const customRules = loadCustomRules(options.rules);
281
- const diff = differenceWith(files, ignores, function (a, b) {
282
- return a.absolute === b.absolute;
283
- }).map(function (paths) {
284
- return paths.original;
285
- });
258
+ const diff = files.filter(file => !ignores.some(ignore => ignore.absolute === file.absolute)).map(paths => paths.original);
286
259
 
287
260
  function lintAndPrint(stdin, files) {
288
261
  files = files || [];
@@ -338,11 +311,17 @@ function lintAndPrint(stdin, files) {
338
311
  printResult(lintResult);
339
312
  }
340
313
 
341
- if ((files.length > 0) && !options.stdin) {
342
- lintAndPrint(null, diff);
343
- } else if ((files.length === 0) && options.stdin && !options.fix) {
344
- const getStdin = require('get-stdin');
345
- getStdin().then(lintAndPrint);
346
- } else {
347
- program.help();
314
+ try {
315
+ if (files.length > 0 && !options.stdin) {
316
+ lintAndPrint(null, diff);
317
+ } else if (files.length === 0 && options.stdin && !options.fix) {
318
+ import('get-stdin')
319
+ .then(module => module.default())
320
+ .then(lintAndPrint);
321
+ } else {
322
+ program.help();
323
+ }
324
+ } catch (error) {
325
+ console.error(error);
326
+ process.exit(exitCodes.unexpectedError);
348
327
  }
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "markdownlint-cli",
3
- "version": "0.30.0",
3
+ "version": "0.32.0",
4
4
  "description": "MarkdownLint Command Line Interface",
5
5
  "main": "markdownlint.js",
6
6
  "bin": {
7
7
  "markdownlint": "markdownlint.js"
8
8
  },
9
9
  "engines": {
10
- "node": ">=12"
10
+ "node": ">=14"
11
11
  },
12
12
  "scripts": {
13
13
  "invalid": "node ./markdownlint.js --config test/test-config.json -- test/incorrect.md",
14
14
  "fix": "cp test/incorrect.md test/incorrect.copy.md && node ./markdownlint.js --fix test/incorrect.copy.md ; cat test/incorrect.copy.md && rm test/incorrect.copy.md",
15
15
  "test": "ava",
16
- "watch": "npm test -- --watch --tap | tap-growl",
16
+ "watch": "npm test --watch",
17
17
  "start": "node ./markdownlint.js",
18
18
  "precommit": "xo && npm test"
19
19
  },
@@ -37,30 +37,25 @@
37
37
  },
38
38
  "homepage": "https://github.com/igorshubovych/markdownlint-cli#readme",
39
39
  "dependencies": {
40
- "commander": "~8.3.0",
41
- "deep-extend": "~0.6.0",
42
- "get-stdin": "~8.0.0",
43
- "glob": "~7.2.0",
44
- "ignore": "~5.1.9",
40
+ "commander": "~9.4.0",
41
+ "get-stdin": "~9.0.0",
42
+ "glob": "~8.0.3",
43
+ "ignore": "~5.2.0",
45
44
  "js-yaml": "^4.1.0",
46
- "jsonc-parser": "~3.0.0",
47
- "lodash.differencewith": "~4.5.0",
48
- "lodash.flatten": "~4.4.0",
49
- "markdownlint": "~0.24.0",
50
- "markdownlint-rule-helpers": "~0.15.0",
51
- "minimatch": "~3.0.4",
52
- "minimist": "~1.2.5",
53
- "run-con": "~1.2.10"
45
+ "jsonc-parser": "~3.1.0",
46
+ "markdownlint": "~0.26.0",
47
+ "markdownlint-rule-helpers": "~0.17.0",
48
+ "minimatch": "~5.1.0",
49
+ "run-con": "~1.2.11"
54
50
  },
55
51
  "devDependencies": {
56
- "ava": "^3.15.0",
57
- "execa": "^5.1.1",
58
- "husky": "^7.0.4",
59
- "tap-growl": "^3.0.0",
52
+ "ava": "^4.3.1",
53
+ "execa": "^6.1.0",
60
54
  "test-rule-package": "./test/custom-rules/test-rule-package",
61
- "xo": "^0.46.4"
55
+ "xo": "^0.50.0"
62
56
  },
63
57
  "xo": {
58
+ "prettier": true,
64
59
  "space": true,
65
60
  "rules": {
66
61
  "comma-dangle": 0,
@@ -73,12 +68,22 @@
73
68
  "unicorn/prefer-ternary": 0
74
69
  }
75
70
  },
71
+ "prettier": {
72
+ "arrowParens": "avoid",
73
+ "bracketSpacing": false,
74
+ "endOfLine": "auto",
75
+ "printWidth": 1000,
76
+ "singleQuote": true,
77
+ "trailingComma": "none"
78
+ },
76
79
  "ava": {
77
80
  "files": [
78
81
  "test/**/*.js",
79
82
  "!test/custom-rules/**/*.js",
80
83
  "!test/md043-config.js"
81
84
  ],
82
- "failFast": true
85
+ "failFast": true,
86
+ "timeout": "1m",
87
+ "workerThreads": false
83
88
  }
84
89
  }