diff --git a/lib/parse.js b/lib/parse.js index a2e89d4..7e1d313 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -67,7 +67,11 @@ function parseNonShell(parsed) { // Escape command & arguments // Batch files need a different escaping strategy, see `lib/util/escape.js` for more information if (isBatchFile(parsed, commandFile)) { - parsed.command = escape.batchCommand(parsed.command); + // Run the batch file by its resolved path, if it was found, otherwise as written + // When a batch file is run through a quoted name found in PATH, e.g. `"gradle"`, cmd.exe sets `%~dp0` to + // the current directory instead of the batch file's directory, which breaks batch files that use it to + // find their own files, such as Gradle's + parsed.command = escape.batchCommand(commandFile ? path.normalize(commandFile) : parsed.command); parsed.args = parsed.args.map((arg) => escape.batchArgument(arg)); } else { parsed.command = escape.command(parsed.command); diff --git a/test/fixtures/own-dir/print-own-dir.bat b/test/fixtures/own-dir/print-own-dir.bat new file mode 100644 index 0000000..66941fe --- /dev/null +++ b/test/fixtures/own-dir/print-own-dir.bat @@ -0,0 +1 @@ +@echo %~dp0 diff --git a/test/index.test.js b/test/index.test.js index d0bfbb4..76b7372 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -304,6 +304,16 @@ run.methods.forEach((method) => { } }); + it('should let batch files found in PATH know their own directory', async () => { + // cmd.exe sets %~dp0 to the current directory if a batch file is run with a quoted name found in PATH + const dir = path.join(__dirname, 'fixtures', 'own-dir'); + const env = { ...process.env, [pathKey]: `${dir}${path.delimiter}${process.env[pathKey]}` }; + + const { stdout } = await run(method, 'print-own-dir', { cwd: path.join(__dirname, 'fixtures'), env }); + + expect(stdout.trim().toLowerCase()).toBe(`${dir}${path.sep}`.toLowerCase()); + }); + it('should enable command extensions and disable delayed expansion in cmd.exe', () => { const parsed = spawn._parse(`${__dirname}/fixtures/echo-forward.bat`, ['!PATH!']);