2 var CC = require("config-chain").ConfigChain
3 var inherits = require("inherits")
4 var configDefs = require("./defaults.js")
5 var types = configDefs.types
6 var once = require("once")
8 var path = require("path")
9 var nopt = require("nopt")
10 var ini = require("ini")
11 var Umask = configDefs.Umask
12 var mkdirp = require("mkdirp")
13 var umask = require("../utils/umask")
17 exports.loaded = false
18 exports.rootConf = null
19 exports.usingBuiltin = false
20 exports.defs = configDefs
22 Object.defineProperty(exports, "defaults", { get: function () {
23 return configDefs.defaults
24 }, enumerable: true })
26 Object.defineProperty(exports, "types", { get: function () {
27 return configDefs.types
28 }, enumerable: true })
30 exports.validate = validate
32 var myUid = process.env.SUDO_UID !== undefined
33 ? process.env.SUDO_UID : (process.getuid && process.getuid())
34 var myGid = process.env.SUDO_GID !== undefined
35 ? process.env.SUDO_GID : (process.getgid && process.getgid())
42 for (var i = 0; i < arguments.length; i++)
43 switch (typeof arguments[i]) {
44 case "string": builtin = arguments[i]; break
45 case "object": cli = arguments[i]; break
46 case "function": cb = arguments[i]; break
53 var ret = exports.loaded
58 return process.nextTick(cb.bind(null, null, ret))
61 // either a fresh object, or a clone of the passed in obj
65 cli = Object.keys(cli).reduce(function (c, k) {
76 cb = once(function (er, conf) {
81 loadCbs.forEach(function (fn) {
87 // check for a builtin if provided.
88 exports.usingBuiltin = !!builtin
89 var rc = exports.rootConf = new Conf()
91 rc.addFile(builtin, "builtin")
95 rc.on("load", function () {
96 load_(builtin, rc, cli, cb)
101 function load_(builtin, rc, cli, cb) {
102 var defaults = configDefs.defaults
103 var conf = new Conf(rc)
105 conf.usingBuiltin = !!builtin
109 conf.loadPrefix(function(er) {
113 // If you're doing `npm --userconfig=~/foo.npmrc` then you'd expect
114 // that ~/.npmrc won't override the stuff in ~/foo.npmrc (or, indeed
117 // However, if the cwd is ~, then ~/.npmrc is the home for the project
118 // config, and will override the userconfig.
120 // If you're not setting the userconfig explicitly, then it will be loaded
121 // twice, which is harmless but excessive. If you *are* setting the
122 // userconfig explicitly then it will override your explicit intent, and
123 // that IS harmful and unexpected.
125 // Solution: Do not load project config file that is the same as either
126 // the default or resolved userconfig value. npm will log a "verbose"
127 // message about this when it happens, but it is a rare enough edge case
128 // that we don't have to be super concerned about it.
129 var projectConf = path.resolve(conf.localPrefix, ".npmrc")
130 var defaultUserConfig = rc.get("userconfig")
131 var resolvedUserConfig = conf.get("userconfig")
132 if (!conf.get("global") &&
133 projectConf !== defaultUserConfig &&
134 projectConf !== resolvedUserConfig) {
135 conf.addFile(projectConf, "project")
136 conf.once("load", afterPrefix)
138 conf.add({}, "project")
143 function afterPrefix() {
144 conf.addFile(conf.get("userconfig"), "user")
145 conf.once("error", cb)
146 conf.once("load", afterUser)
149 function afterUser () {
150 // globalconfig and globalignorefile defaults
151 // need to respond to the 'prefix' setting up to this point.
152 // Eg, `npm config get globalconfig --prefix ~/local` should
153 // return `~/local/etc/npmrc`
154 // annoying humans and their expectations!
155 if (conf.get("prefix")) {
156 var etc = path.resolve(conf.get("prefix"), "etc")
157 mkdirp(etc, function (err) {
158 defaults.globalconfig = path.resolve(etc, "npmrc")
159 defaults.globalignorefile = path.resolve(etc, "npmignore")
160 afterUserContinuation()
163 afterUserContinuation()
167 function afterUserContinuation() {
168 conf.addFile(conf.get("globalconfig"), "global")
170 // move the builtin into the conf stack now.
172 conf.add(rc.shift(), "builtin")
173 conf.once("load", function () {
174 conf.loadExtras(afterExtras)
178 function afterExtras(er) {
182 // warn about invalid bits.
185 var cafile = conf.get("cafile")
188 return conf.loadCAFile(cafile, finalize)
194 function finalize(er) {
199 exports.loaded = conf
204 // Basically the same as CC, but:
206 // 2. Parses environment variable names in field values
207 // 3. Field values that start with ~/ are replaced with process.env.HOME
208 // 4. Can inherit from another Conf object, using it as the base.
210 function Conf (base) {
211 if (!(this instanceof Conf))
212 return new Conf(base)
217 if (base instanceof Conf)
218 this.root = base.list[0] || base.root
222 this.root = configDefs.defaults
225 Conf.prototype.loadPrefix = require("./load-prefix.js")
226 Conf.prototype.loadCAFile = require("./load-cafile.js")
227 Conf.prototype.loadUid = require("./load-uid.js")
228 Conf.prototype.setUser = require("./set-user.js")
229 Conf.prototype.findPrefix = require("./find-prefix.js")
230 Conf.prototype.getCredentialsByURI = require("./get-credentials-by-uri.js")
231 Conf.prototype.setCredentialsByURI = require("./set-credentials-by-uri.js")
232 Conf.prototype.clearCredentialsByURI = require("./clear-credentials-by-uri.js")
234 Conf.prototype.loadExtras = function(cb) {
235 this.setUser(function(er) {
238 this.loadUid(function(er) {
241 // Without prefix, nothing will ever work
242 mkdirp(this.prefix, cb)
247 Conf.prototype.save = function (where, cb) {
248 var target = this.sources[where]
249 if (!target || !(target.path || target.source) || !target.data) {
250 if (where !== "builtin")
251 var er = new Error("bad save target: " + where)
253 process.nextTick(cb.bind(null, er))
256 return this.emit("error", er)
260 var pref = target.prefix || ""
261 Object.keys(target.data).forEach(function (k) {
262 target.source[pref + k] = target.data[k]
264 if (cb) process.nextTick(cb)
268 var data = ini.stringify(target.data)
270 then = then.bind(this)
271 done = done.bind(this)
274 var mode = where === "user" ? "0600" : "0666"
276 fs.unlink(target.path, function () {
277 // ignore the possible error (e.g. the file doesn't exist)
281 mkdirp(path.dirname(target.path), function (er) {
284 fs.writeFile(target.path, data, "utf8", function (er) {
287 if (where === "user" && myUid && myGid)
288 fs.chown(target.path, +myUid, +myGid, then)
298 fs.chmod(target.path, mode, done)
303 if (cb) return cb(er)
304 else return this.emit("error", er)
307 if (this._saving === 0) {
316 Conf.prototype.addFile = function (file, name) {
318 var marker = {__source__:name}
319 this.sources[name] = { path: file, type: "ini" }
322 fs.readFile(file, "utf8", function (er, data) {
323 if (er) // just ignore missing files.
324 return this.add({}, marker)
325 this.addString(data, file, "ini", marker)
331 Conf.prototype.parse = function (content, file) {
332 return CC.prototype.parse.call(this, content, file, "ini")
335 Conf.prototype.add = function (data, marker) {
337 Object.keys(data).forEach(function (k) {
338 data[k] = parseField(data[k], k)
342 this.emit("error", e)
345 return CC.prototype.add.call(this, data, marker)
348 Conf.prototype.addEnv = function (env) {
349 env = env || process.env
352 .filter(function (k) { return k.match(/^npm_config_/i) })
353 .forEach(function (k) {
357 // leave first char untouched, even if
358 // it is a "_" - convert all other to "-"
359 var p = k.toLowerCase()
360 .replace(/^npm_config_/, "")
361 .replace(/(?!^)_/g, "-")
364 return CC.prototype.addEnv.call(this, "", conf, "env")
367 function parseField (f, k) {
368 if (typeof f !== "string" && !(f instanceof String))
371 // type can be an array or single thing.
372 var typeList = [].concat(types[k])
373 var isPath = -1 !== typeList.indexOf(path)
374 var isBool = -1 !== typeList.indexOf(Boolean)
375 var isString = -1 !== typeList.indexOf(String)
376 var isUmask = -1 !== typeList.indexOf(Umask)
377 var isNumber = -1 !== typeList.indexOf(Number)
381 if (f.match(/^".*"$/)) {
386 throw new Error("Failed parsing JSON config key " + k + ": " + f)
390 if (isBool && !isString && f === "")
394 case "true": return true
395 case "false": return false
396 case "null": return null
397 case "undefined": return undefined
403 var homePattern = process.platform === "win32" ? /^~(\/|\\)/ : /^~\//
404 if (f.match(homePattern) && process.env.HOME) {
405 f = path.resolve(process.env.HOME, f.substr(2))
411 f = umask.fromString(f)
413 if (isNumber && !isNaN(f))
419 function envReplace (f) {
420 if (typeof f !== "string" || !f) return f
422 // replace any ${ENV} values with the appropriate environ.
423 var envExpr = /(\\*)\$\{([^}]+)\}/g
424 return f.replace(envExpr, function (orig, esc, name) {
425 esc = esc.length && esc.length % 2
428 if (undefined === process.env[name])
429 throw new Error("Failed to replace env in config: "+orig)
430 return process.env[name]
434 function validate (cl) {
435 // warn about invalid configs at every level.
436 cl.list.forEach(function (conf) {
437 nopt.clean(conf, configDefs.types)
440 nopt.clean(cl.root, configDefs.types)