-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathmain.js
More file actions
354 lines (313 loc) · 12.1 KB
/
main.js
File metadata and controls
354 lines (313 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
/*
* Copyright (c) 2012 Raymond Camden
*
* See the file LICENSE for copying permission.
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/* global define, brackets, $, JSHINT */
define(function (require, exports, module) {
"use strict";
var CodeInspection = brackets.getModule("language/CodeInspection"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
FileUtils = brackets.getModule("file/FileUtils"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
ProjectManager = brackets.getModule("project/ProjectManager"),
pm = PreferencesManager.getExtensionPrefs("jshint"),
defaultConfig;
pm.definePreference("options", "object", {"undef": true})
.on("change", function () {
defaultConfig.options = pm.get("options");
});
pm.definePreference("globals", "object", {})
.on("change", function () {
defaultConfig.globals = pm.get("globals");
});
defaultConfig = {
"options": pm.get("options"),
"globals": pm.get("globals")
};
require("jshint/jshint");
var PREF_SCAN_PROJECT_ONLY = "scanProjectOnly",
JSHINT_NAME = "JSHint";
pm.definePreference(PREF_SCAN_PROJECT_ONLY, "boolean", false)
.on("change", function () {
var val = pm.get(PREF_SCAN_PROJECT_ONLY);
if (_scanProjectOnly !== val) {
_scanProjectOnly = val;
CodeInspection.requestRun(JSHINT_NAME);
}
});
/**
* Extension preference which when set to true will limit the look up for configuration file
* to the project sub-tree. If false, the entire file tree will be searched. The default is
* false.
* @private
* @type {boolean}
*/
var _scanProjectOnly = pm.get(PREF_SCAN_PROJECT_ONLY);
/**
* @private
* @type {string}
*/
var _configFileName = ".jshintrc";
/**
* Synchronous linting entry point.
*
* @param {string} text File contents.
* @param {string} fullPath Absolute path to the file.
* @param {object} config JSHint configuration object.
*
* @return {object} Results of code inspection.
*/
function handleHinter(text, fullPath, config) {
// make sure that synchronous linter does not break
if (!config) {
config = {};
}
var resultJH = JSHINT(text,
$.extend({}, defaultConfig.options, config.options),
$.extend({}, defaultConfig.globals, config.globals));
if (!resultJH) {
var errors = JSHINT.errors,
result = { errors: [] },
i,
len;
for (i = 0, len = errors.length; i < len; i++) {
var messageOb = errors[i],
//default
type = CodeInspection.Type.ERROR;
// encountered an issue when jshint returned a null err
if (messageOb) {
var message;
if (messageOb.type !== undefined) {
// default is ERROR, override only if it differs
if (messageOb.type === "warning") {
type = CodeInspection.Type.WARNING;
}
}
message = messageOb.reason;
if (messageOb.code) {
message += " (" + messageOb.code + ")";
}
result.errors.push({
pos: {line: messageOb.line - 1, ch: messageOb.character - 1},
message: message,
type: type
});
}
}
return result;
} else {
return null;
}
}
/**
* Asynchronous linting entry point.
*
* @param {string} text File contents.
* @param {string} fullPath Absolute path to the file.
*
* @return {$.Promise} Promise to return results of code inspection.
*/
function handleHinterAsync(text, fullPath) {
var deferred = new $.Deferred();
_loadConfig(fullPath)
.then(_applyOverrides(fullPath))
.done(function (cfg) {
deferred.resolve(handleHinter(text, fullPath, cfg));
});
return deferred.promise();
}
/**
* Reads configuration file in the specified directory. Returns a promise for configuration object.
*
* @param {string} dir absolute path to a directory.
* @param {string} configFileName name of the configuration file (optional)
*
* @returns {$.Promise} a promise to return configuration object.
*/
function _readConfig(dir, configFileName) {
var result = new $.Deferred(),
file;
configFileName = configFileName || _configFileName;
file = FileSystem.getFileForPath(dir + configFileName);
file.read(function (err, content) {
if (!err) {
var cfg = {},
config;
try {
config = JSON.parse(removeComments(content));
} catch (e) {
console.error("JSHint: error parsing " + file.fullPath + ". Details: " + e);
result.reject(e);
return;
}
// Load any base config defined by "extends".
// The same functionality as in
// jslints -> cli.js -> loadConfig -> if (config['extends'])...
var baseConfigResult = $.Deferred();
if (config.extends) {
var extendFile = FileSystem.getFileForPath(dir + config.extends);
baseConfigResult = _readConfig(extendFile.parentPath, extendFile.name);
delete config.extends;
}
else {
baseConfigResult.resolve({});
}
baseConfigResult.done(function (baseConfig) {
cfg.globals = $.extend({}, baseConfig.globals, config.globals);
if (config.globals) { delete config.globals; }
cfg.options = $.extend({}, baseConfig.options, config);
result.resolve(cfg);
}).fail(function (e) {
result.reject(e);
});
} else {
result.reject(err);
}
});
return result.promise();
}
/**
* Applies per-file overrides, if any were provided in the configuration.
* Follows format supported in commit #df60b9c on JSHint repository:
* https://github.com/jshint/jshint/commit/df60b9c75daa4321a4d064fcab04e14692c94039
*
* @param {string} fullPath absolute path to the processed file
* @returns {Function} function that returns a promise for configuration object with overrides applied
*/
function _applyOverrides(fullPath) {
var basePath = ProjectManager.getProjectRoot().fullPath,
filePath = FileUtils.getRelativeFilename(basePath, fullPath);
return function (cfg) {
var bundle,
has = Object.prototype.hasOwnProperty.call.bind(Object.prototype.hasOwnProperty),
overrides = cfg.options.overrides,
pattern;
if (overrides) {
delete cfg.options.overrides;
for (pattern in overrides) {
if (has(overrides, pattern) && (new RegExp(pattern)).test(filePath)) {
bundle = overrides[pattern];
if (bundle.globals) {
$.extend(true, cfg.globals, bundle.globals);
delete bundle.globals;
}
$.extend(true, cfg.options, bundle);
}
}
}
return cfg;
};
}
/**
* Looks up the configuration file in the filesystem hierarchy and loads it.
*
* @param {String} root Path to the current project root.
* @param {string} dir Relative path to directory to start with.
* @param {function} readConfig Function to read and load configuration file.
*
* @returns {$.Promise} A promise for configuration.
*/
function _lookupAndLoad(root, dir, readConfig) {
var deferred = new $.Deferred(),
done = false,
cdir = dir,
iter = {
next: function () {
if (done) {
return;
}
readConfig(root + cdir)
.then(function (cfg) {
this.stop(cfg);
}.bind(this))
.fail(function () {
if (!cdir) {
this.stop(defaultConfig);
}
if (!done) {
cdir = FileUtils.getDirectoryPath(cdir.substring(0, cdir.length - 1));
this.next();
}
}.bind(this));
},
stop: function (cfg) {
deferred.resolve(cfg);
done = true;
}
};
if (cdir === undefined || cdir === null) {
deferred.resolve(defaultConfig);
} else {
iter.next();
}
return deferred.promise();
}
/**
* Loads JSHint configuration for the specified file.
*
* The configuration file should have name .jshintrc. If the specified file is outside the
* current project root, then defaultConfiguration is used. Otherwise, the configuration file
* is looked up starting from the directory where the specified file is located, going up to
* the project root, but no further.
*
* @param {string} fullPath Absolute path for the file linted.
*
* @return {$.Promise} Promise to return JSHint configuration object.
*
* @see <a href="http://www.jshint.com/docs/options/">JSHint option
* reference</a>.
*/
function _loadConfig(fullPath) {
var projectRootEntry = ProjectManager.getProjectRoot(),
result = new $.Deferred(),
relPath,
rootPath;
if (!projectRootEntry) {
return result.reject().promise();
}
if (!_scanProjectOnly) {
// scan entire filesystem
rootPath = projectRootEntry.fullPath.substring(0, projectRootEntry.fullPath.indexOf("/") + 1);
} else {
rootPath = projectRootEntry.fullPath;
}
// for files outside the root, use default config
if (!(relPath = FileUtils.getRelativeFilename(rootPath, fullPath))) {
result.resolve(defaultConfig);
return result.promise();
}
relPath = FileUtils.getDirectoryPath(relPath);
_lookupAndLoad(rootPath, relPath, _readConfig)
.done(function (cfg) {
result.resolve(cfg);
});
return result.promise();
}
/**
* Removes JavaScript comments from a string by replacing
* everything between block comments and everything after
* single-line comments in a non-greedy way.
*
* English version of the regex:
* match '/*'
* then match zero or more instances of any character (incl. \n)
* except for instances of '* /' (without a space, obv.)
* then match '* /' (again, without a space)
*
* @param {string} str a string with potential JavaScript comments.
* @returns {string} a string without JavaScript comments.
*/
function removeComments(str) {
str = str || "";
str = str.replace(/\/\*(?:(?!\*\/)[\s\S])*\*\//g, "");
str = str.replace(/\/\/[^\n\r]*/g, ""); // Everything after '//'
return str;
}
CodeInspection.register("javascript", {
name: JSHINT_NAME,
scanFile: handleHinter,
scanFileAsync: handleHinterAsync
});
});