-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathno-relative-packages.js
72 lines (62 loc) · 2.28 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
62
63
64
65
66
67
68
69
70
71
72
import path from 'path';
import readPkgUp from 'eslint-module-utils/readPkgUp';
import { getPhysicalFilename } from 'eslint-module-utils/contextCompat';
import resolve from 'eslint-module-utils/resolve';
import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor';
import importType from '../core/importType';
import docsUrl from '../docsUrl';
/** @param {string} filePath */
function toPosixPath(filePath) {
return filePath.replace(/\\/g, '/');
}
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 = getPhysicalFilename(context);
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}\``,
fix: (fixer) => fixer.replaceText(node, JSON.stringify(toPosixPath(properImport)))
,
});
}
}
module.exports = {
meta: {
type: 'suggestion',
docs: {
category: 'Static analysis',
description: 'Forbid importing packages through relative paths.',
url: docsUrl('no-relative-packages'),
},
fixable: 'code',
schema: [makeOptionsSchema()],
},
create(context) {
return moduleVisitor((source) => checkImportForRelativePackage(context, source.value, source), context.options[0]);
},
};