forked from import-js/eslint-plugin-import
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathno-cycle.js
79 lines (67 loc) · 2.2 KB
/
no-cycle.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
/**
* @fileOverview Ensures that no imported module imports the linted module.
* @author Ben Mosher
*/
import Exports from '../ExportMap'
import moduleVisitor, { makeOptionsSchema } from 'eslint-module-utils/moduleVisitor'
import docsUrl from '../docsUrl'
// todo: cache cycles / deep relationships for faster repeat evaluation
module.exports = {
meta: {
docs: { url: docsUrl('no-cycle') },
schema: [makeOptionsSchema({
maxDepth:{
description: 'maximum dependency depth to traverse',
type: 'integer',
minimum: 1,
},
})],
},
create: function (context) {
const myPath = context.getFilename()
if (myPath === '<text>') return {} // can't cycle-check a non-file
const options = context.options[0] || {}
const maxDepth = options.maxDepth || Infinity
function checkSourceValue(sourceNode, importer) {
const imported = Exports.get(sourceNode.value, context)
if (imported == null) {
return // no-unresolved territory
}
if (imported.path === myPath) {
return // no-self-import territory
}
const untraversed = [{mget: () => imported, route:[]}]
const traversed = new Set()
function detectCycle({mget, route}) {
const m = mget()
if (m == null) return
if (traversed.has(m.path)) return
traversed.add(m.path)
for (let [path, { getter, source }] of m.imports) {
if (path === myPath) return true
if (traversed.has(path)) continue
if (route.length + 1 < maxDepth) {
untraversed.push({
mget: getter,
route: route.concat(source),
})
}
}
}
while (untraversed.length > 0) {
const next = untraversed.shift() // bfs!
if (detectCycle(next)) {
const message = (next.route.length > 0
? `Dependency cycle via ${routeString(next.route)}`
: 'Dependency cycle detected.')
context.report(importer, message)
return
}
}
}
return moduleVisitor(checkSourceValue, context.options[0])
},
}
function routeString(route) {
return route.map(s => `${s.value}:${s.loc.start.line}`).join('=>')
}