Skip to content

Commit

Permalink
config: Do replace environment in config files even for keys (#18426)
Browse files Browse the repository at this point in the history
 as additional replacement for values in .npmrc for example

PR-URL: npm/npm#18426
Credit: @misak113
Reviewed-By: @zkat
Reviewed-By: @iarna
  • Loading branch information
misak113 authored and zkat committed Mar 8, 2018
1 parent b57780b commit f0e998d
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/config/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,10 @@ Conf.prototype.parse = function (content, file) {
Conf.prototype.add = function (data, marker) {
try {
Object.keys(data).forEach(function (k) {
data[k] = parseField(data[k], k)
const newKey = envReplace(k)
const newField = parseField(data[k], newKey)
delete data[k]
data[newKey] = newField
})
} catch (e) {
this.emit('error', e)
Expand Down
55 changes: 55 additions & 0 deletions test/tap/config-envReplace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const fs = require('fs')
const mkdirp = require('mkdirp')
const rimraf = require('rimraf')
const path = require('path')
const ini = require('ini')
const test = require('tap').test
const npmconf = require('../../lib/config/core.js')

const packagePath = path.resolve(__dirname, 'config-envReplace')

const packageJsonFile = JSON.stringify({
name: 'config-envReplace'
})

const inputConfigFile = [
'registry=${NPM_REGISTRY_URL}',
'//${NPM_REGISTRY_HOST}/:_authToken=${NPM_AUTH_TOKEN}',
'always-auth=true',
''
].join('\n')

const expectConfigFile = [
'registry=http://my.registry.com/',
'//my.registry.com/:_authToken=xxxxxxxxxxxxxxx',
'always-auth=true',
''
].join('\n')

test('environment variables replacing in configs', function (t) {
process.env = Object.assign(process.env, {
NPM_REGISTRY_URL: 'http://my.registry.com/',
NPM_REGISTRY_HOST: 'my.registry.com',
NPM_AUTH_TOKEN: 'xxxxxxxxxxxxxxx'
})
mkdirp.sync(packagePath)
const packageJsonPath = path.resolve(packagePath, 'package.json')
const configPath = path.resolve(packagePath, '.npmrc')
fs.writeFileSync(packageJsonPath, packageJsonFile)
fs.writeFileSync(configPath, inputConfigFile)

const originalCwdPath = process.cwd()
process.chdir(packagePath)
npmconf.load(function (error, conf) {
if (error) throw error

const foundConfigFile = ini.stringify(conf.sources.project.data)
t.same(ini.parse(foundConfigFile), ini.parse(expectConfigFile))

fs.unlinkSync(packageJsonPath)
fs.unlinkSync(configPath)
rimraf.sync(packagePath)
process.chdir(originalCwdPath)
t.end()
})
})

0 comments on commit f0e998d

Please sign in to comment.