Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/bun.js/node/types.zig
Original file line number Diff line number Diff line change
Expand Up @@ -634,6 +634,12 @@ pub const PathLike = union(enum) {
return strings.toKernel32Path(@alignCast(std.mem.bytesAsSlice(u16, buf)), normal);
}
const normal = path_handler.normalizeStringBuf(s, b, true, .windows, false);
// If the normalized path is still relative (like "."), resolve it to an absolute path
if (!std.fs.path.isAbsoluteWindows(normal)) {
const cwd_path = std.posix.getcwd(buf) catch @panic("Error getting cwd");
const resolved = path_handler.joinAbsStringBuf(cwd_path, b, &.{normal}, .windows);
return strings.toKernel32Path(@alignCast(std.mem.bytesAsSlice(u16, buf)), resolved);
}
Comment on lines +637 to +642

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Replace panic with graceful error handling for getcwd failure.

Using @panic("Error getting cwd") on line 639 will crash the entire Bun process if getcwd() fails. This can occur in legitimate scenarios such as:

  • The current directory has been deleted
  • Permission issues
  • Filesystem errors

While the fix for resolving relative paths is correct, the error handling needs improvement. Consider one of these approaches:

  1. Return a fallback path: If cwd retrieval fails, return the normalized path as-is (it may fail later in the kernel call, but with a proper error code).
  2. Propagate the error: Change the function signature to return an error type if feasible.
  3. Use a default fallback: Fall back to a known safe path like the executable's directory.

Example fix:

-        const cwd_path = std.posix.getcwd(buf) catch @panic("Error getting cwd");
+        const cwd_path = std.posix.getcwd(buf) catch {
+            // Fallback: return the normalized path as-is and let Windows APIs handle it
+            return strings.toKernel32Path(@alignCast(std.mem.bytesAsSlice(u16, buf)), normal);
+        };

Additionally, check if similar panic calls elsewhere in this function (like line 576, 583, 632) should be addressed consistently.

🤖 Prompt for AI Agents
In src/bun.js/node/types.zig around lines 637 to 642, replace the direct
@panic("Error getting cwd") on getcwd failure with graceful error handling: call
std.posix.getcwd(buf) and if it fails, either (a) return the normalized path
as-is, (b) propagate an error by changing the function signature to return an
error union so callers can handle it, or (c) use a safe fallback path (e.g.,
executable directory); ensure the chosen approach logs or surfaces the original
OS error code/message rather than aborting, and apply the same non-panic pattern
to other @panic calls in this function (lines ~576, 583, 632) for consistent
error handling.

return strings.toKernel32Path(@alignCast(std.mem.bytesAsSlice(u16, buf)), normal);
}

Expand Down
7 changes: 7 additions & 0 deletions src/resolver/resolve_path.zig
Original file line number Diff line number Diff line change
Expand Up @@ -931,6 +931,13 @@ pub fn normalizeStringGenericTZ(
buf_i += 1;
}

// If normalization resulted in an empty path, return "."
// This happens when the input is just "." or consists only of dots/separators that get normalized away
if (buf_i == buf_start and path_.len > 0) {
buf[buf_i] = '.';
buf_i += 1;
}

Comment on lines +934 to +940

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

LGTM! Essential fix to prevent empty normalized paths.

This guard correctly addresses the root cause where path normalization could produce an empty string from inputs like "." or paths consisting only of separators and dots. The condition buf_i == buf_start and path_.len > 0 properly detects when normalization produced no output despite having input, and returning "." is the correct POSIX convention for the current directory.

This change works in conjunction with the types.zig modifications to fully resolve the mkdir(".") issue on Windows.

🤖 Prompt for AI Agents
In src/resolver/resolve_path.zig around lines 934 to 940, normalization can
produce an empty output for inputs like "." or strings made only of
dots/separators; add a guard that if buf_i == buf_start and path_.len > 0 then
write a single '.' into buf and increment buf_i so the function returns "."
instead of an empty string, ensuring POSIX current-directory behavior (this
change prevents mkdir(".") issues on Windows).

