-
Notifications
You must be signed in to change notification settings - Fork 1
/
valid-provide-and-module.js
71 lines (63 loc) · 2.5 KB
/
valid-provide-and-module.js
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
'use strict';
const path = require('path');
const pkgDir = require('pkg-dir');
const util = require('./util');
exports.rule = {
meta: {
docs: {
description: 'require the first goog.provide() or goog.module() has an arg named like the file path'
}
},
create: function(context) {
const entryPoints = context.options[0].entryPoints || ['ol'];
const relativeSourceRoot = context.options[0].root || 'src';
let replace = context.options[0].replace;
if (replace) {
replace = replace.split('|');
}
let gotFirst = false;
return {
CallExpression: function(expression) {
if (gotFirst) {
return;
}
const isProvide = util.isProvideExpression(expression);
const isModule = util.isModuleExpression(expression);
if (isProvide || isModule) {
const type = isProvide ? 'provide' : 'module';
gotFirst = true;
const parent = expression.parent;
if (parent.type !== 'ExpressionStatement') {
return context.report(expression, `Expected goog.${type}() to be in an expression statement`);
}
if (parent.parent.type !== 'Program') {
return context.report(expression, `Expected goog.${type}() to be at the top level`);
}
if (expression.arguments.length !== 1) {
return context.report(expression, `Expected one argument for goog.${type}()`);
}
const arg = expression.arguments[0];
if (arg.type !== 'Literal' || !arg.value || typeof arg.value !== 'string') {
return context.report(expression, `Expected goog.${type}() to be called with a string`);
}
const filePath = context.getFilename();
const sourceRoot = path.join(pkgDir.sync(filePath), relativeSourceRoot);
let requirePath = path.relative(sourceRoot, filePath);
const ext = '.js';
let name = arg.value;
// special case for main entry point
if (entryPoints.indexOf(name) !== -1) {
name += '.index';
}
const expectedPath = name.split('.').join(path.sep) + ext;
if (replace) {
requirePath = requirePath.replace(replace[0], replace[1]);
}
if (expectedPath.toLowerCase() !== requirePath.toLowerCase()) {
return context.report(expression, `Expected goog.${type}('${name}') to be at ${expectedPath.toLowerCase()} instead of ${requirePath.toLowerCase()}`);
}
}
}
};
}
};