/
no-relative-packages.js
69 lines (59 loc) · 2.1 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
import path from 'path'
import readPkgUp from 'read-pkg-up'
import resolve from 'eslint-module-utils/resolve'
import importType from '../core/importType'
import isStaticRequire from '../core/staticRequire'
module.exports = {
meta: {
docs: {},
},
create: function noRelativePackages(context) {
function findNamedPackage(filePath) {
const found = readPkgUp.sync({cwd: filePath, normalize: false})
// console.log(found)
if (found.pkg && !found.pkg.name) {
return findNamedPackage(path.join(found.path, '../..'))
}
return found
}
function checkImportForRelativePackage(importPath, node) {
const potentialViolationTypes = ['parent', 'index', 'sibling']
if (potentialViolationTypes.indexOf(importType(importPath, context)) === -1) {
return
}
const resolvedImport = resolve(importPath, context)
const resolvedContext = 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}"`,
})
}
}
return {
ImportDeclaration(node) {
checkImportForRelativePackage(node.source.value, node.source)
},
CallExpression(node) {
if (isStaticRequire(node)) {
const [ firstArgument ] = node.arguments
checkImportForRelativePackage(firstArgument.value, firstArgument)
}
},
}
},
}