if (options.zero_terminate) {
buf[buf_i] = 0;
}
Expand Down
110 changes: 110 additions & 0 deletions test/regression/issue/21901.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows } from "harness";

// https://github.com/oven-sh/bun/issues/21901
test("mkdir('.') should succeed with recursive option on Windows", async () => {
if (!isWindows) {
test.skip();
return;
}
Comment on lines +5 to +9

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider using test.skipIf for cleaner platform skipping.

The current skip logic is correct, but you can simplify it using test.skipIf:

-test("mkdir('.') should succeed with recursive option on Windows", async () => {
-  if (!isWindows) {
-    test.skip();
-    return;
-  }
+test.skipIf(!isWindows)("mkdir('.') should succeed with recursive option on Windows", async () => {

This is more idiomatic and doesn't require the early return.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
test("mkdir('.') should succeed with recursive option on Windows", async () => {
if (!isWindows) {
test.skip();
return;
}
test.skipIf(!isWindows)("mkdir('.') should succeed with recursive option on Windows", async () => {
🤖 Prompt for AI Agents
In test/regression/issue/21901.test.ts around lines 5 to 9, replace the current
manual platform skip (if (!isWindows) { test.skip(); return; }) with the more
idiomatic test.skipIf(!isWindows) at the start of the test so the test is
skipped on non-Windows without an early return; remove the if block and keep the
rest of the test body unchanged.


// Test mkdirSync with recursive option
{
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const fs = require('fs');
try {
fs.mkdirSync('.', { recursive: true });
console.log('mkdirSync success');
} catch (err) {
console.error('mkdirSync error:', err.message);
process.exit(1);
}
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stdout.trim()).toBe("mkdirSync success");
expect(exitCode).toBe(0);
}
Comment on lines +11 to +37

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial

Consider validating or logging stderr for better debugging.

The test captures stderr but never checks or logs it. Consider adding stderr validation or logging it when the test fails:

 const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

+expect(stderr.trim()).toBe(""); // or log stderr on failure
 expect(stdout.trim()).toBe("mkdirSync success");
 expect(exitCode).toBe(0);

This would make debugging easier if the test fails unexpectedly.

Apply this suggestion to all three test blocks (lines 11-37, 39-67, and 69-109).

🤖 Prompt for AI Agents
In test/regression/issue/21901.test.ts around lines 11-37 (and similarly apply
to blocks at 39-67 and 69-109), the test captures stderr but never asserts or
surfaces it on failure; update each test block to check stderr and surface its
contents when the test does not pass by asserting stderr is empty or by
appending stderr to the failure message—specifically, read proc.stderr.text() as
already done, and include a conditional that fails the test or logs the stderr
output when exitCode !== 0 or when stdout/unexpected values occur so that test
failures show the captured stderr for easier debugging.


// Test mkdir with recursive option (promise)
{
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const fs = require('fs').promises;
(async () => {
try {
await fs.mkdir('.', { recursive: true });
console.log('mkdir success');
} catch (err) {
console.error('mkdir error:', err.message);
process.exit(1);
}
})();
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stdout.trim()).toBe("mkdir success");
expect(exitCode).toBe(0);
}

// Test Promise.allSettled with multiple mkdir('.') calls
{
await using proc = Bun.spawn({
cmd: [
bunExe(),
"-e",
`
const fs = require('fs').promises;
(async () => {
try {
const results = await Promise.allSettled([
fs.mkdir('.', { recursive: true }),
fs.mkdir('.', { recursive: true }),
fs.mkdir('.', { recursive: true }),
]);

const allSucceeded = results.every(r => r.status === 'fulfilled');
if (allSucceeded) {
console.log('Promise.allSettled success');
} else {
const failed = results.filter(r => r.status === 'rejected');
console.error('Some promises failed:', failed.map(f => f.reason?.message).join(', '));
process.exit(1);
}
} catch (err) {
console.error('Promise.allSettled error:', err.message);
process.exit(1);
}
})();
`,
],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});

const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

expect(stdout.trim()).toBe("Promise.allSettled success");
expect(exitCode).toBe(0);
}
});