-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
60 lines (49 loc) · 1.32 KB
/
index.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
// @flow
const fs = require('fs')
const path = require('path')
/*::
type Opts = {
// $FlowFixMe: flow can't tell I'm handling undefined value for this
cwd?: string,
devDeps?: boolean,
shallow?: boolean,
};
*/
function getPackage (dirpath /*: string */) /*: Object | null */ {
try {
const pkgPath = path.join(dirpath, 'package.json')
return JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
} catch (e) {
return null
}
}
module.exports = function lsDeps (opts /*: Opts */ = {}) /*: Object */ {
opts.cwd = opts.cwd || process.cwd()
const nodeModulesPath = path.join(opts.cwd, 'node_modules')
const result = {}
const seen = []
;(function getDeps (dirpath /*: string */, pkgName /* ?: string */) {
if (pkgName && seen.includes(pkgName)) {
return
}
const pkgJSON = getPackage(dirpath)
if (pkgJSON) {
if (pkgName) {
seen.push(pkgName)
result[pkgName] = pkgJSON.version
}
if (!pkgName || !opts.shallow) {
let deps = Object.keys(pkgJSON.dependencies || {})
if (opts.devDeps) {
deps = deps.concat(
Object.keys(pkgJSON.devDependencies || {})
)
}
for (const depName of deps) {
getDeps(path.join(nodeModulesPath, depName), depName)
}
}
}
})(opts.cwd)
return result
}