|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +// Original repository: https://github.com/defunctzombie/node-lsmod/ |
| 4 | +// |
| 5 | +// [2018-02-09] @kamilogorek - Handle scoped packages structure |
| 6 | + |
| 7 | +// builtin |
| 8 | +var fs = require('fs'); |
| 9 | +var path = require('path'); |
| 10 | + |
| 11 | +// node 0.6 support |
| 12 | +fs.existsSync = fs.existsSync || path.existsSync; |
| 13 | + |
| 14 | +// mainPaths are the paths where our mainprog will be able to load from |
| 15 | +// we store these to avoid grabbing the modules that were loaded as a result |
| 16 | +// of a dependency module loading its dependencies, we only care about deps our |
| 17 | +// mainprog loads |
| 18 | +var mainPaths = (require.main && require.main.paths) || []; |
| 19 | + |
| 20 | +module.exports = function() { |
| 21 | + var paths = Object.keys(require.cache || []); |
| 22 | + |
| 23 | + // module information |
| 24 | + var infos = {}; |
| 25 | + |
| 26 | + // paths we have already inspected to avoid traversing again |
| 27 | + var seen = {}; |
| 28 | + |
| 29 | + paths.forEach(function(p) { |
| 30 | + /* eslint-disable consistent-return */ |
| 31 | + |
| 32 | + var dir = p; |
| 33 | + |
| 34 | + (function updir() { |
| 35 | + var orig = dir; |
| 36 | + dir = path.dirname(orig); |
| 37 | + |
| 38 | + if (/@[^/]+$/.test(dir)) { |
| 39 | + dir = path.dirname(dir); |
| 40 | + } |
| 41 | + |
| 42 | + if (!dir || orig === dir || seen[orig]) { |
| 43 | + return; |
| 44 | + } else if (mainPaths.indexOf(dir) < 0) { |
| 45 | + return updir(); |
| 46 | + } |
| 47 | + |
| 48 | + var pkgfile = path.join(orig, 'package.json'); |
| 49 | + var exists = fs.existsSync(pkgfile); |
| 50 | + |
| 51 | + seen[orig] = true; |
| 52 | + |
| 53 | + // travel up the tree if no package.json here |
| 54 | + if (!exists) { |
| 55 | + return updir(); |
| 56 | + } |
| 57 | + |
| 58 | + try { |
| 59 | + var info = JSON.parse(fs.readFileSync(pkgfile, 'utf8')); |
| 60 | + infos[info.name] = info.version; |
| 61 | + } catch (e) {} |
| 62 | + })(); |
| 63 | + |
| 64 | + /* eslint-enable consistent-return */ |
| 65 | + }); |
| 66 | + |
| 67 | + return infos; |
| 68 | +}; |
0 commit comments