1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const CLIEngine = require("../cli-engine"),
|
13 | globUtils = require("./glob-utils"),
|
14 | baseDefaultOptions = require("../../conf/default-cli-options");
|
15 |
|
16 | const debug = require("debug")("eslint:source-code-utils");
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | function getSourceCodeOfFile(filename, options) {
|
30 | debug("getting sourceCode of", filename);
|
31 | const opts = Object.assign({}, options, { rules: {} });
|
32 | const cli = new CLIEngine(opts);
|
33 | const results = cli.executeOnFiles([filename]);
|
34 |
|
35 | if (results && results.results[0] && results.results[0].messages[0] && results.results[0].messages[0].fatal) {
|
36 | const msg = results.results[0].messages[0];
|
37 |
|
38 | throw new Error(`(${filename}:${msg.line}:${msg.column}) ${msg.message}`);
|
39 | }
|
40 | const sourceCode = cli.linter.getSourceCode();
|
41 |
|
42 | return sourceCode;
|
43 | }
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 |
|
63 | function getSourceCodeOfFiles(patterns, providedOptions, providedCallback) {
|
64 | const sourceCodes = {};
|
65 | const globPatternsList = typeof patterns === "string" ? [patterns] : patterns;
|
66 | let options, callback;
|
67 |
|
68 | const defaultOptions = Object.assign({}, baseDefaultOptions, { cwd: process.cwd() });
|
69 |
|
70 | if (typeof providedOptions === "undefined") {
|
71 | options = defaultOptions;
|
72 | callback = null;
|
73 | } else if (typeof providedOptions === "function") {
|
74 | callback = providedOptions;
|
75 | options = defaultOptions;
|
76 | } else if (typeof providedOptions === "object") {
|
77 | options = Object.assign({}, defaultOptions, providedOptions);
|
78 | callback = providedCallback;
|
79 | }
|
80 | debug("constructed options:", options);
|
81 |
|
82 | const filenames = globUtils.listFilesToProcess(globPatternsList, options)
|
83 | .filter(fileInfo => !fileInfo.ignored)
|
84 | .reduce((files, fileInfo) => files.concat(fileInfo.filename), []);
|
85 |
|
86 | if (filenames.length === 0) {
|
87 | debug(`Did not find any files matching pattern(s): ${globPatternsList}`);
|
88 | }
|
89 | filenames.forEach(filename => {
|
90 | const sourceCode = getSourceCodeOfFile(filename, options);
|
91 |
|
92 | if (sourceCode) {
|
93 | debug("got sourceCode of", filename);
|
94 | sourceCodes[filename] = sourceCode;
|
95 | }
|
96 | if (callback) {
|
97 | callback(filenames.length);
|
98 | }
|
99 | });
|
100 | return sourceCodes;
|
101 | }
|
102 |
|
103 | module.exports = {
|
104 | getSourceCodeOfFiles
|
105 | };
|