1 // traverse the node_modules/package.json tree
2 // looking for duplicates. If any duplicates are found,
3 // then move them up to the highest level necessary
4 // in order to make them no longer duplicated.
6 // This is kind of ugly, and really highlights the need for
7 // much better "put pkg X at folder Y" abstraction. Oh well,
8 // whatever. Perfect enemy of the good, and all that.
10 var fs = require("fs")
11 var asyncMap = require("slide").asyncMap
12 var path = require("path")
13 var readJson = require("read-package-json")
14 var archy = require("archy")
15 var util = require("util")
16 var RegClient = require("npm-registry-client")
17 var npmconf = require("npmconf")
18 var semver = require("semver")
19 var rimraf = require("rimraf")
20 var log = require("npmlog")
21 var npm = require("./npm.js")
23 module.exports = dedupe
25 dedupe.usage = "npm dedupe [pkg pkg...]"
27 function dedupe (args, silent, cb) {
28 if (typeof silent === "function") cb = silent, silent = false
30 if (npm.command.match(/^find/)) dryrun = true
31 return dedupe_(npm.prefix, args, {}, dryrun, silent, cb)
34 function dedupe_ (dir, filter, unavoidable, dryrun, silent, cb) {
35 readInstalled(path.resolve(dir), {}, null, function (er, data, counter) {
44 // find out which things are dupes
45 var dupes = Object.keys(counter || {}).filter(function (k) {
46 if (filter.length && -1 === filter.indexOf(k)) return false
47 return counter[k] > 1 && !unavoidable[k]
48 }).reduce(function (s, k) {
53 // any that are unavoidable need to remain as they are. don't even
54 // try to touch them or figure it out. Maybe some day, we can do
55 // something a bit more clever here, but for now, just skip over it,
56 // and all its children.
58 if (unavoidable[obj.name]) {
59 obj.unavoidable = true
61 if (obj.parent && obj.parent.unavoidable) {
62 obj.unavoidable = true
64 Object.keys(obj.children).forEach(function (k) {
69 // then collect them up and figure out who needs them
71 if (dupes[obj.name] && !obj.unavoidable) {
72 dupes[obj.name].push(obj)
75 obj.dependents = whoDepends(obj)
76 Object.keys(obj.children).forEach(function (k) {
82 var k = Object.keys(dupes)
83 if (!k.length) return cb()
84 return npm.commands.ls(k, silent, cb)
87 var summary = Object.keys(dupes).map(function (n) {
88 return [n, dupes[n].filter(function (d) {
89 return d && d.parent && !d.parent.duplicate && !d.unavoidable
90 }).map(function M (d) {
91 return [d.path, d.version, d.dependents.map(function (k) {
92 return [k.path, k.version, k.dependencies[d.name] || ""]
95 }).map(function (item) {
99 var ranges = set.map(function (i) {
100 return i[2].map(function (d) {
103 }).reduce(function (l, r) {
105 }, []).map(function (v, i, set) {
106 if (set.indexOf(v) !== i) return false
108 }).filter(function (v) {
112 var locs = set.map(function (i) {
116 var versions = set.map(function (i) {
118 }).filter(function (v, i, set) {
119 return set.indexOf(v) === i
122 var has = set.map(function (i) {
124 }).reduce(function (set, kv) {
129 var loc = locs.length ? locs.reduce(function (a, b) {
130 // a=/path/to/node_modules/foo/node_modules/bar
131 // b=/path/to/node_modules/elk/node_modules/bar
132 // ==/path/to/node_modules/bar
133 var nmReg = new RegExp("\\" + path.sep + "node_modules\\" + path.sep)
138 // find the longest chain that both A and B share.
139 // then push the name back on it, and join by /node_modules/
141 for (var i = 0, al = a.length, bl = b.length; i < al && i < bl && a[i] === b[i]; i++);
142 return a.slice(0, i).concat(name).join(path.sep + "node_modules" + path.sep)
145 return [item[0], { item: item
152 }).filter(function (i) {
156 findVersions(npm, summary, function (er, set) {
157 if (er) return cb(er)
158 if (!set.length) return cb()
159 installAndRetest(set, filter, dir, unavoidable, silent, cb)
164 function installAndRetest (set, filter, dir, unavoidable, silent, cb) {
165 //return cb(null, set)
168 asyncMap(set, function (item, cb) {
169 // [name, has, loc, locMatch, regMatch, others]
173 var locMatch = item[3]
174 var regMatch = item[4]
177 // nothing to be done here. oh well. just a conflict.
178 if (!locMatch && !regMatch) {
179 log.warn("unavoidable conflict", item[0], item[1])
180 log.warn("unavoidable conflict", "Not de-duplicating")
181 unavoidable[item[0]] = true
185 // nothing to do except to clean up the extraneous deps
186 if (locMatch && has[where] === locMatch) {
187 remove.push.apply(remove, others)
192 var what = name + "@" + regMatch
193 // where is /path/to/node_modules/foo/node_modules/bar
194 // for package "bar", but we need it to be just
195 // /path/to/node_modules/foo
196 var nmReg = new RegExp("\\" + path.sep + "node_modules\\" + path.sep)
197 where = where.split(nmReg)
199 where = where.join(path.sep + "node_modules" + path.sep)
200 remove.push.apply(remove, others)
202 return npm.commands.install(where, what, cb)
206 return cb(new Error("danger zone\n" + name + " " +
207 + regMatch + " " + locMatch))
209 }, function (er, installed) {
210 if (er) return cb(er)
211 asyncMap(remove, rimraf, function (er) {
212 if (er) return cb(er)
213 remove.forEach(function (r) {
216 dedupe_(dir, filter, unavoidable, false, silent, cb)
221 function findVersions (npm, summary, cb) {
222 // now, for each item in the summary, try to find the maximum version
223 // that will satisfy all the ranges. next step is to install it at
224 // the specified location.
225 asyncMap(summary, function (item, cb) {
229 var locs = data.locs.filter(function (l) {
233 // not actually a dupe, or perhaps all the other copies were
234 // children of a dupe, so this'll maybe be picked up later.
235 if (locs.length === 0) {
239 // { <folder>: <version> }
242 // the versions that we already have.
243 // if one of these is ok, then prefer to use that.
244 // otherwise, try fetching from the registry.
245 var versions = data.versions
247 var ranges = data.ranges
248 npm.registry.get(name, function (er, data) {
249 var regVersions = er ? [] : Object.keys(data.versions)
250 var locMatch = bestMatch(versions, ranges)
252 var tag = npm.config.get("tag");
253 var distTags = data["dist-tags"];
254 if (distTags && distTags[tag] && data.versions[distTags[tag]]) {
255 regMatch = distTags[tag]
257 regMatch = bestMatch(regVersions, ranges)
260 cb(null, [[name, has, loc, locMatch, regMatch, locs]])
265 function bestMatch (versions, ranges) {
266 return versions.filter(function (v) {
267 return !ranges.some(function (r) {
268 return !semver.satisfies(v, r, true)
270 }).sort(semver.compareLoose).pop()
274 function readInstalled (dir, counter, parent, cb) {
275 var pkg, children, realpath
277 fs.realpath(dir, function (er, rp) {
282 readJson(path.resolve(dir, "package.json"), function (er, data) {
283 if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er)
284 if (er) return cb() // not a package, probably.
285 counter[data.name] = counter[data.name] || 0
290 , version: data.version
291 , dependencies: data.dependencies || {}
292 , optionalDependencies: data.optionalDependencies || {}
293 , devDependencies: data.devDependencies || {}
294 , bundledDependencies: data.bundledDependencies || []
299 , family: Object.create(parent ? parent.family : null)
304 parent.children[data.name] = pkg
305 parent.family[data.name] = pkg
310 fs.readdir(path.resolve(dir, "node_modules"), function (er, c) {
311 children = c || [] // error is ok, just means no children.
312 children = children.filter(function (p) {
313 return !p.match(/^[\._-]/)
319 if (!children || !pkg || !realpath) return
321 // ignore devDependencies. Just leave them where they are.
322 children = children.filter(function (c) {
323 return !pkg.devDependencies.hasOwnProperty(c)
326 pkg.realPath = realpath
327 if (pkg.realPath !== pkg.path) children = []
328 var d = path.resolve(dir, "node_modules")
329 asyncMap(children, function (child, cb) {
330 readInstalled(path.resolve(d, child), counter, pkg, cb)
337 function whoDepends (pkg) {
338 var start = pkg.parent || pkg
339 return whoDepends_(pkg, [], start)
342 function whoDepends_ (pkg, who, test) {
344 test.dependencies[pkg.name] &&
345 test.family[pkg.name] === pkg) {
348 Object.keys(test.children).forEach(function (n) {
349 whoDepends_(pkg, who, test.children[n])