]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/developer-guide/nodejs-api.md
ee1a7a449705ca31690ea732b6b24b1205fec182
[pve-eslint.git] / eslint / docs / developer-guide / nodejs-api.md
1 # Node.js API
2
3 While ESLint is designed to be run on the command line, it's possible to use ESLint programmatically through the Node.js API. The purpose of the Node.js API is to allow plugin and tool authors to use the ESLint functionality directly, without going through the command line interface.
4
5 **Note:** Use undocumented parts of the API at your own risk. Only those parts that are specifically mentioned in this document are approved for use and will remain stable and reliable. Anything left undocumented is unstable and may change or be removed at any point.
6
7 ## Table of Contents
8
9 * [SourceCode](#sourcecode)
10 * [splitLines()](#sourcecode-splitlines)
11 * [Linter](#linter)
12 * [verify()](#linter-verify)
13 * [verifyAndFix()](#linter-verifyandfix)
14 * [defineRule()](#linter-definerule)
15 * [defineRules()](#linter-definerules)
16 * [getRules()](#linter-getrules)
17 * [defineParser()](#linter-defineparser)
18 * [version](#linter-version)
19 * [linter (deprecated)](#linter-1)
20 * [CLIEngine](#cliengine)
21 * [executeOnFiles()](#cliengine-executeonfiles)
22 * [resolveFileGlobPatterns()](#cliengine-resolvefileglobpatterns)
23 * [getConfigForFile()](#cliengine-getconfigforfile)
24 * [executeOnText()](#cliengine-executeontext)
25 * [addPlugin()](#cliengine-addplugin)
26 * [isPathIgnored()](#cliengine-ispathignored)
27 * [getFormatter()](#cliengine-getformatter)
28 * [getErrorResults()](#cliengine-geterrorresults)
29 * [outputFixes()](#cliengine-outputfixes)
30 * [getRules()](#cliengine-getrules)
31 * [version](#cliengine-version)
32 * [RuleTester](#ruletester)
33 * [Customizing RuleTester](#customizing-ruletester)
34 * [Deprecated APIs](#deprecated-apis)
35
36 ## SourceCode
37
38 The `SourceCode` type represents the parsed source code that ESLint executes on. It's used internally in ESLint and is also available so that already-parsed code can be used. You can create a new instance of `SourceCode` by passing in the text string representing the code and an abstract syntax tree (AST) in [ESTree](https://github.com/estree/estree) format (including location information, range information, comments, and tokens):
39
40 ```js
41 const SourceCode = require("eslint").SourceCode;
42
43 const code = new SourceCode("var foo = bar;", ast);
44 ```
45
46 The `SourceCode` constructor throws an error if the AST is missing any of the required information.
47
48 The `SourceCode` constructor strips Unicode BOM.
49 Please note the AST also should be parsed from stripped text.
50
51 ```js
52 const SourceCode = require("eslint").SourceCode;
53
54 const code = new SourceCode("\uFEFFvar foo = bar;", ast);
55
56 assert(code.hasBOM === true);
57 assert(code.text === "var foo = bar;");
58 ```
59
60 ### SourceCode#splitLines()
61
62 This is a static function on `SourceCode` that is used to split the source code text into an array of lines.
63
64 ```js
65 const SourceCode = require("eslint").SourceCode;
66
67 const code = "var a = 1;\nvar b = 2;"
68
69 // split code into an array
70 const codeLines = SourceCode.splitLines(code);
71
72 /*
73 Value of codeLines will be
74 [
75 "var a = 1;",
76 "var b = 2;"
77 ]
78 */
79 ```
80
81 ## Linter
82
83 The `Linter` object does the actual evaluation of the JavaScript code. It doesn't do any filesystem operations, it simply parses and reports on the code. In particular, the `Linter` object does not process configuration objects or files.
84 The `Linter` is a constructor, and you can create a new instance by passing in the options you want to use. The available options are:
85
86 * `cwd` - Path to a directory that should be considered as the current working directory. It is accessible to rules by calling `context.getCwd()` (see [The Context Object](./working-with-rules.md#The-Context-Object)). If `cwd` is `undefined`, it will be normalized to `process.cwd()` if the global `process` object is defined (for example, in the Node.js runtime) , or `undefined` otherwise.
87
88 For example:
89
90 ```js
91 const Linter = require("eslint").Linter;
92 const linter1 = new Linter({ cwd: 'path/to/project' });
93 const linter2 = new Linter();
94 ```
95
96 In this example, rules run on `linter1` will get `path/to/project` when calling `context.getCwd()`.
97 Those run on `linter2` will get `process.cwd()` if the global `process` object is defined or `undefined` otherwise (e.g. on the browser https://eslint.org/demo).
98
99 ### Linter#verify
100
101 The most important method on `Linter` is `verify()`, which initiates linting of the given text. This method accepts three arguments:
102
103 * `code` - the source code to lint (a string or instance of `SourceCode`).
104 * `config` - a configuration object that has been processed and normalized by CLIEngine using eslintrc files and/or other configuration arguments.
105 * **Note**: If you want to lint text and have your configuration be read and processed, use CLIEngine's [`executeOnFiles`](#cliengineexecuteonfiles) or [`executeOnText`](#cliengineexecuteontext) instead.
106 * `options` - (optional) Additional options for this run.
107 * `filename` - (optional) the filename to associate with the source code.
108 * `preprocess` - (optional) A function that [Processors in Plugins](/docs/developer-guide/working-with-plugins.md#processors-in-plugins) documentation describes as the `preprocess` method.
109 * `postprocess` - (optional) A function that [Processors in Plugins](/docs/developer-guide/working-with-plugins.md#processors-in-plugins) documentation describes as the `postprocess` method.
110 * `filterCodeBlock` - (optional) A function that decides which code blocks the linter should adopt. The function receives two arguments. The first argument is the virtual filename of a code block. The second argument is the text of the code block. If the function returned `true` then the linter adopts the code block. If the function was omitted, the linter adopts only `*.js` code blocks. If you provided a `filterCodeBlock` function, it overrides this default behavior, so the linter doesn't adopt `*.js` code blocks automatically.
111 * `disableFixes` - (optional) when set to `true`, the linter doesn't make either the `fix` or `suggestions` property of the lint result.
112 * `allowInlineConfig` - (optional) set to `false` to disable inline comments from changing ESLint rules.
113 * `reportUnusedDisableDirectives` - (optional) when set to `true`, adds reported errors for unused `eslint-disable` directives when no problems would be reported in the disabled area anyway.
114
115 If the third argument is a string, it is interpreted as the `filename`.
116
117 You can call `verify()` like this:
118
119 ```js
120 const Linter = require("eslint").Linter;
121 const linter = new Linter();
122
123 const messages = linter.verify("var foo;", {
124 rules: {
125 semi: 2
126 }
127 }, { filename: "foo.js" });
128
129 // or using SourceCode
130
131 const Linter = require("eslint").Linter,
132 linter = new Linter(),
133 SourceCode = require("eslint").SourceCode;
134
135 const code = new SourceCode("var foo = bar;", ast);
136
137 const messages = linter.verify(code, {
138 rules: {
139 semi: 2
140 }
141 }, { filename: "foo.js" });
142 ```
143
144 The `verify()` method returns an array of objects containing information about the linting warnings and errors. Here's an example:
145
146 ```js
147 {
148 fatal: false,
149 ruleId: "semi",
150 severity: 2,
151 line: 1,
152 column: 23,
153 message: "Expected a semicolon.",
154 fix: {
155 range: [1, 15],
156 text: ";"
157 }
158 }
159 ```
160
161 The information available for each linting message is:
162
163 * `column` - the column on which the error occurred.
164 * `fatal` - usually omitted, but will be set to true if there's a parsing error (not related to a rule).
165 * `line` - the line on which the error occurred.
166 * `message` - the message that should be output.
167 * `nodeType` - the node or token type that was reported with the problem.
168 * `ruleId` - the ID of the rule that triggered the messages (or null if `fatal` is true).
169 * `severity` - either 1 or 2, depending on your configuration.
170 * `endColumn` - the end column of the range on which the error occurred (this property is omitted if it's not range).
171 * `endLine` - the end line of the range on which the error occurred (this property is omitted if it's not range).
172 * `fix` - an object describing the fix for the problem (this property is omitted if no fix is available).
173 * `suggestions` - an array of objects describing possible lint fixes for editors to programmatically enable (see details in the [Working with Rules docs](./working-with-rules.md#providing-suggestions)).
174
175 Linting message objects have a deprecated `source` property. This property **will be removed** from linting messages in an upcoming breaking release. If you depend on this property, you should now use the `SourceCode` instance provided by the linter.
176
177 You can also get an instance of the `SourceCode` object used inside of `linter` by using the `getSourceCode()` method:
178
179 ```js
180 const Linter = require("eslint").Linter;
181 const linter = new Linter();
182
183 const messages = linter.verify("var foo = bar;", {
184 rules: {
185 semi: 2
186 }
187 }, { filename: "foo.js" });
188
189 const code = linter.getSourceCode();
190
191 console.log(code.text); // "var foo = bar;"
192 ```
193
194 In this way, you can retrieve the text and AST used for the last run of `linter.verify()`.
195
196 ### Linter#verifyAndFix()
197
198 This method is similar to verify except that it also runs autofixing logic, similar to the `--fix` flag on the command line. The result object will contain the autofixed code, along with any remaining linting messages for the code that were not autofixed.
199
200 ```js
201 const Linter = require("eslint").Linter;
202 const linter = new Linter();
203
204 const messages = linter.verifyAndFix("var foo", {
205 rules: {
206 semi: 2
207 }
208 });
209 ```
210
211 Output object from this method:
212
213 ```js
214 {
215 fixed: true,
216 output: "var foo;",
217 messages: []
218 }
219 ```
220
221 The information available is:
222
223 * `fixed` - True, if the code was fixed.
224 * `output` - Fixed code text (might be the same as input if no fixes were applied).
225 * `messages` - Collection of all messages for the given code (It has the same information as explained above under `verify` block).
226
227 ### Linter#defineRule
228
229 Each `Linter` instance holds a map of rule names to loaded rule objects. By default, all ESLint core rules are loaded. If you want to use `Linter` with custom rules, you should use the `defineRule` method to register your rules by ID.
230
231 ```js
232 const Linter = require("eslint").Linter;
233 const linter = new Linter();
234
235 linter.defineRule("my-custom-rule", {
236 // (an ESLint rule)
237
238 create(context) {
239 // ...
240 }
241 });
242
243 const results = linter.verify("// some source text", { rules: { "my-custom-rule": "error" } });
244 ```
245
246 ### Linter#defineRules
247
248 This is a convenience method similar to `Linter#defineRule`, except that it allows you to define many rules at once using an object.
249
250 ```js
251 const Linter = require("eslint").Linter;
252 const linter = new Linter();
253
254 linter.defineRules({
255 "my-custom-rule": { /* an ESLint rule */ create() {} },
256 "another-custom-rule": { /* an ESLint rule */ create() {} }
257 });
258
259 const results = linter.verify("// some source text", {
260 rules: {
261 "my-custom-rule": "error",
262 "another-custom-rule": "warn"
263 }
264 });
265 ```
266
267 ### Linter#getRules
268
269 This method returns a map of all loaded rules.
270
271 ```js
272 const Linter = require("eslint").Linter;
273 const linter = new Linter();
274
275 linter.getRules();
276
277 /*
278 Map {
279 'accessor-pairs' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
280 'array-bracket-newline' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
281 ...
282 }
283 */
284 ```
285
286 ### Linter#defineParser
287
288 Each instance of `Linter` holds a map of custom parsers. If you want to define a parser programmatically, you can add this function
289 with the name of the parser as first argument and the [parser object](/docs/developer-guide/working-with-custom-parsers.md) as second argument. The default `"espree"` parser will already be loaded for every `Linter` instance.
290
291 ```js
292 const Linter = require("eslint").Linter;
293 const linter = new Linter();
294
295 linter.defineParser("my-custom-parser", {
296 parse(code, options) {
297 // ...
298 }
299 });
300
301 const results = linter.verify("// some source text", { parser: "my-custom-parser" });
302 ```
303
304 ### Linter#version/Linter.version
305
306 Each instance of `Linter` has a `version` property containing the semantic version number of ESLint that the `Linter` instance is from.
307
308 ```js
309 const Linter = require("eslint").Linter;
310 const linter = new Linter();
311
312 linter.version; // => '4.5.0'
313 ```
314
315 There is also a `Linter.version` property that you can read without instantiating `Linter`:
316
317 ```js
318 const Linter = require("eslint").Linter;
319
320 Linter.version; // => '4.5.0'
321 ```
322
323 ## linter
324
325 The `eslint.linter` object (deprecated) is an instance of the `Linter` class as defined [above](#linter). `eslint.linter` exists for backwards compatibility, but we do not recommend using it because any mutations to it are shared among every module that uses `eslint`. Instead, please create your own instance of `eslint.Linter`.
326
327 ```js
328 const linter = require("eslint").linter;
329
330 const messages = linter.verify("var foo;", {
331 rules: {
332 semi: 2
333 }
334 }, { filename: "foo.js" });
335 ```
336
337 Note: This API is deprecated as of 4.0.0.
338
339 ## CLIEngine
340
341 The primary Node.js API is `CLIEngine`, which is the underlying utility that runs the ESLint command line interface. This object will read the filesystem for configuration and file information but will not output any results. Instead, it allows you direct access to the important information so you can deal with the output yourself.
342
343 You can get a reference to the `CLIEngine` by doing the following:
344
345 ```js
346 const CLIEngine = require("eslint").CLIEngine;
347 ```
348
349 The `CLIEngine` is a constructor, and you can create a new instance by passing in the options you want to use. The available options are:
350
351 * `allowInlineConfig` - Set to `false` to disable the use of configuration comments (such as `/*eslint-disable*/`). Corresponds to `--no-inline-config`.
352 * `baseConfig` - Can optionally be set to a config object that has the same schema as `.eslintrc.*`. This will used as a default config, and will be merged with any configuration defined in `.eslintrc.*` files, with the `.eslintrc.*` files having precedence.
353 * `cache` - Operate only on changed files (default: `false`). Corresponds to `--cache`.
354 * `cacheFile` - Name of the file where the cache will be stored (default: `.eslintcache`). Corresponds to `--cache-file`. Deprecated: use `cacheLocation` instead.
355 * `cacheLocation` - Name of the file or directory where the cache will be stored (default: `.eslintcache`). Corresponds to `--cache-location`.
356 * `configFile` - The configuration file to use (default: null). If `useEslintrc` is true or not specified, this configuration will be merged with any configuration defined in `.eslintrc.*` files, with options in this configuration having precedence. Corresponds to `-c`.
357 * `cwd` - Path to a directory that should be considered as the current working directory.
358 * `envs` - An array of environments to load (default: empty array). Corresponds to `--env`. Note: This differs from `.eslintrc.*` / `baseConfig`, where instead the option is called `env` and is an object.
359 * `errorOnUnmatchedPattern` - Set to `false` to prevent errors when pattern is unmatched. Corresponds to `--no-error-on-unmatched-pattern`.
360 * `extensions` - An array of filename extensions that should be checked for code. The default is an array containing just `".js"`. Corresponds to `--ext`. It is only used in conjunction with directories, not with filenames, glob patterns or when using `executeOnText()`.
361 * `fix` - A boolean or a function (default: `false`). If a function, it will be passed each linting message and should return a boolean indicating whether the fix should be included with the output report (errors and warnings will not be listed if fixed). Files on disk are never changed regardless of the value of `fix`. To persist changes to disk, call [`outputFixes()`](#cliengineoutputfixes).
362 * `fixTypes` - An array of rule types for which fixes should be applied (default: `null`). This array acts like a filter, only allowing rules of the given types to apply fixes. Possible array values are `"problem"`, `"suggestion"`, and `"layout"`.
363 * `globals` - An array of global variables to declare (default: empty array). Corresponds to `--global`, and similarly supports passing `'name:true'` to denote a writeable global. Note: This differs from `.eslintrc.*` / `baseConfig`, where `globals` is an object.
364 * `ignore` - False disables use of `.eslintignore`, `ignorePath` and `ignorePattern` (default: true). Corresponds to `--no-ignore`.
365 * `ignorePath` - The ignore file to use instead of `.eslintignore` (default: null). Corresponds to `--ignore-path`.
366 * `ignorePattern` - Glob patterns for paths to ignore. String or array of strings.
367 * `parser` - Specify the parser to be used (default: `espree`). Corresponds to `--parser`.
368 * `parserOptions` - An object containing parser options (default: empty object). Corresponds to `--parser-options`.
369 * `plugins` - An array of plugins to load (default: empty array). Corresponds to `--plugin`.
370 * `reportUnusedDisableDirectives` - When set to `true`, adds reported errors for unused `eslint-disable` directives when no problems would be reported in the disabled area anyway (default: false). Corresponds to `--report-unused-disable-directives`.
371 * `resolvePluginsRelativeTo` - Determines the folder where plugins should be resolved from. Should be used when an integration installs plugins and uses those plugins to lint code on behalf of the end user. Corresponds to `--resolve-plugins-relative-to`.
372 * `rulePaths` - An array of directories to load custom rules from (default: empty array). Corresponds to `--rulesdir`.
373 * `rules` - An object of rules to use (default: null). Corresponds to `--rule`.
374 * `useEslintrc` - Set to false to disable use of `.eslintrc` files (default: true). Corresponds to `--no-eslintrc`.
375 * `globInputPaths` - Set to false to skip glob resolution of input file paths to lint (default: true). If false, each input file paths is assumed to be a non-glob path to an existing file.
376
377 To programmatically set `.eslintrc.*` options not supported above (such as `extends`,
378 `overrides` and `settings`), define them in a config object passed to `baseConfig` instead.
379
380 For example:
381
382 ```js
383 const CLIEngine = require("eslint").CLIEngine;
384
385 const cli = new CLIEngine({
386 baseConfig: {
387 extends: ["eslint-config-shared"],
388 settings: {
389 sharedData: "Hello"
390 }
391 },
392 envs: ["browser", "mocha"],
393 useEslintrc: false,
394 rules: {
395 semi: 2
396 }
397 });
398 ```
399
400 In this example, a new `CLIEngine` instance is created that extends a configuration called
401 `"eslint-config-shared"`, a setting named `"sharedData"` and two environments (`"browser"`
402 and `"mocha"`) are defined, loading of `.eslintrc` and `package.json` files are disabled,
403 and the `semi` rule enabled as an error. You can then call methods on `cli` and these options
404 will be used to perform the correct action.
405
406 Note: Currently `CLIEngine` does not validate options passed to it, but may start doing so in the future.
407
408 ### CLIEngine#executeOnFiles()
409
410 If you want to lint one or more files, use the `executeOnFiles()` method. This method accepts a single argument, which is an array of files and/or directories to traverse for files. You can pass the same values as you would using the ESLint command line interface, such as `"."` to search all JavaScript files in the current directory. Here's an example:
411
412 ```js
413 const CLIEngine = require("eslint").CLIEngine;
414
415 const cli = new CLIEngine({
416 envs: ["browser", "mocha"],
417 useEslintrc: false,
418 rules: {
419 semi: 2
420 }
421 });
422
423 // lint myfile.js and all files in lib/
424 const report = cli.executeOnFiles(["myfile.js", "lib/"]);
425 ```
426
427 The return value is an object containing the results of the linting operation. Here's an example of a report object:
428
429 ```js
430 {
431 results: [
432 {
433 filePath: "/Users/eslint/project/myfile.js",
434 messages: [{
435 ruleId: "semi",
436 severity: 2,
437 message: "Missing semicolon.",
438 line: 1,
439 column: 13,
440 nodeType: "ExpressionStatement",
441 fix: { range: [12, 12], text: ";" }
442 }, {
443 ruleId: "no-useless-escape",
444 severity: 1,
445 message: "disallow unnecessary escape characters",
446 line: 1,
447 column: 10,
448 nodeType: "ExpressionStatement",
449 suggestions: [{
450 desc: "Remove unnecessary escape. This maintains the current functionality.",
451 fix: { range: [9, 10], text: "" }
452 }, {
453 desc: "Escape backslash to include it in the RegExp.",
454 fix: { range: [9, 9], text: "\\" }
455 }]
456 }],
457 errorCount: 1,
458 warningCount: 1,
459 fixableErrorCount: 1,
460 fixableWarningCount: 0,
461 source: "\"use strict\"\n"
462 }
463 ],
464 errorCount: 1,
465 warningCount: 0,
466 fixableErrorCount: 1,
467 fixableWarningCount: 0,
468 usedDeprecatedRules: []
469 }
470 ```
471
472 You can also pass `fix: true` when instantiating the `CLIEngine` in order to have it figure out what fixes can be applied.
473
474 ```js
475 const CLIEngine = require("eslint").CLIEngine;
476
477 const cli = new CLIEngine({
478 envs: ["browser", "mocha"],
479 fix: true, // difference from last example
480 useEslintrc: false,
481 rules: {
482 semi: 2,
483 quotes: [2, "double"]
484 }
485 });
486
487 // lint myfile.js and all files in lib/
488 const report = cli.executeOnFiles(["myfile.js", "lib/"]);
489 ```
490
491 ```js
492 {
493 results: [
494 {
495 filePath: "/Users/eslint/project/myfile.js",
496 messages: [
497 {
498 ruleId: "semi",
499 severity: 2,
500 message: "Missing semicolon.",
501 line: 1,
502 column: 13,
503 nodeType: "ExpressionStatement",
504 fix: { range: [12, 12], text: ";" }
505 },
506 {
507 ruleId: "func-name-matching",
508 severity: 2,
509 message: "Function name `bar` should match variable name `foo`",
510 line: 2,
511 column: 5,
512 nodeType: "VariableDeclarator"
513 }
514 ],
515 errorCount: 2,
516 warningCount: 0,
517 fixableErrorCount: 1,
518 fixableWarningCount: 0,
519 output: "\"use strict\";\nvar foo = function bar() {};\nfoo();\n"
520 }
521 ],
522 errorCount: 2,
523 warningCount: 0,
524 fixableErrorCount: 1,
525 fixableWarningCount: 0,
526 usedDeprecatedRules: []
527 }
528 ```
529
530 If the operation ends with a parsing error, you will get a single message for this file, with `fatal: true` added as an extra property.
531
532 ```js
533 {
534 results: [
535 {
536 filePath: "./myfile.js",
537 messages: [
538 {
539 ruleId: null,
540 fatal: true,
541 severity: 2,
542 message: "Parsing error: Unexpected token foo",
543 line: 1,
544 column: 10
545 }
546 ],
547 errorCount: 1,
548 warningCount: 0,
549 fixableErrorCount: 0,
550 fixableWarningCount: 0,
551 source: "function foo() {}"
552 }
553 ],
554 errorCount: 1,
555 warningCount: 0,
556 fixableErrorCount: 0,
557 fixableWarningCount: 0,
558 usedDeprecatedRules: []
559 }
560 ```
561
562 The top-level report object has a `results` array containing all linting results for files that had warnings or errors (any files that did not produce a warning or error are omitted). Each file result includes:
563
564 * `filePath` - Path to the given file.
565 * `messages` - Array containing the result of calling `linter.verify()` on the given file.
566 * `errorCount` and `warningCount` - The exact number of errors and warnings respectively on the given file.
567 * `source` - The source code for the given file. This property is omitted if this file has no errors/warnings or if the `output` property is present.
568 * `output` - The source code for the given file with as many fixes applied as possible, so you can use that to rewrite the files if necessary. This property is omitted if no fix is available.
569
570 The top-level report object also has `errorCount` and `warningCount` which give the exact number of errors and warnings respectively on all the files. Additionally, `usedDeprecatedRules` signals any deprecated rules used and their replacement (if available). Specifically, it is array of objects with properties like so:
571
572 * `ruleId` - The name of the rule (e.g. `indent-legacy`).
573 * `replacedBy` - An array of rules that replace the deprecated rule (e.g. `["indent"]`).
574
575 Once you get a report object, it's up to you to determine how to output the results. Fixes will not be automatically applied to the files, even if you set `fix: true` when constructing the `CLIEngine` instance. To apply fixes to the files, call [`outputFixes`](#cliengineoutputfixes).
576
577 ### CLIEngine#resolveFileGlobPatterns()
578
579 You can pass filesystem-style or glob patterns to ESLint and have it function properly. In order to achieve this, ESLint must resolve non-glob patterns into glob patterns before determining which files to execute on. The `resolveFileGlobPatterns()` methods uses the current settings from `CLIEngine` to resolve non-glob patterns into glob patterns. Pass an array of patterns that might be passed to the ESLint CLI and it will return an array of glob patterns that mean the same thing. Here's an example:
580
581 ```js
582 const CLIEngine = require("eslint").CLIEngine;
583
584 const cli = new CLIEngine({
585 });
586
587 // pass an array of patterns
588 const globPatterns = cli.resolveFileGlobPatterns(["."]);
589 console.log(globPatterns[i]); // ["**/*.js"]
590 ```
591
592 ### CLIEngine#getConfigForFile()
593
594 If you want to retrieve a configuration object for a given file, use the `getConfigForFile()` method. This method accepts one argument, a file path, and returns an object represented the calculated configuration of the file. Here's an example:
595
596 ```js
597 const CLIEngine = require("eslint").CLIEngine;
598
599 const cli = new CLIEngine({
600 envs: ["browser", "mocha"],
601 useEslintrc: false,
602 rules: {
603 semi: 2
604 }
605 });
606
607 const config = cli.getConfigForFile("myfile.js");
608 ```
609
610 Once you have the configuration information, you can pass it into the `linter` object:
611
612 ```js
613 const CLIEngine = require("eslint").CLIEngine,
614 Linter = require("eslint").Linter;
615
616 const linter = new Linter();
617 const cli = new CLIEngine({
618 envs: ["browser", "mocha"],
619 useEslintrc: false,
620 rules: {
621 semi: 2
622 }
623 });
624
625 const config = cli.getConfigForFile("myfile.js");
626
627 const messages = linter.verify('var foo;', config);
628 ```
629
630 ### CLIEngine#executeOnText()
631
632 If you already have some text to lint, then you can use the `executeOnText()` method to lint that text. The linter will assume that the text is a file in the current working directory, and so will still obey any `.eslintrc` and `.eslintignore` files that may be present. Here's an example:
633
634 ```js
635 const CLIEngine = require("eslint").CLIEngine;
636
637 const cli = new CLIEngine({
638 envs: ["browser", "mocha"],
639 useEslintrc: false,
640 rules: {
641 semi: 2
642 }
643 });
644
645 // Lint the supplied text and optionally set a filename that is displayed in the report
646 const report = cli.executeOnText("var foo = 'bar';", "foo.js");
647
648 // In addition to the above, warn if the resolved file name is ignored.
649 const reportAndWarnOnIgnoredFile = cli.executeOnText("var foo = 'bar';", "foo.js", true);
650 ```
651
652 The `report` returned from `executeOnText()` is in the same format as from `executeOnFiles()`, but there is only ever one result in `report.results`.
653
654 If a filename in the optional second parameter matches a file that is configured to be ignored, then this function returns no errors or warnings. The method includes an additional optional boolean third parameter. When `true`, a resolved file name that is ignored will return a warning.
655
656 ### CLIEngine#addPlugin()
657
658 Loads a plugin from configuration object with specified name. Name can include plugin prefix ("eslint-plugin-")
659
660 ```js
661 const CLIEngine = require("eslint").CLIEngine;
662 const cli = new CLIEngine({
663 ignore: true
664 });
665 cli.addPlugin("eslint-plugin-processor", {
666 processors: {
667 ".txt": {
668 preprocess: function(text) {
669 return [text];
670 },
671 postprocess: function(messages) {
672 return messages[0];
673 }
674 }
675 }
676 });
677 ```
678
679 ### CLIEngine#isPathIgnored()
680
681 Checks if a given path is ignored by ESLint.
682
683 ```js
684 const CLIEngine = require("eslint").CLIEngine;
685
686 const cli = new CLIEngine({
687 ignore: true,
688 ignorePath: ".customIgnoreFile"
689 });
690
691 const isIgnored = cli.isPathIgnored("foo/bar.js");
692 ```
693
694 ### CLIEngine#getFormatter()
695
696 Retrieves a formatter, which you can then use to format a report object. The argument is either the name of a built-in formatter:
697
698 * "[checkstyle](../user-guide/formatters#checkstyle)"
699 * "[codeframe](../user-guide/formatters#codeframe)"
700 * "[compact](../user-guide/formatters#compact)"
701 * "[html](../user-guide/formatters#html)"
702 * "[jslint-xml](../user-guide/formatters#jslint-xml)"
703 * "[json](../user-guide/formatters#json)"
704 * "[junit](../user-guide/formatters#junit)"
705 * "[stylish](../user-guide/formatters#stylish)" (the default)
706 * "[table](../user-guide/formatters#table)"
707 * "[tap](../user-guide/formatters#tap)"
708 * "[unix](../user-guide/formatters#unix)"
709 * "[visualstudio](../user-guide/formatters#visualstudio)"
710
711 or the full path to a JavaScript file containing a custom formatter. You can also omit the argument to retrieve the default formatter.
712
713 ```js
714 const CLIEngine = require("eslint").CLIEngine;
715
716 const cli = new CLIEngine({
717 envs: ["browser", "mocha"],
718 useEslintrc: false,
719 rules: {
720 semi: 2
721 }
722 });
723
724 // lint myfile.js and all files in lib/
725 const report = cli.executeOnFiles(["myfile.js", "lib/"]);
726
727 // get the default formatter
728 const formatter = cli.getFormatter();
729
730 // Also could do...
731 // const formatter = cli.getFormatter("compact");
732 // const formatter = cli.getFormatter("./my/formatter.js");
733
734 // output to console
735 console.log(formatter(report.results));
736 ```
737
738 **Note:** Also available as a static function on `CLIEngine`.
739
740 ```js
741 // get the default formatter by calling the static function
742 const formatter = CLIEngine.getFormatter();
743 ```
744
745 **Important:** You must pass in the `results` property of the report. Passing in `report` directly will result in an error.
746
747 ### CLIEngine#getErrorResults()
748
749 This is a static function on `CLIEngine`. It can be used to filter out all the non error messages from the report object.
750
751 ```js
752 const CLIEngine = require("eslint").CLIEngine;
753
754 const cli = new CLIEngine({
755 envs: ["browser", "mocha"],
756 useEslintrc: false,
757 rules: {
758 semi: 2
759 }
760 });
761
762 // lint myfile.js and all files in lib/
763 const report = cli.executeOnFiles(["myfile.js", "lib/"]);
764
765 // only get the error messages
766 const errorReport = CLIEngine.getErrorResults(report.results)
767 ```
768
769 **Important:** You must pass in the `results` property of the report. Passing in `report` directly will result in an error.
770
771 ### CLIEngine#outputFixes()
772
773 This is a static function on `CLIEngine` that is used to output fixes from `report` to disk. It does by looking for files that have an `output` property in their results. Here's an example:
774
775 ```js
776 const CLIEngine = require("eslint").CLIEngine;
777
778 const cli = new CLIEngine({
779 envs: ["browser", "mocha"],
780 fix: true,
781 useEslintrc: false,
782 rules: {
783 semi: 2
784 }
785 });
786
787 // lint myfile.js and all files in lib/
788 const report = cli.executeOnFiles(["myfile.js", "lib/"]);
789
790 // output fixes to disk
791 CLIEngine.outputFixes(report);
792 ```
793
794 ### CLIEngine#getRules()
795
796 This method returns a map of all loaded rules. Under the hood, it calls [Linter#getRules](#lintergetrules).
797
798 ```js
799 const CLIEngine = require("eslint").CLIEngine;
800 const cli = new CLIEngine();
801
802 cli.getRules();
803
804 /*
805 Map {
806 'accessor-pairs' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
807 'array-bracket-newline' => { meta: { docs: [Object], schema: [Array] }, create: [Function: create] },
808 ...
809 }
810 */
811 ```
812
813
814 ### CLIEngine.version
815
816 `CLIEngine` has a static `version` property containing the semantic version number of ESLint that it comes from.
817
818 ```js
819 require("eslint").CLIEngine.version; // '4.5.0'
820 ```
821
822 ## RuleTester
823
824 `eslint.RuleTester` is a utility to write tests for ESLint rules. It is used internally for the bundled rules that come with ESLint, and it can also be used by plugins.
825
826 Example usage:
827
828 ```js
829 "use strict";
830
831 const rule = require("../../../lib/rules/my-rule"),
832 RuleTester = require("eslint").RuleTester;
833
834 const ruleTester = new RuleTester();
835
836 ruleTester.run("my-rule", rule, {
837 valid: [
838 {
839 code: "var foo = true",
840 options: [{ allowFoo: true }]
841 }
842 ],
843
844 invalid: [
845 {
846 code: "var invalidVariable = true",
847 errors: [{ message: "Unexpected invalid variable." }]
848 },
849 {
850 code: "var invalidVariable = true",
851 errors: [{ message: /^Unexpected.+variable/ }]
852 }
853 ]
854 });
855 ```
856
857 The `RuleTester` constructor accepts an optional object argument, which can be used to specify defaults for your test cases. For example, if all of your test cases use ES2015, you can set it as a default:
858
859 ```js
860 const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 2015 } });
861 ```
862
863 The `RuleTester#run()` method is used to run the tests. It should be passed the following arguments:
864
865 * The name of the rule (string)
866 * The rule object itself (see ["working with rules"](./working-with-rules))
867 * An object containing `valid` and `invalid` properties, each of which is an array containing test cases.
868
869 A test case is an object with the following properties:
870
871 * `code` (string, required): The source code that the rule should be run on
872 * `options` (array, optional): The options passed to the rule. The rule severity should not be included in this list.
873 * `filename` (string, optional): The filename for the given case (useful for rules that make assertions about filenames).
874
875 In addition to the properties above, invalid test cases can also have the following properties:
876
877 * `errors` (number or array, required): Asserts some properties of the errors that the rule is expected to produce when run on this code. If this is a number, asserts the number of errors produced. Otherwise, this should be a list of objects, each containing information about a single reported error. The following properties can be used for an error (all are optional):
878 * `message` (string/regexp): The message for the error
879 * `messageId` (string): The Id for the error. See [testing errors with messageId](#testing-errors-with-messageid) for details
880 * `data` (object): Placeholder data which can be used in combination with `messageId`
881 * `type` (string): The type of the reported AST node
882 * `line` (number): The 1-based line number of the reported location
883 * `column` (number): The 1-based column number of the reported location
884 * `endLine` (number): The 1-based line number of the end of the reported location
885 * `endColumn` (number): The 1-based column number of the end of the reported location
886 * `suggestions` (array): An array of objects with suggestion details to check. See [Testing Suggestions](#testing-suggestions) for details
887
888 If a string is provided as an error instead of an object, the string is used to assert the `message` of the error.
889 * `output` (string, required if the rule fixes code): Asserts the output that will be produced when using this rule for a single pass of autofixing (e.g. with the `--fix` command line flag). If this is `null`, asserts that none of the reported problems suggest autofixes.
890
891 Any additional properties of a test case will be passed directly to the linter as config options. For example, a test case can have a `parserOptions` property to configure parser behavior:
892
893 ```js
894 {
895 code: "let foo;",
896 parserOptions: { ecmaVersion: 2015 }
897 }
898 ```
899
900 If a valid test case only uses the `code` property, it can optionally be provided as a string containing the code, rather than an object with a `code` key.
901
902 #### Testing errors with `messageId`
903
904 If the rule under test uses `messageId`s, you can use `messageId` property in a test case to assert reported error's `messageId` instead of its `message`.
905
906 ```js
907 {
908 code: "let foo;",
909 errors: [{ messageId: "unexpected" }]
910 }
911 ```
912
913 For messages with placeholders, a test case can also use `data` property to additionally assert reported error's `message`.
914
915 ```js
916 {
917 code: "let foo;",
918 errors: [{ messageId: "unexpected", data: { name: "foo" } }]
919 }
920 ```
921
922 Please note that `data` in a test case does not assert `data` passed to `context.report`. Instead, it is used to form the expected message text which is then compared with the received `message`.
923
924 #### Testing Suggestions
925
926 Suggestions can be tested by defining a `suggestions` key on an errors object. The options to check for the suggestions are the following (all are optional):
927
928 * `desc` (string): The suggestion `desc` value
929 * `messageId` (string): The suggestion `messageId` value for suggestions that use `messageId`s
930 * `data` (object): Placeholder data which can be used in combination with `messageId`
931 * `output` (string): A code string representing the result of applying the suggestion fix to the input code
932
933 Example:
934
935 ```js
936 ruleTester.run("my-rule-for-no-foo", rule, {
937 valid: [],
938 invalid: [{
939 code: "var foo;",
940 errors: [{
941 suggestions: [{
942 desc: "Rename identifier 'foo' to 'bar'",
943 output: "var bar;"
944 }]
945 }]
946 }]
947 })
948 ```
949
950 `messageId` and `data` properties in suggestion test objects work the same way as in error test objects. See [testing errors with messageId](#testing-errors-with-messageid) for details.
951
952 ```js
953 ruleTester.run("my-rule-for-no-foo", rule, {
954 valid: [],
955 invalid: [{
956 code: "var foo;",
957 errors: [{
958 suggestions: [{
959 messageId: "renameFoo",
960 data: { newName: "bar" },
961 output: "var bar;"
962 }]
963 }]
964 }]
965 })
966 ```
967
968 ### Customizing RuleTester
969
970 `RuleTester` depends on two functions to run tests: `describe` and `it`. These functions can come from various places:
971
972 1. If `RuleTester.describe` and `RuleTester.it` have been set to function values, `RuleTester` will use `RuleTester.describe` and `RuleTester.it` to run tests. You can use this to customize the behavior of `RuleTester` to match a test framework that you're using.
973 1. Otherwise, if `describe` and `it` are present as globals, `RuleTester` will use `global.describe` and `global.it` to run tests. This allows `RuleTester` to work when using frameworks like [Mocha](https://mochajs.org/) without any additional configuration.
974 1. Otherwise, `RuleTester#run` will simply execute all of the tests in sequence, and will throw an error if one of them fails. This means you can simply execute a test file that calls `RuleTester.run` using `node`, without needing a testing framework.
975
976 `RuleTester#run` calls the `describe` function with two arguments: a string describing the rule, and a callback function. The callback calls the `it` function with a string describing the test case, and a test function. The test function will return successfully if the test passes, and throw an error if the test fails. (Note that this is the standard behavior for test suites when using frameworks like [Mocha](https://mochajs.org/); this information is only relevant if you plan to customize `RuleTester.it` and `RuleTester.describe`.)
977
978 Example of customizing `RuleTester`:
979
980 ```js
981 "use strict";
982
983 const RuleTester = require("eslint").RuleTester,
984 test = require("my-test-runner"),
985 myRule = require("../../../lib/rules/my-rule");
986
987 RuleTester.describe = function(text, method) {
988 RuleTester.it.title = text;
989 return method.call(this);
990 };
991
992 RuleTester.it = function(text, method) {
993 test(RuleTester.it.title + ": " + text, method);
994 };
995
996 // then use RuleTester as documented
997
998 const ruleTester = new RuleTester();
999
1000 ruleTester.run("my-rule", myRule, {
1001 valid: [
1002 // valid test cases
1003 ],
1004 invalid: [
1005 // invalid test cases
1006 ]
1007 })
1008 ```
1009
1010 ## Deprecated APIs
1011
1012 * `cli` - the `cli` object has been deprecated in favor of `CLIEngine`. As of v1.0.0, `cli` is no longer exported and should not be used by external tools.
1013 * `linter` - the `linter` object has been deprecated in favor of `Linter` as of v4.0.0.