Skip to content

Commit

Permalink
run-script: Export the CWD that npm was run from to scripts
Browse files Browse the repository at this point in the history
Credit: @MichaelQQ
Reviewed-By: @iarna
PR-URL: npm/npm#12356
  • Loading branch information
mst-work authored and iarna committed Jul 18, 2017
1 parent b019680 commit 20c4622
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
6 changes: 6 additions & 0 deletions doc/cli/npm-run-script.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@ you should write:

instead of `"scripts": {"test": "node_modules/.bin/tap test/\*.js"}` to run your tests.

Scripts are run from the root of the module, regardless of what your current
working directory is when you call `npm run`. If you want your script to
have different behavior based on what subdirectory your in you can use the
`INIT_CWD` environment variable, which holds the full path you were in when
you ran `npm run`.

`npm run` sets the `NODE` environment variable to the `node` executable with
which `npm` is executed. Also, if the `--scripts-prepend-node-path` is passed,
the directory within which `node` resides is added to the
Expand Down
1 change: 1 addition & 0 deletions lib/utils/lifecycle.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ function lifecycle (pkg, stage, wd, unsafe, failOk, cb) {
env.npm_lifecycle_event = stage
env.npm_node_execpath = env.NODE = env.NODE || process.execPath
env.npm_execpath = require.main.filename
env.INIT_CWD = process.cwd()

// 'nobody' typically doesn't have permission to write to /tmp
// even if it's never used, sh freaks out.
Expand Down
58 changes: 58 additions & 0 deletions test/tap/lifecycle-INIT_CWD.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
var fs = require('fs')
var path = require('path')

var mkdirp = require('mkdirp')
var osenv = require('osenv')
var rimraf = require('rimraf')
var test = require('tap').test

var common = require('../common-tap.js')

var pkg = path.resolve(__dirname, 'lifecycle-initcwd')
var subdir = path.resolve(pkg, 'subdir')

var json = {
name: 'init-cwd',
version: '1.0.0',
scripts: {
initcwd: 'echo "$INIT_CWD"'
}
}

test('setup', function (t) {
cleanup()
mkdirp.sync(pkg)
mkdirp.sync(subdir)
fs.writeFileSync(
path.join(pkg, 'package.json'),
JSON.stringify(json, null, 2)
)

process.chdir(subdir)
t.end()
})

test('make sure the env.INIT_CWD is correct', function (t) {
common.npm(['run-script', 'initcwd'], {
cwd: subdir
}, function (er, code, stdout) {
if (er) throw er
t.equal(code, 0, 'exit code')
stdout = stdout.trim().split(/\r|\n/).pop()
var actual = stdout

t.equal(actual, subdir)
t.end()
})
})

test('cleanup', function (t) {
cleanup()
t.end()
})

function cleanup () {
process.chdir(osenv.tmpdir())
rimraf.sync(subdir)
rimraf.sync(pkg)
}

0 comments on commit 20c4622

Please sign in to comment.