UNPKG

7.29 kBJavaScriptView Raw
1/*
2 * Copyright (C) 2016 salesforce.com, inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17"use strict";
18
19var glob = require('glob');
20var path = require('path');
21var fs = require('fs');
22var cli = require('heroku-cli-util');
23var linter = require('eslint').linter;
24var defaultConfig = require('./config');
25var defaultStyle = require('./code-style-rules');
26var objectAssign = require('object-assign');
27var formatter = require('eslint-friendly-formatter');
28
29var SINGLETON_FILE_REGEXP = /(Controller|Renderer|Helper|Provider|Test|Model)\.js$/;
30
31function noop() {}
32
33// this computes the first position after all the comments (multi-line and single-line)
34// from the top of the code
35function afterCommentsPosition(code) {
36 var position = 0;
37 var match;
38 do {
39 // /\*.*?\*/
40 match = code.match(/^(\s*(\/\*([\s\S]*?)\*\/)?\s*)/);
41 if (!match || !match[1]) {
42 match = code.match(/^(\s*\/\/.*\s*)/);
43 }
44 if (match && match[1]) {
45 position += match[1].length;
46 code = code.slice(match[1].length);
47 }
48 } while (match);
49 return position;
50}
51
52function processSingletonCode(code) {
53 // transform `({...})` into `"use strict"; exports = ({...});`
54 var pos = afterCommentsPosition(code);
55 if (code.charAt(pos) === '(') {
56 code = code.slice(0, pos) + '"use strict"; exports = ' + code.slice(pos);
57 pos = code.lastIndexOf(')') + 1;
58 if (code.charAt(pos) !== ';') {
59 code = code.slice(0, pos) + ';' + code.slice(pos);
60 }
61 }
62 return code;
63}
64
65function processFunctionCode(code) {
66 // transform `function () {}` into `"use strict"; exports = function () {};`
67 var pos = afterCommentsPosition(code);
68 if (code.indexOf('function', pos) === pos) {
69 code = code.slice(0, pos) + '"use strict"; exports = ' + code.slice(pos);
70 pos = code.lastIndexOf('}') + 1;
71 if (code.charAt(pos) !== ';') {
72 code = code.slice(0, pos) + ';' + code.slice(pos);
73 }
74 }
75 return code;
76}
77
78function process(src, config, options) {
79 var messages = linter.verify(src, config, {
80 allowInlineConfig: true, // TODO: internal code should be linted with this set to false
81 quiet: true
82 });
83
84 if (!options.verbose) {
85 messages = messages.filter(function (msg) {
86 return msg.severity > 1;
87 });
88 }
89
90 // eslint docs say that linter.verify will return null if no errors are found,
91 // but it actually returns an empty array. Also it is possible
92 // that the filter above will return an empty array.
93 //
94 // In either case an empty result should return null,
95 // not an empty array
96 if(messages.length > 0){
97 return messages;
98 } else {
99 return null
100 }
101}
102
103module.exports = function (cwd, opts, context) {
104 // No log, debug or warn functions if --json option is passed
105 var log = opts.json ? noop : cli.log;
106 var debug = opts.json ? noop : cli.debug;
107 var warn = opts.json ? noop : cli.warn;
108
109 // Lint return result
110 var isSuccess = true;
111
112 var ignore = [
113 // these are the things that we know for sure we never want to inspect
114 '**/node_modules/**',
115 '**/jsdoc/**',
116 '**/htdocs/**',
117 '**/invalidTest/**',
118 '**/purposelyInvalid/**',
119 '**/invalidTestData/**',
120 '**/validationTest/**',
121 '**/lintTest/**',
122 '**/target/**',
123 '**/parseError/**',
124 '**/*.junk.js',
125 '**/*_mock?.js'
126 ].concat(opts.ignore ? [opts.ignore] : []);
127
128 var globOptions = {
129 silent: true,
130 cwd: cwd,
131 nodir: true,
132 realpath: true,
133 ignore: ignore
134 };
135
136 var patterns = [opts.files || '**/*.js'];
137
138 var config = {};
139 objectAssign(config, defaultConfig);
140 config.rules = objectAssign({}, defaultConfig.rules);
141
142 if (opts.config) {
143 log('Applying custom rules from ' + opts.config);
144 var customStyle = require(path.join(context.cwd, opts.config));
145 if (customStyle && customStyle.rules) {
146 Object.keys(customStyle.rules).forEach(function (name) {
147 if (defaultStyle.rules.hasOwnProperty(name)) {
148 config.rules[name] = customStyle.rules[name];
149 debug(' -> Rule: ' + name + ' is now set to ' + JSON.stringify(config.rules[name]));
150 } else {
151 debug(' -> Ignoring non-style rule: ' + name);
152 }
153 });
154 }
155 }
156
157 // Using local debug function for non-json text
158 debug('Search for "' + patterns.join('" or "') + '" in folder "' + cwd + '"');
159 debug(' -> Ignoring: ' + ignore.join(','));
160
161 var files = [];
162 // for blt-like structures we look for aura structures
163 // and we search from there to narrow down the search.
164 var folders = glob.sync('**/*.{app,cmp,lib}', globOptions);
165 folders = folders.map(function (v) {
166 return path.dirname(v);
167 });
168 folders = folders.filter(function (v, i) {
169 return folders.indexOf(v) === i;
170 });
171
172 folders.forEach(function (folder) {
173 globOptions.cwd = folder;
174 patterns.forEach(function (pattern) {
175 files = files.concat(glob.sync(pattern, globOptions));
176 });
177 });
178
179 // deduping...
180 files = files.filter(function (v, i) {
181 return files.indexOf(v) === i;
182 });
183
184 if (files.length) {
185 log('Found ' + files.length + ' matching files.\n----------------');
186
187 var output = [];
188 files.forEach(function (file) {
189 var source = fs.readFileSync(file, 'utf8');
190
191 // in some cases, we need to massage the source before linting it
192 if (SINGLETON_FILE_REGEXP.test(file)) {
193 source = processSingletonCode(source);
194 } else {
195 source = processFunctionCode(source);
196 }
197
198 var messages = process(source, config, opts);
199 if (messages) {
200 if (opts.json) {
201 output.push({
202 file: file,
203 result: messages
204 })
205 } else {
206 log('FILE: ' + file + ':');
207 log(formatter([{
208 messages: messages,
209 filePath: '<input>'
210 }]).replace(/<input>/g, 'Line'));
211 }
212 if ( messages.length > 0 ) {
213 isSuccess = false;
214 }
215 }
216 });
217
218 // printout JSON string to STDOUT
219 if (opts.json) {
220 cli.log(JSON.stringify(output, null, 4));
221 }
222 } else {
223 warn('Did not find matching files.');
224 }
225
226 return isSuccess;
227
228}