-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIndividualMethodImport.js
85 lines (69 loc) · 2.35 KB
/
IndividualMethodImport.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const BaseRule = require('src/rules/Base');
class IndividualMethodImportRule extends BaseRule {
/**
* checks whether package methods are imported / required individually. For instance, when we consider **lodash** library, first two ways of `import` should be avoided.
*
* ```js
* 1) import _ from 'lodash';
* 2) import { uniq } from 'lodash';
* 3) import uniq from 'lodash/uniq';
* ```
*
* {@link https://www.blazemeter.com/blog/the-correct-way-to-import-lodash-libraries-a-benchmark}
*
* @param {PatchronContext} patchronContext
* @param {IndividualMethodImportConfig} config
* @param {Patch} file
*/
constructor(patchronContext, config, file) {
super(patchronContext, file);
const { packages } = config;
this.packages = packages;
}
invoke() {
if (!this.packages.length) {
this.log.warning(__filename, 'No packages defined', this.file);
return [];
}
const { splitPatch } = this.file;
const data = this.setupData(splitPatch);
if (!this._includesAnyMatch(data)) {
return [];
}
const reviewComments = [];
const dataLength = data.length;
for (let index = 0; index < dataLength; index++) {
const { trimmedContent } = data[index];
if (
this.CUSTOM_LINES.includes(trimmedContent) ||
trimmedContent.startsWith(this.HUNK_HEADER_INDICATOR)
) {
continue;
}
const myPackage = this.packages.find(({ regex }) =>
trimmedContent.match(regex)
);
if (myPackage) {
reviewComments.push(
this.getSingleLineComment({
body: this._getCommentBody(myPackage),
index
})
);
}
}
return reviewComments;
}
_includesAnyMatch(data) {
return data.some(({ trimmedContent }) =>
this.packages.some(({ regex }) => trimmedContent.match(regex))
);
}
/**
* @returns {string}
*/
_getCommentBody(myPackage) {
return `Please, import ${myPackage.name} features one-by-one, directly from the bundle.`;
}
}
module.exports = IndividualMethodImportRule;