-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathno-relative-parent-imports.js
49 lines (39 loc) · 1.61 KB
/
no-relative-parent-imports.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
import { basename, dirname, relative } from 'path';
import { getPhysicalFilename } from 'eslint-module-utils/contextCompat';
import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor';
import resolve from 'eslint-module-utils/resolve';
import importType from '../core/importType';
import docsUrl from '../docsUrl';
module.exports = {
meta: {
type: 'suggestion',
docs: {
category: 'Static analysis',
description: 'Forbid importing modules from parent directories.',
url: docsUrl('no-relative-parent-imports'),
},
schema: [makeOptionsSchema()],
},
create: function noRelativePackages(context) {
const myPath = getPhysicalFilename(context);
if (myPath === '<text>') { return {}; } // can't check a non-file
function checkSourceValue(sourceNode) {
const depPath = sourceNode.value;
if (importType(depPath, context) === 'external') { // ignore packages
return;
}
const absDepPath = resolve(depPath, context);
if (!absDepPath) { // unable to resolve path
return;
}
const relDepPath = relative(dirname(myPath), absDepPath);
if (importType(relDepPath, context) === 'parent') {
context.report({
node: sourceNode,
message: `Relative imports from parent directories are not allowed. Please either pass what you're importing through at runtime (dependency injection), move \`${basename(myPath)}\` to same directory as \`${depPath}\` or consider making \`${depPath}\` a package.`,
});
}
}
return moduleVisitor(checkSourceValue, context.options[0]);
},
};