1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 | "use strict";
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 | const CLIEngine = require("../cli-engine"),
|
13 | globUtil = require("./glob-util"),
|
14 | baseDefaultOptions = require("../../conf/default-cli-options");
|
15 |
|
16 | const debug = require("debug")("eslint:source-code-util");
|
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 |
|
64 |
|
65 | function getSourceCodeOfFiles(patterns, options, cb) {
|
66 | const sourceCodes = {};
|
67 | let opts;
|
68 |
|
69 | if (typeof patterns === "string") {
|
70 | patterns = [patterns];
|
71 | }
|
72 |
|
73 | const defaultOptions = Object.assign({}, baseDefaultOptions, { cwd: process.cwd() });
|
74 |
|
75 | if (typeof options === "undefined") {
|
76 | opts = defaultOptions;
|
77 | } else if (typeof options === "function") {
|
78 | cb = options;
|
79 | opts = defaultOptions;
|
80 | } else if (typeof options === "object") {
|
81 | opts = Object.assign({}, defaultOptions, options);
|
82 | }
|
83 | debug("constructed options:", opts);
|
84 | patterns = globUtil.resolveFileGlobPatterns(patterns, opts);
|
85 |
|
86 | const filenames = globUtil.listFilesToProcess(patterns, opts)
|
87 | .filter(fileInfo => !fileInfo.ignored)
|
88 | .reduce((files, fileInfo) => files.concat(fileInfo.filename), []);
|
89 |
|
90 | if (filenames.length === 0) {
|
91 | debug(`Did not find any files matching pattern(s): ${patterns}`);
|
92 | }
|
93 | filenames.forEach(filename => {
|
94 | const sourceCode = getSourceCodeOfFile(filename, opts);
|
95 |
|
96 | if (sourceCode) {
|
97 | debug("got sourceCode of", filename);
|
98 | sourceCodes[filename] = sourceCode;
|
99 | }
|
100 | if (cb) {
|
101 | cb(filenames.length);
|
102 | }
|
103 | });
|
104 | return sourceCodes;
|
105 | }
|
106 |
|
107 | module.exports = {
|
108 | getSourceCodeOfFiles
|
109 | };
|