/
no-relative-packages.js
61 lines (52 loc) · 1.94 KB
/
no-relative-packages.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
import path from 'path';
import readPkgUp from 'eslint-module-utils/readPkgUp';
import resolve from 'eslint-module-utils/resolve';
import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor';
import importType from '../core/importType';
import docsUrl from '../docsUrl';
function findNamedPackage(filePath) {
const found = readPkgUp({ cwd: filePath });
if (found.pkg && !found.pkg.name) {
return findNamedPackage(path.join(found.path, '../..'));
}
return found;
}
function checkImportForRelativePackage(context, importPath, node) {
const potentialViolationTypes = ['parent', 'index', 'sibling'];
if (potentialViolationTypes.indexOf(importType(importPath, context)) === -1) {
return;
}
const resolvedImport = resolve(importPath, context);
const resolvedContext = context.getPhysicalFilename ? context.getPhysicalFilename() : context.getFilename();
if (!resolvedImport || !resolvedContext) {
return;
}
const importPkg = findNamedPackage(resolvedImport);
const contextPkg = findNamedPackage(resolvedContext);
if (importPkg.pkg && contextPkg.pkg && importPkg.pkg.name !== contextPkg.pkg.name) {
const importBaseName = path.basename(importPath);
const importRoot = path.dirname(importPkg.path);
const properPath = path.relative(importRoot, resolvedImport);
const properImport = path.join(
importPkg.pkg.name,
path.dirname(properPath),
importBaseName === path.basename(importRoot) ? '' : importBaseName
);
context.report({
node,
message: `Relative import from another package is not allowed. Use \`${properImport}\` instead of \`${importPath}\``,
});
}
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
url: docsUrl('no-relative-packages'),
},
schema: [makeOptionsSchema()],
},
create(context) {
return moduleVisitor((source) => checkImportForRelativePackage(context, source.value, source), context.options[0]);
},
};