const BB = require('bluebird')
const assert = require('assert')
const chain = require('slide').chain
const detectIndent = require('detect-indent')
const detectNewline = require('detect-newline')
const fs = require('graceful-fs')
const readFile = BB.promisify(require('graceful-fs').readFile)
const git = require('./utils/git.js')
const lifecycle = require('./utils/lifecycle.js')
const log = require('npmlog')
const npm = require('./npm.js')
const output = require('./utils/output.js')
const parseJSON = require('./utils/parse-json.js')
const path = require('path')
const semver = require('semver')
const stringifyPackage = require('stringify-package')
const writeFileAtomic = require('write-file-atomic')
version.usage = 'npm version [<newversion> | major | minor | patch | premajor | preminor | prepatch | prerelease [--preid=<prerelease-id>] | from-git]' +
'\n(run in package dir)\n' +
"'npm -v' or 'npm --version' to print npm version " +
'(' + npm.version + ')\n' +
"'npm view <pkg> version' to view a package's " +
"'npm ls' to inspect current package/dependency versions"
function version (args, silent, cb_) {
if (typeof cb_ !== 'function') {
if (args.length > 1) return cb_(version.usage)
readPackage(function (er, data, indent, newline) {
if (!args.length) return dump(data, cb_)
log.error('version', 'No valid package.json found')
if (args[0] === 'from-git') {
retrieveTagVersion(silent, data, cb_)
var newVersion = semver.valid(args[0])
if (!newVersion) newVersion = semver.inc(data.version, args[0], npm.config.get('preid'))
if (!newVersion) return cb_(version.usage)
persistVersion(newVersion, silent, data, cb_)
function retrieveTagVersion (silent, data, cb_) {
], function (er, results) {
var version = results[results.length - 1]
persistVersion(version, silent, data, localData, cb_)
function parseLastGitTag (cb) {
var options = { env: process.env }
git.whichAndExec(['describe', '--abbrev=0'], options, function (er, stdout) {
if (er.message.indexOf('No names found') !== -1) return cb(new Error('No tags found'))
var prefix = npm.config.get('tag-version-prefix')
// Strip the prefix from the start of the tag:
if (tag.indexOf(prefix) === 0) tag = tag.slice(prefix.length)
var version = semver.valid(tag)
if (!version) return cb(new Error(tag + ' is not a valid version'))
function persistVersion (newVersion, silent, data, localData, cb_) {
if (typeof localData === 'function') {
if (!npm.config.get('allow-same-version') && data.version === newVersion) {
return cb_(new Error('Version not changed, might want --allow-same-version'))
data.version = newVersion
var lifecycleData = Object.create(data)
lifecycleData._id = data.name + '@' + newVersion
!localData.hasGit && [checkGit, localData],
[lifecycle, lifecycleData, 'preversion', where],
[updatePackage, newVersion, silent],
[lifecycle, lifecycleData, 'version', where],
[commit, localData, newVersion],
[lifecycle, lifecycleData, 'postversion', where]
function readPackage (cb) {
var packagePath = path.join(npm.localPrefix, 'package.json')
fs.readFile(packagePath, 'utf8', function (er, data) {
if (er) return cb(new Error(er))
indent = detectIndent(data).indent
newline = detectNewline(data)
cb(er, data, indent, newline)
function updatePackage (newVersion, silent, cb_) {
if (!er && !silent) output('v' + newVersion)
readPackage(function (er, data, indent, newline) {
if (er) return cb(new Error(er))
data.version = newVersion
write(data, 'package.json', indent, newline, cb)
function commit (localData, newVersion, cb) {
updateShrinkwrap(newVersion, function (er, hasShrinkwrap, hasLock) {
if (er || !localData.hasGit) return cb(er)
localData.hasShrinkwrap = hasShrinkwrap
localData.hasPackageLock = hasLock
_commit(newVersion, localData, cb)
const SHRINKWRAP = 'npm-shrinkwrap.json'
const PKGLOCK = 'package-lock.json'
function readLockfile (name) {
path.join(npm.localPrefix, name), 'utf8'
).catch({code: 'ENOENT'}, () => null)
function updateShrinkwrap (newVersion, cb) {
readLockfile(SHRINKWRAP),
(shrinkwrap, lockfile) => {
if (!shrinkwrap && !lockfile) {
return cb(null, false, false)
const file = shrinkwrap ? SHRINKWRAP : PKGLOCK
data = parseJSON(shrinkwrap || lockfile)
indent = detectIndent(shrinkwrap || lockfile).indent
newline = detectNewline(shrinkwrap || lockfile)
log.error('version', `Bad ${file} data.`)
data.version = newVersion
write(data, file, indent, newline, (err) => {
log.error('version', `Failed to update version in ${file}`)
return cb(null, !!shrinkwrap, !!lockfile)
function dump (data, cb) {
if (data && data.name && data.version) v[data.name] = data.version
Object.keys(process.versions).sort().forEach(function (k) {
v[k] = process.versions[k]
if (npm.config.get('json')) v = JSON.stringify(v, null, 2)
function statGitFolder (cb) {
fs.stat(path.join(npm.localPrefix, '.git'), cb)
function callGitStatus (cb) {
[ 'status', '--porcelain' ],
function cleanStatusLines (stdout) {
var lines = stdout.trim().split('\n').filter(function (line) {
return line.trim() && !line.match(/^\?\? /)
function verifyGit (cb) {
function checkStatus (er) {
callGitStatus(checkStdout)
function checkStdout (er, stdout) {
var lines = cleanStatusLines(stdout)
'Git working directory not clean.\n' + lines.join('\n')
statGitFolder(checkStatus)
function checkGit (localData, cb) {
statGitFolder(function (er) {
var doGit = !er && npm.config.get('git-tag-version')
if (er && npm.config.get('git-tag-version')) log.verbose('version', 'error checking for .git', er)
log.verbose('version', 'not tagging in git')
callGitStatus(function (er, stdout) {
if (er && er.code === 'ENOGIT') {
'This is a Git checkout, but the git command was not found.',
'npm could not create a Git tag for this release!'
var lines = cleanStatusLines(stdout)
if (lines.length && !npm.config.get('force')) {
'Git working directory not clean.\n' + lines.join('\n')
module.exports.buildCommitArgs = buildCommitArgs
function buildCommitArgs (args) {
if (args[0] === 'commit') args.shift()
if (!npm.config.get('commit-hooks')) add.push('-n')
if (npm.config.get('allow-same-version')) add.push('--allow-empty')
return ['commit', ...add, ...args]
module.exports.buildTagFlags = buildTagFlags
function buildTagFlags () {
npm.config.get('sign-git-tag') ? 's' : '',
npm.config.get('allow-same-version') ? 'f' : '',
function _commit (version, localData, cb) {
const options = { env: process.env }
const message = npm.config.get('message').replace(/%s/g, version)
const signCommit = npm.config.get('sign-git-commit')
const commitArgs = buildCommitArgs([
...(signCommit ? ['-S', '-m'] : ['-m']),
stagePackageFiles(localData, options).then(() => {
return git.exec(commitArgs, options)
if (!localData.existingTag) {
'tag', npm.config.get('tag-version-prefix') + version,
function stagePackageFiles (localData, options) {
return addLocalFile('package.json', options, false).then(() => {
if (localData.hasShrinkwrap) {
return addLocalFile('npm-shrinkwrap.json', options, true)
} else if (localData.hasPackageLock) {
return addLocalFile('package-lock.json', options, true)
function addLocalFile (file, options, ignoreFailure) {
const p = git.exec(['add', path.join(npm.localPrefix, file)], options)
function write (data, file, indent, newline, cb) {
assert(data && typeof data === 'object', 'must pass data to version write')
assert(typeof file === 'string', 'must pass filename to write to version write')
log.verbose('version.write', 'data', data, 'to', file)
path.join(npm.localPrefix, file),
stringifyPackage(data, indent, newline),