markdownlint-cli 0.28.1 → 0.31.1

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 +18 -6
  2. package/markdownlint.js +96 -107
  3. package/package.json +26 -20
package/README.md CHANGED
@@ -26,18 +26,26 @@ markdownlint --help
26
26
  MarkdownLint Command Line Interface
27
27
 
28
28
  Options:
29
-
30
- -h, --help output usage information
31
29
  -V, --version output the version number
32
30
  -c, --config [configFile] configuration file (JSON, JSONC, JS, or YAML)
33
31
  -d, --dot include files/folders with a dot (for example `.github`)
34
32
  -f, --fix fix basic errors (does not work with STDIN)
35
- -i, --ignore [file|directory|glob] file(s) to ignore/exclude
33
+ -i, --ignore [file|directory|glob] file(s) to ignore/exclude (default: [])
36
34
  -j, --json write issues in json format
37
35
  -o, --output [outputFile] write issues to file (no console)
38
36
  -p, --ignore-path [file] path to file with ignore pattern(s)
39
- -r, --rules [file|directory|glob|package] custom rule files
37
+ -q, --quiet do not write issues to STDOUT
38
+ -r, --rules [file|directory|glob|package] include custom rule files (default: [])
40
39
  -s, --stdin read from STDIN (does not work with files)
40
+ --enable [rules...] Enable certain rules, e.g. --enable MD013 MD041
41
+ --disable [rules...] Disable certain rules, e.g. --disable MD013 MD041
42
+ -h, --help display help for command
43
+ ```
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"
41
49
  ```
42
50
 
43
51
  ### Globbing
@@ -100,6 +108,9 @@ If the `--config` argument is provided, the file must be valid JSON, JSONC, JS,
100
108
  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.
101
109
  A JS configuration file may internally `require` one or more npm packages as a way of reusing configuration across projects.
102
110
 
111
+ `--enable` and `--disable` override configuration files; if a configuration file disables `MD002` and you pass `--enable MD002`, it will be enabled.
112
+ If a rule is passed to both `--enable` and `--disable`, it will be disabled.
113
+
103
114
  > JS configuration files must be provided via the `--config` argument; they are not automatically loaded because running untrusted code is a security concern.
104
115
 
105
116
  ## Exit codes
@@ -107,9 +118,10 @@ A JS configuration file may internally `require` one or more npm packages as a w
107
118
  `markdownlint-cli` returns one of the following exit codes:
108
119
 
109
120
  - `0`: Program ran successfully
110
- - `1`: Linting errors / bad parameter
121
+ - `1`: Linting errors
111
122
  - `2`: Unable to write `-o`/`--output` output file
112
123
  - `3`: Unable to load `-r`/`--rules` custom rule
124
+ - `4`: Unexpected error (e.g. malformed config)
113
125
 
114
126
  ## Use with pre-commit
115
127
 
@@ -117,7 +129,7 @@ To run `markdownlint-cli` as part of a [pre-commit][pre-commit] workflow, add so
117
129
 
118
130
  ```yaml
119
131
  - repo: https://github.com/igorshubovych/markdownlint-cli
120
- rev: v0.28.1
132
+ rev: v0.31.1
121
133
  hooks:
122
134
  - id: markdownlint
123
135
  ```
package/markdownlint.js CHANGED
@@ -5,17 +5,16 @@
5
5
  const fs = require('fs');
6
6
  const path = require('path');
7
7
  const Module = require('module');
8
+ const os = require('os');
9
+ const process = require('process');
8
10
  const program = require('commander');
11
+
9
12
  const options = program.opts();
10
- const differenceWith = require('lodash.differencewith');
11
- const flatten = require('lodash.flatten');
13
+ const glob = require('glob');
12
14
  const markdownlint = require('markdownlint');
13
15
  const rc = require('run-con');
14
- const glob = require('glob');
15
16
  const minimatch = require('minimatch');
16
- const minimist = require('minimist');
17
- const pkg = require('./package');
18
- const os = require('os');
17
+ const pkg = require('./package.json');
19
18
 
