This repository has been archived by the owner on Aug 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
ls.js
94 lines (90 loc) · 2.82 KB
/
ls.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// show the installed versions of a package
module.exports = exports = ls
var npm = require("../npm")
, log = require("./utils/log")
, readInstalled = require("./utils/read-installed")
, registry = require("./utils/registry")
, semver = require("./utils/semver")
function ls (args, cb) {
readInstalled([], function (er, installed) {
registry.get(function (er, remote) {
var pretty = prettify(merge(installed, remote), args)
, stdout = process.stdout
stdout.write(pretty)
stdout.flush()
})
})
}
function strcmp (a, b) { return a > b ? 1 : -1 }
function prettify (data, args) {
var pkgs = Object.keys(data).sort(strcmp)
, attrs = []
, names = []
, pretty = []
, maxNameLen = 0
pkgs.forEach(function (name) {
var pkg = data[name]
Object.keys(pkg).sort(semver.compare).forEach(function (v) {
var ver = pkg[v]
, p = []
ver.tags = ver.tags.length === 0
? ""
: ("@tag=" + ver.tags.join(" @tag="))
for (var i in ver) if (ver[i]) {
p.push((typeof ver[i] === "string") ? ver[i] : "@" + i)
}
names.push(name + "@" + v)
maxNameLen = Math.max(maxNameLen, (name + "@" + v).length)
attrs.push(p.sort(strcmp).join(" "))
})
})
var space = " "
for (var n = 0, l = names.length; n < l; n ++) {
names[n] += space.substr(0, maxNameLen - names[n].length)
pretty.push(names[n] + " " + attrs[n])
}
// don't color if it's piping to some other process.
var doColor = !process.binding("stdio").isStdoutBlocking()
, colors = [36, 32, 33, 31, 35 ]
, c = 0
, l = colors.length
if (args) args.forEach(function (arg) {
pretty = pretty.filter(function (line) { return line.match(arg) })
if (doColor) {
pretty = pretty.map(function (line) {
return line.split(arg).join("\033["+colors[c]+"m" + arg + "\033[m")
})
c = (c + 1) % l
}
})
if (!pretty.length) pretty = ["Nothing found"]
pretty.push("")
return pretty.join("\n")
}
function merge (installed, remote) {
var merged = {}
// first, just copy the installed stuff
for (var p in installed) {
merged[p] = {}
for (var v in installed[p]) {
merged[p][v] = { installed : true, tags : [] }
for (var s in installed[p][v]) {
merged[p][v][s] = installed[p][v][s]
}
}
}
// now merge in the remote stuff.
for (var p in remote) {
merged[p] = merged[p] || {}
for (var v in remote[p].versions) {
merged[p][v] = merged[p][v] || {}
merged[p][v].remote = true
merged[p][v].stable = (remote[p]["dist-tags"].stable === v)
merged[p][v].tags = []
Object.keys(remote[p]["dist-tags"]).forEach(function (tag) {
if (remote[p]["dist-tags"][tag] === v) merged[p][v].tags.push(tag)
})
}
}
return merged
}