From 760f2af3c99316e58ea1d08c5384eccba33f573b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Cruz?= Date: Sun, 29 Nov 2026 03:48:39 +0000 Subject: [PATCH] fix: run batch files by their resolved path on Windows Since 7.1.0, batch files were run through cmd.exe by their quoted name as written, e.g. `"gradle"`. When a batch file is run through a quoted name found in PATH, 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. Batch files are now run by the path they resolved to, when found. Fixes #203. --- lib/parse.js | 6 +++++- test/fixtures/own-dir/print-own-dir.bat | 1 + test/index.test.js | 10 ++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 test/fixtures/own-dir/print-own-dir.bat diff --git a/lib/parse.js b/lib/parse.js index 9c4eb71..b962869 100644 --- a/lib/parse.js +++ b/lib/parse.js @@ -72,7 +72,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 afd70e4..09c7f6f 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -306,6 +306,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!']);