20
19
  function jsoncParse(text) {
21
20
  return JSON.parse(require('jsonc-parser').stripComments(text));
@@ -25,50 +24,43 @@ function jsYamlSafeLoad(text) {
25
24
  return require('js-yaml').load(text);
26
25
  }
27
26
 
28
- const projectConfigFiles = [
29
- '.markdownlint.json',
30
- '.markdownlint.yaml',
31
- '.markdownlint.yml'
32
- ];
27
+ const exitCodes = {
28
+ lintFindings: 1,
29
+ failedToWriteOutputFile: 2,
30
+ failedToLoadCustomRules: 3,
31
+ unexpectedError: 4
32
+ };
33
+
34
+ const projectConfigFiles = ['.markdownlint.json', '.markdownlint.yaml', '.markdownlint.yml'];
33
35
  const configFileParsers = [jsoncParse, jsYamlSafeLoad];
34
36
  const fsOptions = {encoding: 'utf8'};
35
37
  const processCwd = process.cwd();
36
38
 
37
39
  function readConfiguration(userConfigFile) {
38
40
  const jsConfigFile = /\.js$/i.test(userConfigFile);
39
- const rcArgv = minimist(process.argv.slice(2));
40
- if (jsConfigFile) {
41
- // Prevent rc package from parsing .js config file as INI
42
- delete rcArgv.config;
43
- }
44
41
 
45
42
  // Load from well-known config files
46
- let config = rc('markdownlint', {}, rcArgv);
43
+ let config = rc('markdownlint', {});
47
44
  for (const projectConfigFile of projectConfigFiles) {
48
45
  try {
49
46
  fs.accessSync(projectConfigFile, fs.R_OK);
50
47
  const projectConfig = markdownlint.readConfigSync(projectConfigFile, configFileParsers);
51
- config = require('deep-extend')(config, projectConfig);
48
+ config = {...config, ...projectConfig};
52
49
  break;
53
50
  } catch {
54
51
  // Ignore failure
55
52
  }
56
53
  }
57
54
 
58
- // Normally parsing this file is not needed,
59
- // because it is already parsed by rc package.
60
- // However I have to do it to overwrite configuration
61
- // from .markdownlint.{json,yaml,yml}.
55
+ // Normally parsing this file is not needed, because it is already parsed by rc package.
56
+ // However I have to do it to overwrite configuration from .markdownlint.{json,yaml,yml}.
62
57
  if (userConfigFile) {
63
58
  try {
64
- const userConfig = jsConfigFile ?
65
- // Evaluate .js configuration file as code
66
- require(path.resolve(processCwd, userConfigFile)) :
67
- // Load JSON/YAML configuration as data
68
- markdownlint.readConfigSync(userConfigFile, configFileParsers);
59
+ const userConfig = jsConfigFile ? require(path.resolve(processCwd, userConfigFile)) : markdownlint.readConfigSync(userConfigFile, configFileParsers);
69
60
  config = require('deep-extend')(config, userConfig);
70
61
  } catch (error) {
71
- console.warn('Cannot read or parse config file ' + userConfigFile + ': ' + error.message);
62
+ console.error(`Cannot read or parse config file '${userConfigFile}': ${error.message}`);
63
+ process.exitCode = exitCodes.unexpectedError;
72
64
  }
73
65
  }
74
66
 
@@ -88,18 +80,13 @@ function prepareFileList(files, fileExtensions, previousResults) {
88
80
  extensionGlobPart += '{' + fileExtensions.join(',') + '}';
89
81
  }
90
82
 
91
- files = files.map(function (file) {
83
+ files = files.map(file => {
92
84
  try {
93
85
  if (fs.lstatSync(file).isDirectory()) {
94
86
  // Directory (file falls through to below)
95
87
  if (previousResults) {
96
- const matcher = new minimatch.Minimatch(
97
- path.resolve(processCwd, path.join(file, '**', extensionGlobPart)), globOptions);
98
- return previousResults.filter(function (fileInfo) {
99
- return matcher.match(fileInfo.absolute);
100
- }).map(function (fileInfo) {
101
- return fileInfo.original;
102
- });
88
+ const matcher = new minimatch.Minimatch(path.resolve(processCwd, path.join(file, '**', extensionGlobPart)), globOptions);
89
+ return previousResults.filter(fileInfo => matcher.match(fileInfo.absolute)).map(fileInfo => fileInfo.original);
103
90
  }
104
91
 
105
92
  return glob.sync(path.join(file, '**', extensionGlobPart), globOptions);
@@ -108,11 +95,7 @@ function prepareFileList(files, fileExtensions, previousResults) {
108
95
  // Not a directory, not a file, may be a glob
109
96
  if (previousResults) {
110
97
  const matcher = new minimatch.Minimatch(path.resolve(processCwd, file), globOptions);
111
- return previousResults.filter(function (fileInfo) {
112
- return matcher.match(fileInfo.absolute);
113
- }).map(function (fileInfo) {
114
- return fileInfo.original;
115
- });
98
+ return previousResults.filter(fileInfo => matcher.match(fileInfo.absolute)).map(fileInfo => fileInfo.original);
116
99
  }
117
100
 
118
101
  return glob.sync(file, globOptions);
@@ -121,77 +104,67 @@ function prepareFileList(files, fileExtensions, previousResults) {
121
104
  // File
122
105
  return file;
123
106
  });
124
- return flatten(files).map(function (file) {
125
- return {
126
- original: file,
127
- relative: path.relative(processCwd, file),
128
- absolute: path.resolve(file)
129
- };
130
- });
107
+ return files.flat().map(file => ({
108
+ original: file,
109
+ relative: path.relative(processCwd, file),
110
+ absolute: path.resolve(file)
111
+ }));
131
112
  }
132
113
 
133
114
  function printResult(lintResult) {
134
-
135
- const results = flatten(Object.keys(lintResult).map(file => {
136
- return lintResult[file].map(result => {
115
+ const results = Object.keys(lintResult).flatMap(file =>
116
+ lintResult[file].map(result => {
137
117
  if (options.json) {
138
118
  return {
139
119
  fileName: file,
140
- ...result
141
- }
142
- } else {
143
- return {
144
- file: file,
145
- lineNumber: result.lineNumber,
146
- column: (result.errorRange && result.errorRange[0]) || 0,
147
- names: result.ruleNames.join('/'),
148
- description: result.ruleDescription +
149
- (result.errorDetail ? ' [' + result.errorDetail + ']' : '') +
150
- (result.errorContext ? ' [Context: "' + result.errorContext + '"]' : '')
120
+ ...result
151
121
  };
152
122
  }
153
- });
154
- }));
155
-
123
+
124
+ return {
125
+ file: file,
126
+ lineNumber: result.lineNumber,
127
+ column: (result.errorRange && result.errorRange[0]) || 0,
128
+ names: result.ruleNames.join('/'),
129
+ description: result.ruleDescription + (result.errorDetail ? ' [' + result.errorDetail + ']' : '') + (result.errorContext ? ' [Context: "' + result.errorContext + '"]' : '')
130
+ };
131
+ })
132
+ );
133
+
156
134
  let lintResultString = '';
157
135
  if (results.length > 0) {
158
136
  if (options.json) {
159
- results.sort((a, b) => {
160
- return a.fileName.localeCompare(b.fileName) || a.lineNumber - b.lineNumber ||
161
- a.ruleDescription.localeCompare(b.ruleDescription);
162
- });
137
+ results.sort((a, b) => a.fileName.localeCompare(b.fileName) || a.lineNumber - b.lineNumber || a.ruleDescription.localeCompare(b.ruleDescription));
163
138
  lintResultString = JSON.stringify(results, null, 2);
164
139
  } else {
165
- results.sort((a, b) => {
166
- return a.file.localeCompare(b.file) || a.lineNumber - b.lineNumber ||
167
- a.names.localeCompare(b.names) || a.description.localeCompare(b.description);
168
- });
169
-
170
- lintResultString = results.map(result => {
171
- const {file, lineNumber, column, names, description} = result;
172
- const columnText = column ? `:${column}` : '';
173
- return `${file}:${lineNumber}${columnText} ${names} ${description}`;
174
- }).join('\n');
140
+ results.sort((a, b) => a.file.localeCompare(b.file) || a.lineNumber - b.lineNumber || a.names.localeCompare(b.names) || a.description.localeCompare(b.description));
141
+
142
+ lintResultString = results
143
+ .map(result => {
144
+ const {file, lineNumber, column, names, description} = result;
145
+ const columnText = column ? `:${column}` : '';
146
+ return `${file}:${lineNumber}${columnText} ${names} ${description}`;
147
+ })
148
+ .join('\n');
175
149
  }
150
+
176
151
  // Note: process.exit(1) will end abruptly, interrupting asynchronous IO
177
152
  // streams (e.g., when the output is being piped). Just set the exit code
178
153
  // and let the program terminate normally.
179
154
  // @see {@link https://nodejs.org/dist/latest-v8.x/docs/api/process.html#process_process_exit_code}
180
155
  // @see {@link https://github.com/igorshubovych/markdownlint-cli/pull/29#issuecomment-343535291}
181
- process.exitCode = 1;
156
+ process.exitCode = exitCodes.lintFindings;
182
157
  }
183
158
 
184
159
  if (options.output) {
185
- lintResultString = lintResultString.length > 0 ?
186
- lintResultString + os.EOL :
187
- lintResultString;
160
+ lintResultString = lintResultString.length > 0 ? lintResultString + os.EOL : lintResultString;
188
161
  try {
189
162
  fs.writeFileSync(options.output, lintResultString);
190
163
  } catch (error) {
191
164
  console.warn('Cannot write to output file ' + options.output + ': ' + error.message);
192
- process.exitCode = 2;
165
+ process.exitCode = exitCodes.failedToWriteOutputFile;
193
166
  }
194
- } else if (lintResultString) {
167
+ } else if (lintResultString && !options.quiet) {
195
168
  console.error(lintResultString);
196
169
  }
197
170
  }
@@ -212,8 +185,11 @@ program
212
185
  .option('-j, --json', 'write issues in json format')
213
186
  .option('-o, --output [outputFile]', 'write issues to file (no console)')
214
187
  .option('-p, --ignore-path [file]', 'path to file with ignore pattern(s)')
215
- .option('-r, --rules [file|directory|glob|package]', 'custom rule files', concatArray, [])
216
- .option('-s, --stdin', 'read from STDIN (does not work with files)');
188
+ .option('-q, --quiet', 'do not write issues to STDOUT')
189
+ .option('-r, --rules [file|directory|glob|package]', 'include custom rule files', concatArray, [])
190
+ .option('-s, --stdin', 'read from STDIN (does not work with files)')
191
+ .option('--enable [rules...]', 'Enable certain rules, e.g. --enable MD013 MD041')
192
+ .option('--disable [rules...]', 'Disable certain rules, e.g. --disable MD013 MD041');
217
193
 
218
194
  program.parse(process.argv);
219
195
 
@@ -241,12 +217,10 @@ function tryResolvePath(filepath) {
241
217
  }
242
218
 
243
219
  function loadCustomRules(rules) {
244
- return flatten(rules.map(function (rule) {
220
+ return rules.flatMap(rule => {
245
221
  try {
246
222
  const resolvedPath = [tryResolvePath(rule)];
247
- const fileList = flatten(prepareFileList(resolvedPath, ['js']).map(function (filepath) {
248
- return require(filepath.absolute);
249
- }));
223
+ const fileList = prepareFileList(resolvedPath, ['js']).flatMap(filepath => require(filepath.absolute));
250
224
  if (fileList.length === 0) {
251
225
  throw new Error('No such rule');
252
226
  }
@@ -254,9 +228,9 @@ function loadCustomRules(rules) {
254
228
  return fileList;
255
229
  } catch (error) {
256
230
  console.error('Cannot load custom rule ' + rule + ': ' + error.message);
257
- process.exit(3);
231
+ return process.exit(exitCodes.failedToLoadCustomRules);
258
232
  }
259
- }));
233
+ });
260
234
  }
261
235
 
262
236
  let ignorePath = '.markdownlintignore';
@@ -274,19 +248,26 @@ if (existsSync(ignorePath)) {
274
248
  ignoreFilter = fileInfo => !ignoreInstance.ignores(fileInfo.relative);
275
249
  }
276
250
 
277
- const files = prepareFileList(program.args, ['md', 'markdown'])
278
- .filter(value => ignoreFilter(value));
251
+ const files = prepareFileList(program.args, ['md', 'markdown']).filter(value => ignoreFilter(value));
279
252
  const ignores = prepareFileList(options.ignore, ['md', 'markdown'], files);
280
253
  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
- });
254
+ const diff = files.filter(file => !ignores.some(ignore => ignore.absolute === file.absolute)).map(paths => paths.original);
286
255
 
287
256
  function lintAndPrint(stdin, files) {
288
257
  files = files || [];
289
258
  const config = readConfiguration(options.config);
259
+
260
+ for (const rule of options.enable || []) {
261
+ // Leave default values in place if rule is an object
262
+ if (!config[rule]) {
263
+ config[rule] = true;
264
+ }
265
+ }
266
+
267
+ for (const rule of options.disable || []) {
268
+ config[rule] = false;
269
+ }
270
+
290
271
  const lintOptions = {
291
272
  config,
292
273
  customRules,
@@ -297,6 +278,7 @@ function lintAndPrint(stdin, files) {
297
278
  stdin
298
279
  };
299
280
  }
281
+
300
282
  if (options.json) {
301
283
  lintOptions.resultVersion = 3;
302
284
  }
@@ -325,11 +307,18 @@ function lintAndPrint(stdin, files) {
325
307
  printResult(lintResult);
326
308
  }
327
309
 
328
- if ((files.length > 0) && !options.stdin) {
329
- lintAndPrint(null, diff);
330
- } else if ((files.length === 0) && options.stdin && !options.fix) {
331
- const getStdin = require('get-stdin');
332
- getStdin().then(lintAndPrint);
333
- } else {
334
- program.help();
310
+ try {
311
+ if (files.length > 0 && !options.stdin) {
312
+ lintAndPrint(null, diff);
313
+ } else if (files.length === 0 && options.stdin && !options.fix) {
314
+ // eslint-disable-next-line node/no-unsupported-features/es-syntax
315
+ import('get-stdin')
316
+ .then(module => module.default())
317
+ .then(lintAndPrint);
318
+ } else {
319
+ program.help();
320
+ }
321
+ } catch (error) {
322
+ console.error(error);
323
+ process.exit(exitCodes.unexpectedError);
335
324
  }
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "markdownlint-cli",
3
- "version": "0.28.1",
3
+ "version": "0.31.1",
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": ">=10"
10
+ "node": ">=12"
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,46 +37,52 @@
37
37
  },
38
38
  "homepage": "https://github.com/igorshubovych/markdownlint-cli#readme",
39
39
  "dependencies": {
40
- "commander": "~8.0.0",
41
- "deep-extend": "~0.6.0",
42
- "get-stdin": "~8.0.0",
43
- "glob": "~7.1.7",
44
- "ignore": "~5.1.8",
40
+ "commander": "~9.0.0",
41
+ "get-stdin": "~9.0.0",
42
+ "glob": "~7.2.0",
43
+ "ignore": "~5.2.0",
45
44
  "js-yaml": "^4.1.0",
46
45
  "jsonc-parser": "~3.0.0",
47
- "lodash.differencewith": "~4.5.0",
48
- "lodash.flatten": "~4.4.0",
49
- "markdownlint": "~0.23.1",
50
- "markdownlint-rule-helpers": "~0.14.0",
51
- "minimatch": "~3.0.4",
52
- "minimist": "~1.2.5",
46
+ "markdownlint": "~0.25.1",
47
+ "markdownlint-rule-helpers": "~0.16.0",
48
+ "minimatch": "~3.0.5",
53
49
  "run-con": "~1.2.10"
54
50
  },
55
51
  "devDependencies": {
56
- "ava": "^3.15.0",
57
- "execa": "^5.1.1",
58
- "husky": "^7.0.1",
59
- "tap-growl": "^3.0.0",
52
+ "ava": "^4.0.1",
53
+ "execa": "^6.0.0",
60
54
  "test-rule-package": "./test/custom-rules/test-rule-package",
61
- "xo": "^0.42.0"
55
+ "xo": "^0.47.0"
62
56
  },
63
57
  "xo": {
58
+ "prettier": true,
64
59
  "space": true,
65
60
  "rules": {
61
+ "comma-dangle": 0,
66
62
  "linebreak-style": 0,
67
63
  "no-var": 0,
68
64
  "prefer-arrow-callback": 0,
69
65
  "promise/prefer-await-to-then": 0,
70
66
  "object-shorthand": 0,
67
+ "unicorn/prefer-module": 0,
71
68
  "unicorn/prefer-ternary": 0
72
69
  }
73
70
  },
71
+ "prettier": {
72
+ "arrowParens": "avoid",
73
+ "bracketSpacing": false,
74
+ "endOfLine": "auto",
75
+ "printWidth": 1000,
76
+ "singleQuote": true,
77
+ "trailingComma": "none"
78
+ },
74
79
  "ava": {
75
80
  "files": [
76
81
  "test/**/*.js",
77
82
  "!test/custom-rules/**/*.js",
78
83
  "!test/md043-config.js"
79
84
  ],
80
- "failFast": true
85
+ "failFast": true,
86
+ "workerThreads": false
81
87
  }
82
88
  }