Skip to content

Commit

Permalink
Merge pull request #19994 from /issues/19993
Browse files Browse the repository at this point in the history
Fix npm run init to work when using NPM >= 8
  • Loading branch information
mariospr authored Dec 9, 2021
2 parents cbcc2f6 + 478bf2f commit fe479fa
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
const fs = require('fs')
const Log = require('./logging')
const { spawnSync } = require('child_process')

const getNPMConfig = (path) => {
// This is the valid way of retrieving configuration values for NPM <= 6, with
// npm_package_config_* still working up to NPM 7, but no longer for NPM >= 8.
// See https://github.com/npm/rfcs/blob/main/implemented/0021-reduce-lifecycle-script-environment.md
const getNPMConfigFromEnv = (path) => {
const key = path.join('_')
// Npm <= 6 did not preserve dashes in package.json keys
const keyNoDashes = key.replace('-', '_')
Expand All @@ -15,6 +19,29 @@ const getNPMConfig = (path) => {
process.env[package_prefix + key]
}

// From NPM >= 8, we need to inspect the package.json file, which should
// be available via the 'npm_package_json' environment variable.
const getNPMConfigFromPackageJson = (path) => {
let packages = { config: {} }
if (fs.existsSync(process.env['npm_package_json'])) {
packages = require(process.env['npm_package_json'])
}

let obj = packages.config
for (var i = 0, len = path.length; i < len; i++) {
if (!obj) {
return obj
}
obj = obj[path[i]]
}
return obj
}

const getNPMConfig = (path) => {
return getNPMConfigFromEnv(path) || getNPMConfigFromPackageJson(path)
}


const getProjectVersion = (projectName) => {
return getNPMConfig(['projects', projectName, 'tag']) || getNPMConfig(['projects', projectName, 'branch'])
}
Expand Down

0 comments on commit fe479fa

Please sign in to comment.