3d49cbf6f63aa8bd01d274cf4adb0192ead131c8
[platform/upstream/nodejs.git] / deps / npm / lib / dedupe.js
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.
5 //
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.
9
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")
22
23 module.exports = dedupe
24
25 dedupe.usage = "npm dedupe [pkg pkg...]"
26
27 function dedupe (args, silent, cb) {
28   if (typeof silent === "function") cb = silent, silent = false
29   var dryrun = false
30   if (npm.command.match(/^find/)) dryrun = true
31   return dedupe_(npm.prefix, args, {}, dryrun, silent, cb)
32 }
33
34 function dedupe_ (dir, filter, unavoidable, dryrun, silent, cb) {
35   readInstalled(path.resolve(dir), {}, null, function (er, data, counter) {
36     if (er) {
37       return cb(er)
38     }
39
40     if (!data) {
41       return cb()
42     }
43
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) {
49       s[k] = []
50       return s
51     }, {})
52
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.
57     ;(function U (obj) {
58       if (unavoidable[obj.name]) {
59         obj.unavoidable = true
60       }
61       if (obj.parent && obj.parent.unavoidable) {
62         obj.unavoidable = true
63       }
64       Object.keys(obj.children).forEach(function (k) {
65         U(obj.children[k])
66       })
67     })
68
69     // then collect them up and figure out who needs them
70     ;(function C (obj) {
71       if (dupes[obj.name] && !obj.unavoidable) {
72         dupes[obj.name].push(obj)
73         obj.duplicate = true
74       }
75       obj.dependents = whoDepends(obj)
76       Object.keys(obj.children).forEach(function (k) {
77         C(obj.children[k])
78       })
79     })(data)
80
81     if (dryrun) {
82       var k = Object.keys(dupes)
83       if (!k.length) return cb()
84       return npm.commands.ls(k, silent, cb)
85     }
86
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] || ""]
93         })]
94       })]
95     }).map(function (item) {
96       var name = item[0]
97       var set = item[1]
98
99       var ranges = set.map(function (i) {
100         return i[2].map(function (d) {
101           return d[2]
102         })
103       }).reduce(function (l, r) {
104         return l.concat(r)
105       }, []).map(function (v, i, set) {
106         if (set.indexOf(v) !== i) return false
107         return v
108       }).filter(function (v) {
109         return v !== false
110       })
111
112       var locs = set.map(function (i) {
113         return i[0]
114       })
115
116       var versions = set.map(function (i) {
117         return i[1]
118       }).filter(function (v, i, set) {
119         return set.indexOf(v) === i
120       })
121
122       var has = set.map(function (i) {
123         return [i[0], i[1]]
124       }).reduce(function (set, kv) {
125         set[kv[0]] = kv[1]
126         return set
127       }, {})
128
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         a = a.split(/\/node_modules\//)
134         b = b.split(/\/node_modules\//)
135         var name = a.pop()
136         b.pop()
137         // find the longest chain that both A and B share.
138         // then push the name back on it, and join by /node_modules/
139         var res = []
140         for (var i = 0, al = a.length, bl = b.length; i < al && i < bl && a[i] === b[i]; i++);
141         return a.slice(0, i).concat(name).join("/node_modules/")
142       }) : undefined
143
144       return [item[0], { item: item
145                        , ranges: ranges
146                        , locs: locs
147                        , loc: loc
148                        , has: has
149                        , versions: versions
150                        }]
151     }).filter(function (i) {
152       return i[1].loc
153     })
154
155     findVersions(npm, summary, function (er, set) {
156       if (er) return cb(er)
157       if (!set.length) return cb()
158       installAndRetest(set, filter, dir, unavoidable, silent, cb)
159     })
160   })
161 }
162
163 function installAndRetest (set, filter, dir, unavoidable, silent, cb) {
164   //return cb(null, set)
165   var remove = []
166
167   asyncMap(set, function (item, cb) {
168     // [name, has, loc, locMatch, regMatch, others]
169     var name = item[0]
170     var has = item[1]
171     var where = item[2]
172     var locMatch = item[3]
173     var regMatch = item[4]
174     var others = item[5]
175
176     // nothing to be done here.  oh well.  just a conflict.
177     if (!locMatch && !regMatch) {
178       log.warn("unavoidable conflict", item[0], item[1])
179       log.warn("unavoidable conflict", "Not de-duplicating")
180       unavoidable[item[0]] = true
181       return cb()
182     }
183
184     // nothing to do except to clean up the extraneous deps
185     if (locMatch && has[where] === locMatch) {
186       remove.push.apply(remove, others)
187       return cb()
188     }
189
190     if (regMatch) {
191       var what = name + "@" + regMatch
192       // where is /path/to/node_modules/foo/node_modules/bar
193       // for package "bar", but we need it to be just
194       // /path/to/node_modules/foo
195       where = where.split(/\/node_modules\//)
196       where.pop()
197       where = where.join("/node_modules/")
198       remove.push.apply(remove, others)
199
200       return npm.commands.install(where, what, cb)
201     }
202
203     // hrm?
204     return cb(new Error("danger zone\n" + name + " " +
205                         + regMatch + " " + locMatch))
206
207   }, function (er, installed) {
208     if (er) return cb(er)
209     asyncMap(remove, rimraf, function (er) {
210       if (er) return cb(er)
211       remove.forEach(function (r) {
212         log.info("rm", r)
213       })
214       dedupe_(dir, filter, unavoidable, false, silent, cb)
215     })
216   })
217 }
218
219 function findVersions (npm, summary, cb) {
220   // now, for each item in the summary, try to find the maximum version
221   // that will satisfy all the ranges.  next step is to install it at
222   // the specified location.
223   asyncMap(summary, function (item, cb) {
224     var name = item[0]
225     var data = item[1]
226     var loc = data.loc
227     var locs = data.locs.filter(function (l) {
228       return l !== loc
229     })
230
231     // not actually a dupe, or perhaps all the other copies were
232     // children of a dupe, so this'll maybe be picked up later.
233     if (locs.length === 0) {
234       return cb(null, [])
235     }
236
237     // { <folder>: <version> }
238     var has = data.has
239
240     // the versions that we already have.
241     // if one of these is ok, then prefer to use that.
242     // otherwise, try fetching from the registry.
243     var versions = data.versions
244
245     var ranges = data.ranges
246     npm.registry.get(name, function (er, data) {
247       var regVersions = er ? [] : Object.keys(data.versions)
248       var locMatch = bestMatch(versions, ranges)
249       var regMatch;
250       var tag = npm.config.get("tag");
251       var distTags = data["dist-tags"];
252       if (distTags && distTags[tag] && data.versions[distTags[tag]]) {
253         regMatch = distTags[tag]
254       } else {
255         regMatch = bestMatch(regVersions, ranges)
256       }
257
258       cb(null, [[name, has, loc, locMatch, regMatch, locs]])
259     })
260   }, cb)
261 }
262
263 function bestMatch (versions, ranges) {
264   return versions.filter(function (v) {
265     return !ranges.some(function (r) {
266       return !semver.satisfies(v, r, true)
267     })
268   }).sort(semver.compareLoose).pop()
269 }
270
271
272 function readInstalled (dir, counter, parent, cb) {
273   var pkg, children, realpath
274
275   fs.realpath(dir, function (er, rp) {
276     realpath = rp
277     next()
278   })
279
280   readJson(path.resolve(dir, "package.json"), function (er, data) {
281     if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er)
282     if (er) return cb() // not a package, probably.
283     counter[data.name] = counter[data.name] || 0
284     counter[data.name]++
285     pkg =
286       { _id: data._id
287       , name: data.name
288       , version: data.version
289       , dependencies: data.dependencies || {}
290       , optionalDependencies: data.optionalDependencies || {}
291       , devDependencies: data.devDependencies || {}
292       , bundledDependencies: data.bundledDependencies || []
293       , path: dir
294       , realPath: dir
295       , children: {}
296       , parent: parent
297       , family: Object.create(parent ? parent.family : null)
298       , unavoidable: false
299       , duplicate: false
300       }
301     if (parent) {
302       parent.children[data.name] = pkg
303       parent.family[data.name] = pkg
304     }
305     next()
306   })
307
308   fs.readdir(path.resolve(dir, "node_modules"), function (er, c) {
309     children = c || [] // error is ok, just means no children.
310     children = children.filter(function (p) {
311       return !p.match(/^[\._-]/)
312     })
313     next()
314   })
315
316   function next () {
317     if (!children || !pkg || !realpath) return
318
319     // ignore devDependencies.  Just leave them where they are.
320     children = children.filter(function (c) {
321       return !pkg.devDependencies.hasOwnProperty(c)
322     })
323
324     pkg.realPath = realpath
325     if (pkg.realPath !== pkg.path) children = []
326     var d = path.resolve(dir, "node_modules")
327     asyncMap(children, function (child, cb) {
328       readInstalled(path.resolve(d, child), counter, pkg, cb)
329     }, function (er) {
330       cb(er, pkg, counter)
331     })
332   }
333 }
334
335 function whoDepends (pkg) {
336   var start = pkg.parent || pkg
337   return whoDepends_(pkg, [], start)
338 }
339
340 function whoDepends_ (pkg, who, test) {
341   if (test !== pkg &&
342       test.dependencies[pkg.name] &&
343       test.family[pkg.name] === pkg) {
344     who.push(test)
345   }
346   Object.keys(test.children).forEach(function (n) {
347     whoDepends_(pkg, who, test.children[n])
348   })
349   return who
350 }
351