This repository has been archived by the owner on May 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (71 loc) · 2.34 KB
/
index.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
const path = require("path");
function isParentFolder(relativeFilePath, context, rootDir) {
const absoluteRootPath = context.getCwd() + (rootDir !== '' ? path.sep + rootDir : '');
const absoluteFilePath = path.join(path.dirname(context.getFilename()), relativeFilePath)
return relativeFilePath.startsWith("../") && (
rootDir === '' ||
(absoluteFilePath.startsWith(absoluteRootPath) &&
context.getFilename().startsWith(absoluteRootPath))
);
}
function isSameFolder(path) {
return path.startsWith("./");
}
function getAbsolutePath(relativePath, context, rootDir, prefix) {
return [
prefix,
...path
.relative(
context.getCwd() + (rootDir !== '' ? path.sep + rootDir : ''),
path.join(path.dirname(context.getFilename()), relativePath)
)
.split(path.sep)
].filter(String).join("/");
}
const message = "import statements should have an absolute path";
module.exports = {
rules: {
"no-relative-import-paths": {
meta: {
type: "layout",
fixable: "code",
},
create: function (context) {
const { allowSameFolder, rootDir, prefix } = {
allowSameFolder: context.options[0]?.allowSameFolder || false,
rootDir: context.options[0]?.rootDir || '',
prefix: context.options[0]?.prefix || '',
};
return {
ImportDeclaration: function (node) {
const path = node.source.value;
if (isParentFolder(path, context, rootDir)) {
context.report({
node,
message: message,
fix: function (fixer) {
return fixer.replaceTextRange(
[node.source.range[0] + 1, node.source.range[1] - 1],
getAbsolutePath(path, context, rootDir || '', prefix)
);
},
});
}
if (isSameFolder(path) && !allowSameFolder) {
context.report({
node,
message: message,
fix: function (fixer) {
return fixer.replaceTextRange(
[node.source.range[0] + 1, node.source.range[1] - 1],
getAbsolutePath(path, context, rootDir || '', prefix)
);
},
});
}
},
};
},
},
},
};