UNPKG

7.52 kBJavaScriptView Raw
1
2module.exports = completion
3
4completion.usage = "npm completion >> ~/.bashrc\n"
5 + "npm completion >> ~/.zshrc\n"
6 + "source <(npm completion)"
7
8var npm = require("./npm.js")
9 , npmconf = require("./config/core.js")
10 , configDefs = npmconf.defs
11 , configTypes = configDefs.types
12 , shorthands = configDefs.shorthands
13 , nopt = require("nopt")
14 , configNames = Object.keys(configTypes).filter(function (e) {
15 return e.charAt(0) !== "_"
16 })
17 , shorthandNames = Object.keys(shorthands)
18 , allConfs = configNames.concat(shorthandNames)
19 , once = require("once")
20
21
22completion.completion = function (opts, cb) {
23 if (opts.w > 3) return cb()
24
25 var fs = require("graceful-fs")
26 , path = require("path")
27 , bashExists = null
28 , zshExists = null
29 fs.stat(path.resolve(process.env.HOME, ".bashrc"), function (er) {
30 bashExists = !er
31 next()
32 })
33 fs.stat(path.resolve(process.env.HOME, ".zshrc"), function (er) {
34 zshExists = !er
35 next()
36 })
37 function next () {
38 if (zshExists === null || bashExists === null) return
39 var out = []
40 if (zshExists) out.push("~/.zshrc")
41 if (bashExists) out.push("~/.bashrc")
42 if (opts.w === 2) out = out.map(function (m) {
43 return [">>", m]
44 })
45 cb(null, out)
46 }
47}
48
49function completion (args, cb) {
50 if (process.platform === "win32") {
51 var e = new Error("npm completion not supported on windows")
52 e.code = "ENOTSUP"
53 e.errno = require("constants").ENOTSUP
54 return cb(e)
55 }
56
57 // if the COMP_* isn't in the env, then just dump the script.
58 if (process.env.COMP_CWORD === undefined
59 ||process.env.COMP_LINE === undefined
60 ||process.env.COMP_POINT === undefined
61 ) return dumpScript(cb)
62
63 console.error(process.env.COMP_CWORD)
64 console.error(process.env.COMP_LINE)
65 console.error(process.env.COMP_POINT)
66
67 //console.log("abracadabrasauce\nabracad cat monger")
68 //if (Math.random() * 3 < 1) console.log("man\\ bear\\ pig")
69 //else if (Math.random() * 3 < 1)
70 // console.log("porkchop\\ sandwiches\nporkman")
71 //else console.log("encephylophagy")
72
73 // get the partial line and partial word,
74 // if the point isn't at the end.
75 // ie, tabbing at: npm foo b|ar
76 var w = +process.env.COMP_CWORD
77 , words = args.map(unescape)
78 , word = words[w]
79 , line = process.env.COMP_LINE
80 , point = +process.env.COMP_POINT
81 , partialLine = line.substr(0, point)
82 , partialWords = words.slice(0, w)
83
84 // figure out where in that last word the point is.
85 var partialWord = args[w]
86 , i = partialWord.length
87 while (partialWord.substr(0, i) !== partialLine.substr(-1*i) && i > 0) {
88 i --
89 }
90 partialWord = unescape(partialWord.substr(0, i))
91 partialWords.push(partialWord)
92
93 var opts = { words : words
94 , w : w
95 , word : word
96 , line : line
97 , lineLength : line.length
98 , point : point
99 , partialLine : partialLine
100 , partialWords : partialWords
101 , partialWord : partialWord
102 , raw: args
103 }
104
105 cb = wrapCb(cb, opts)
106
107 console.error(opts)
108
109 if (partialWords.slice(0, -1).indexOf("--") === -1) {
110 if (word.charAt(0) === "-") return configCompl(opts, cb)
111 if (words[w - 1]
112 && words[w - 1].charAt(0) === "-"
113 && !isFlag(words[w - 1])) {
114 // awaiting a value for a non-bool config.
115 // don't even try to do this for now
116 console.error("configValueCompl")
117 return configValueCompl(opts, cb)
118 }
119 }
120
121 // try to find the npm command.
122 // it's the first thing after all the configs.
123 // take a little shortcut and use npm's arg parsing logic.
124 // don't have to worry about the last arg being implicitly
125 // boolean'ed, since the last block will catch that.
126 var parsed = opts.conf =
127 nopt(configTypes, shorthands, partialWords.slice(0, -1), 0)
128 // check if there's a command already.
129 console.error(parsed)
130 var cmd = parsed.argv.remain[1]
131 if (!cmd) return cmdCompl(opts, cb)
132
133 Object.keys(parsed).forEach(function (k) {
134 npm.config.set(k, parsed[k])
135 })
136
137 // at this point, if words[1] is some kind of npm command,
138 // then complete on it.
139 // otherwise, do nothing
140 cmd = npm.commands[cmd]
141 if (cmd && cmd.completion) return cmd.completion(opts, cb)
142
143 // nothing to do.
144 cb()
145}
146
147function dumpScript (cb) {
148 var fs = require("graceful-fs")
149 , path = require("path")
150 , p = path.resolve(__dirname, "utils/completion.sh")
151
152 // The Darwin patch below results in callbacks first for the write and then
153 // for the error handler, so make sure we only call our callback once.
154 cb = once(cb)
155
156 fs.readFile(p, "utf8", function (er, d) {
157 if (er) return cb(er)
158 d = d.replace(/^\#\!.*?\n/, "")
159
160 process.stdout.write(d, function () { cb() })
161 process.stdout.on("error", function (er) {
162 // Darwin is a real dick sometimes.
163 //
164 // This is necessary because the "source" or "." program in
165 // bash on OS X closes its file argument before reading
166 // from it, meaning that you get exactly 1 write, which will
167 // work most of the time, and will always raise an EPIPE.
168 //
169 // Really, one should not be tossing away EPIPE errors, or any
170 // errors, so casually. But, without this, `. <(npm completion)`
171 // can never ever work on OS X.
172 if (er.errno === "EPIPE") er = null
173 cb(er)
174 })
175
176 })
177}
178
179function unescape (w) {
180 if (w.charAt(0) === "\"") return w.replace(/^"|"$/g, "")
181 else return w.replace(/\\ /g, " ")
182}
183
184function escape (w) {
185 if (!w.match(/\s+/)) return w
186 return "\"" + w + "\""
187}
188
189// The command should respond with an array. Loop over that,
190// wrapping quotes around any that have spaces, and writing
191// them to stdout. Use console.log, not the outfd config.
192// If any of the items are arrays, then join them with a space.
193// Ie, returning ["a", "b c", ["d", "e"]] would allow it to expand
194// to: "a", "b c", or "d" "e"
195function wrapCb (cb, opts) { return function (er, compls) {
196 if (!Array.isArray(compls)) compls = compls ? [compls] : []
197 compls = compls.map(function (c) {
198 if (Array.isArray(c)) c = c.map(escape).join(" ")
199 else c = escape(c)
200 return c
201 })
202 if (opts.partialWord) compls = compls.filter(function (c) {
203 return c.indexOf(opts.partialWord) === 0
204 })
205 console.error([er && er.stack, compls, opts.partialWord])
206 if (er || compls.length === 0) return cb(er)
207
208 console.log(compls.join("\n"))
209 cb()
210}}
211
212// the current word has a dash. Return the config names,
213// with the same number of dashes as the current word has.
214function configCompl (opts, cb) {
215 var word = opts.word
216 , split = word.match(/^(-+)((?:no-)*)(.*)$/)
217 , dashes = split[1]
218 , no = split[2]
219 , flags = configNames.filter(isFlag)
220 console.error(flags)
221
222 return cb(null, allConfs.map(function (c) {
223 return dashes + c
224 }).concat(flags.map(function (f) {
225 return dashes + (no || "no-") + f
226 })))
227}
228
229// expand with the valid values of various config values.
230// not yet implemented.
231function configValueCompl (opts, cb) {
232 console.error("configValue", opts)
233 return cb(null, [])
234}
235
236// check if the thing is a flag or not.
237function isFlag (word) {
238 // shorthands never take args.
239 var split = word.match(/^(-*)((?:no-)+)?(.*)$/)
240 , no = split[2]
241 , conf = split[3]
242 return no || configTypes[conf] === Boolean || shorthands[conf]
243}
244
245// complete against the npm commands
246function cmdCompl (opts, cb) {
247 return cb(null, npm.fullList)
248}