"Fossies" - the Fresh Open Source Software Archive

Member "Atom/resources/app/apm/node_modules/npm/lib/config/core.js" (8 Mar 2017, 11296 Bytes) of archive /windows/misc/atom-windows.zip:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Javascript source code syntax highlighting (style: standard) with prefixed line numbers and code folding option. Alternatively you can here view or download the uninterpreted source code file.

    1 var CC = require('config-chain').ConfigChain
    2 var inherits = require('inherits')
    3 var configDefs = require('./defaults.js')
    4 var types = configDefs.types
    5 var once = require('once')
    6 var fs = require('fs')
    7 var path = require('path')
    8 var nopt = require('nopt')
    9 var ini = require('ini')
   10 var Umask = configDefs.Umask
   11 var mkdirp = require('mkdirp')
   12 var umask = require('../utils/umask')
   13 var isWindows = require('../utils/is-windows.js')
   14 
   15 exports.load = load
   16 exports.Conf = Conf
   17 exports.loaded = false
   18 exports.rootConf = null
   19 exports.usingBuiltin = false
   20 exports.defs = configDefs
   21 
   22 Object.defineProperty(exports, 'defaults', { get: function () {
   23   return configDefs.defaults
   24 }, enumerable: true })
   25 
   26 Object.defineProperty(exports, 'types', { get: function () {
   27   return configDefs.types
   28 }, enumerable: true })
   29 
   30 exports.validate = validate
   31 
   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())
   36 
   37 var loading = false
   38 var loadCbs = []
   39 function load () {
   40   var cli, builtin, cb
   41   for (var i = 0; i < arguments.length; i++) {
   42     switch (typeof arguments[i]) {
   43       case 'string': builtin = arguments[i]; break
   44       case 'object': cli = arguments[i]; break
   45       case 'function': cb = arguments[i]; break
   46     }
   47   }
   48 
   49   if (!cb) cb = function () {}
   50 
   51   if (exports.loaded) {
   52     var ret = exports.loaded
   53     if (cli) {
   54       ret = new Conf(ret)
   55       ret.unshift(cli)
   56     }
   57     return process.nextTick(cb.bind(null, null, ret))
   58   }
   59 
   60   // either a fresh object, or a clone of the passed in obj
   61   if (!cli) {
   62     cli = {}
   63   } else {
   64     cli = Object.keys(cli).reduce(function (c, k) {
   65       c[k] = cli[k]
   66       return c
   67     }, {})
   68   }
   69 
   70   loadCbs.push(cb)
   71   if (loading) return
   72 
   73   loading = true
   74 
   75   cb = once(function (er, conf) {
   76     if (!er) {
   77       exports.loaded = conf
   78       loading = false
   79     }
   80     loadCbs.forEach(function (fn) {
   81       fn(er, conf)
   82     })
   83     loadCbs.length = 0
   84   })
   85 
   86   // check for a builtin if provided.
   87   exports.usingBuiltin = !!builtin
   88   var rc = exports.rootConf = new Conf()
   89   if (builtin) {
   90     rc.addFile(builtin, 'builtin')
   91   } else {
   92     rc.add({}, 'builtin')
   93   }
   94 
   95   rc.on('load', function () {
   96     load_(builtin, rc, cli, cb)
   97   })
   98   rc.on('error', cb)
   99 }
  100 
  101 function load_ (builtin, rc, cli, cb) {
  102   var defaults = configDefs.defaults
  103   var conf = new Conf(rc)
  104 
  105   conf.usingBuiltin = !!builtin
  106   conf.add(cli, 'cli')
  107   conf.addEnv()
  108 
  109   conf.loadPrefix(function (er) {
  110     if (er) return cb(er)
  111 
  112     // If you're doing `npm --userconfig=~/foo.npmrc` then you'd expect
  113     // that ~/.npmrc won't override the stuff in ~/foo.npmrc (or, indeed
  114     // be used at all).
  115     //
  116     // However, if the cwd is ~, then ~/.npmrc is the home for the project
  117     // config, and will override the userconfig.
  118     //
  119     // If you're not setting the userconfig explicitly, then it will be loaded
  120     // twice, which is harmless but excessive.  If you *are* setting the
  121     // userconfig explicitly then it will override your explicit intent, and
  122     // that IS harmful and unexpected.
  123     //
  124     // Solution: Do not load project config file that is the same as either
  125     // the default or resolved userconfig value.  npm will log a "verbose"
  126     // message about this when it happens, but it is a rare enough edge case
  127     // that we don't have to be super concerned about it.
  128     var projectConf = path.resolve(conf.localPrefix, '.npmrc')
  129     var defaultUserConfig = rc.get('userconfig')
  130     var resolvedUserConfig = conf.get('userconfig')
  131     if (!conf.get('global') &&
  132         projectConf !== defaultUserConfig &&
  133         projectConf !== resolvedUserConfig) {
  134       conf.addFile(projectConf, 'project')
  135       conf.once('load', afterPrefix)
  136     } else {
  137       conf.add({}, 'project')
  138       afterPrefix()
  139     }
  140   })
  141 
  142   function afterPrefix () {
  143     conf.addFile(conf.get('userconfig'), 'user')
  144     conf.once('error', cb)
  145     conf.once('load', afterUser)
  146   }
  147 
  148   function afterUser () {
  149     // globalconfig and globalignorefile defaults
  150     // need to respond to the 'prefix' setting up to this point.
  151     // Eg, `npm config get globalconfig --prefix ~/local` should
  152     // return `~/local/etc/npmrc`
  153     // annoying humans and their expectations!
  154     if (conf.get('prefix')) {
  155       var etc = path.resolve(conf.get('prefix'), 'etc')
  156       mkdirp(etc, function () {
  157         defaults.globalconfig = path.resolve(etc, 'npmrc')
  158         defaults.globalignorefile = path.resolve(etc, 'npmignore')
  159         afterUserContinuation()
  160       })
  161     } else {
  162       afterUserContinuation()
  163     }
  164   }
  165 
  166   function afterUserContinuation () {
  167     conf.addFile(conf.get('globalconfig'), 'global')
  168 
  169     // move the builtin into the conf stack now.
  170     conf.root = defaults
  171     conf.add(rc.shift(), 'builtin')
  172     conf.once('load', function () {
  173       conf.loadExtras(afterExtras)
  174     })
  175   }
  176 
  177   function afterExtras (er) {
  178     if (er) return cb(er)
  179 
  180     // warn about invalid bits.
  181     validate(conf)
  182 
  183     var cafile = conf.get('cafile')
  184 
  185     if (cafile) {
  186       return conf.loadCAFile(cafile, finalize)
  187     }
  188 
  189     finalize()
  190   }
  191 
  192   function finalize (er) {
  193     if (er) {
  194       return cb(er)
  195     }
  196 
  197     exports.loaded = conf
  198     cb(er, conf)
  199   }
  200 }
  201 
  202 // Basically the same as CC, but:
  203 // 1. Always ini
  204 // 2. Parses environment variable names in field values
  205 // 3. Field values that start with ~/ are replaced with process.env.HOME
  206 // 4. Can inherit from another Conf object, using it as the base.
  207 inherits(Conf, CC)
  208 function Conf (base) {
  209   if (!(this instanceof Conf)) return new Conf(base)
  210 
  211   CC.apply(this)
  212 
  213   if (base) {
  214     if (base instanceof Conf) {
  215       this.root = base.list[0] || base.root
  216     } else {
  217       this.root = base
  218     }
  219   } else {
  220     this.root = configDefs.defaults
  221   }
  222 }
  223 
  224 Conf.prototype.loadPrefix = require('./load-prefix.js')
  225 Conf.prototype.loadCAFile = require('./load-cafile.js')
  226 Conf.prototype.loadUid = require('./load-uid.js')
  227 Conf.prototype.setUser = require('./set-user.js')
  228 Conf.prototype.findPrefix = require('./find-prefix.js')
  229 Conf.prototype.getCredentialsByURI = require('./get-credentials-by-uri.js')
  230 Conf.prototype.setCredentialsByURI = require('./set-credentials-by-uri.js')
  231 Conf.prototype.clearCredentialsByURI = require('./clear-credentials-by-uri.js')
  232 
  233 Conf.prototype.loadExtras = function (cb) {
  234   this.setUser(function (er) {
  235     if (er) return cb(er)
  236     this.loadUid(function (er) {
  237       if (er) return cb(er)
  238       // Without prefix, nothing will ever work
  239       mkdirp(this.prefix, cb)
  240     }.bind(this))
  241   }.bind(this))
  242 }
  243 
  244 Conf.prototype.save = function (where, cb) {
  245   var target = this.sources[where]
  246   if (!target || !(target.path || target.source) || !target.data) {
  247     var er
  248     if (where !== 'builtin') er = new Error('bad save target: ' + where)
  249     if (cb) {
  250       process.nextTick(cb.bind(null, er))
  251       return this
  252     }
  253     return this.emit('error', er)
  254   }
  255 
  256   if (target.source) {
  257     var pref = target.prefix || ''
  258     Object.keys(target.data).forEach(function (k) {
  259       target.source[pref + k] = target.data[k]
  260     })
  261     if (cb) process.nextTick(cb)
  262     return this
  263   }
  264 
  265   var data = ini.stringify(target.data)
  266 
  267   var then = function then (er) {
  268     if (er) return done(er)
  269 
  270     fs.chmod(target.path, mode, done)
  271   }
  272 
  273   var done = function done (er) {
  274     if (er) {
  275       if (cb) return cb(er)
  276       else return this.emit('error', er)
  277     }
  278     this._saving --
  279     if (this._saving === 0) {
  280       if (cb) cb()
  281       this.emit('save')
  282     }
  283   }
  284 
  285   then = then.bind(this)
  286   done = done.bind(this)
  287   this._saving ++
  288 
  289   var mode = where === 'user' ? '0600' : '0666'
  290   if (!data.trim()) {
  291     fs.unlink(target.path, function () {
  292       // ignore the possible error (e.g. the file doesn't exist)
  293       done(null)
  294     })
  295   } else {
  296     mkdirp(path.dirname(target.path), function (er) {
  297       if (er) return then(er)
  298       fs.writeFile(target.path, data, 'utf8', function (er) {
  299         if (er) return then(er)
  300         if (where === 'user' && myUid && myGid) {
  301           fs.chown(target.path, +myUid, +myGid, then)
  302         } else {
  303           then()
  304         }
  305       })
  306     })
  307   }
  308 
  309   return this
  310 }
  311 
  312 Conf.prototype.addFile = function (file, name) {
  313   name = name || file
  314   var marker = { __source__: name }
  315   this.sources[name] = { path: file, type: 'ini' }
  316   this.push(marker)
  317   this._await()
  318   fs.readFile(file, 'utf8', function (er, data) {
  319     // just ignore missing files.
  320     if (er) return this.add({}, marker)
  321 
  322     this.addString(data, file, 'ini', marker)
  323   }.bind(this))
  324   return this
  325 }
  326 
  327 // always ini files.
  328 Conf.prototype.parse = function (content, file) {
  329   return CC.prototype.parse.call(this, content, file, 'ini')
  330 }
  331 
  332 Conf.prototype.add = function (data, marker) {
  333   try {
  334     Object.keys(data).forEach(function (k) {
  335       data[k] = parseField(data[k], k)
  336     })
  337   } catch (e) {
  338     this.emit('error', e)
  339     return this
  340   }
  341   return CC.prototype.add.call(this, data, marker)
  342 }
  343 
  344 Conf.prototype.addEnv = function (env) {
  345   env = env || process.env
  346   var conf = {}
  347   Object.keys(env)
  348     .filter(function (k) { return k.match(/^npm_config_/i) })
  349     .forEach(function (k) {
  350       if (!env[k]) return
  351 
  352       // leave first char untouched, even if
  353       // it is a '_' - convert all other to '-'
  354       var p = k.toLowerCase()
  355                .replace(/^npm_config_/, '')
  356                .replace(/(?!^)_/g, '-')
  357       conf[p] = env[k]
  358     })
  359   return CC.prototype.addEnv.call(this, '', conf, 'env')
  360 }
  361 
  362 function parseField (f, k) {
  363   if (typeof f !== 'string' && !(f instanceof String)) return f
  364 
  365   // type can be an array or single thing.
  366   var typeList = [].concat(types[k])
  367   var isPath = typeList.indexOf(path) !== -1
  368   var isBool = typeList.indexOf(Boolean) !== -1
  369   var isString = typeList.indexOf(String) !== -1
  370   var isUmask = typeList.indexOf(Umask) !== -1
  371   var isNumber = typeList.indexOf(Number) !== -1
  372 
  373   f = ('' + f).trim()
  374 
  375   if (f.match(/^".*"$/)) {
  376     try {
  377       f = JSON.parse(f)
  378     } catch (e) {
  379       throw new Error('Failed parsing JSON config key ' + k + ': ' + f)
  380     }
  381   }
  382 
  383   if (isBool && !isString && f === '') return true
  384 
  385   switch (f) {
  386     case 'true': return true
  387     case 'false': return false
  388     case 'null': return null
  389     case 'undefined': return undefined
  390   }
  391 
  392   f = envReplace(f)
  393 
  394   if (isPath) {
  395     var homePattern = isWindows ? /^~(\/|\\)/ : /^~\//
  396     if (f.match(homePattern) && process.env.HOME) {
  397       f = path.resolve(process.env.HOME, f.substr(2))
  398     }
  399     f = path.resolve(f)
  400   }
  401 
  402   if (isUmask) f = umask.fromString(f)
  403 
  404   if (isNumber && !isNaN(f)) f = +f
  405 
  406   return f
  407 }
  408 
  409 function envReplace (f) {
  410   if (typeof f !== 'string' || !f) return f
  411 
  412   // replace any ${ENV} values with the appropriate environ.
  413   var envExpr = /(\\*)\$\{([^}]+)\}/g
  414   return f.replace(envExpr, function (orig, esc, name) {
  415     esc = esc.length && esc.length % 2
  416     if (esc) return orig
  417     if (undefined === process.env[name]) {
  418       throw new Error('Failed to replace env in config: ' + orig)
  419     }
  420 
  421     return process.env[name]
  422   })
  423 }
  424 
  425 function validate (cl) {
  426   // warn about invalid configs at every level.
  427   cl.list.forEach(function (conf) {
  428     nopt.clean(conf, configDefs.types)
  429   })
  430 
  431   nopt.clean(cl.root, configDefs.types)
  432 }