Repository navigation
feat(io): Add append option to Bun.write, BunFile.write and FileSink (BunFile.writer) - #25751
mattermoran wants to merge 9 commits into
Conversation
WalkthroughAdds an Changes
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/bun.js/webcore/Blob.zig (1)
1050-1072: CRITICAL: File-to-file copy path doesn't support append mode.When both source and destination are file-backed blobs, the code uses an optimized file copy path (lines 1051-1072). However, this path doesn't check the
appendflag fromoptions, meaningBun.write(destFile, srcFile, { append: true })will silently overwrite the destination instead of appending to it.Either:
- Skip this optimization when
appendis true and fall through to the bytes-based write path, or- Return an error indicating that file-to-file append is not supported
🔎 Proposed fix to skip optimization for append mode
} // If this is file <> file, we can just copy the file - else if (destination_type == .file and source_type == .file) { + else if (destination_type == .file and source_type == .file and (options.append orelse false) == false) { if (comptime Environment.isWindows) {
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zigtest/js/bun/io/bun-write-append.test.ts
🧰 Additional context used
📓 Path-based instructions (5)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Usebun:testwith files that end in*.test.{ts,js,jsx,tsx,mjs,cjs}
Do not write flaky tests. Never wait for time to pass in tests; always wait for the condition to be met instead of using an arbitrary amount of time
Never use hardcoded port numbers in tests. Always useport: 0to get a random port
Prefer concurrent tests over sequential tests usingtest.concurrentordescribe.concurrentwhen multiple tests spawn processes or write files, unless it's very difficult to make them concurrent
When spawning Bun processes in tests, usebunExeandbunEnvfromharnessto ensure the same build of Bun is used and debug logging is silenced
Use-eflag for single-file tests when spawning Bun processes
UsetempDir()from harness to create temporary directories with files for multi-file tests instead of creating files manually
Prefer async/await over callbacks in tests
When callbacks must be used and it's just a single callback, usePromise.withResolversto create a promise that can be resolved or rejected from a callback
Do not set a timeout on tests. Bun already has timeouts
UseBuffer.alloc(count, fill).toString()instead of'A'.repeat(count)to create repetitive strings in tests, as ''.repeat is very slow in debug JavaScriptCore builds
Usedescribeblocks for grouping related tests
Always useawait usingorusingto ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc
Always check exit codes and test error scenarios in error tests
Usedescribe.each()for parameterized tests
UsetoMatchSnapshot()for snapshot testing
UsebeforeAll(),afterEach(),beforeEach()for setup/teardown in tests
Track resources (servers, clients) in arrays for cleanup inafterEach()
Files:
test/js/bun/io/bun-write-append.test.ts
**/*.test.ts?(x)
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.ts?(x): Never usebun testdirectly - always usebun bd testto run tests with debug build changes
For single-file tests, prefer-eflag overtempDir
For multi-file tests, prefertempDirandBun.spawnover single-file tests
UsenormalizeBunSnapshotto normalize snapshot output of tests
Never write tests that check for 'panic', 'uncaught exception', or similar strings in test output
UsetempDirfromharnessto create temporary directories - do not usetmpdirSyncorfs.mkdtempSync
When spawning processes in tests, expect stdout before expecting exit code for more useful error messages on test failure
Do not write flaky tests - do not usesetTimeoutin tests; instead await the condition to be met
Verify tests fail withUSE_SYSTEM_BUN=1 bun test <file>and pass withbun bd test <file>- tests are invalid if they pass with USE_SYSTEM_BUN=1
Test files must end with.test.tsor.test.tsx
Avoid shell commands likefindorgrepin tests - use Bun's Glob and built-in tools instead
Files:
test/js/bun/io/bun-write-append.test.ts
test/**/*.test.ts?(x)
📄 CodeRabbit inference engine (CLAUDE.md)
Always use
port: 0in tests - do not hardcode ports or use custom random port number functions
Files:
test/js/bun/io/bun-write-append.test.ts
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Private fields in Zig are fully supported using the#prefix:struct { #foo: u32 };
Use decl literals in Zig for declaration initialization:const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer@importat the bottom of the file (auto formatter will move them automatically)
Files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zig
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zig
🧠 Learnings (20)
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output
Applied to files:
test/js/bun/io/bun-write-append.test.tspackages/bun-types/bun.d.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : For multi-file tests, prefer `tempDir` and `Bun.spawn` over single-file tests
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` with files that end in `*.test.{ts,js,jsx,tsx,mjs,cjs}`
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-19T02:44:46.354Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/context-propagation.test.ts:1-1
Timestamp: 2025-10-19T02:44:46.354Z
Learning: In the Bun repository, standalone packages under packages/ (e.g., bun-vscode, bun-inspector-protocol, bun-plugin-yaml, bun-plugin-svelte, bun-debug-adapter-protocol, bun-otel) co-locate their tests with package source code using *.test.ts files. This follows standard npm/monorepo patterns. The test/ directory hierarchy (test/js/bun/, test/cli/, test/js/node/) is reserved for testing Bun's core runtime APIs and built-in functionality, not standalone packages.
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Verify tests fail with `USE_SYSTEM_BUN=1 bun test <file>` and pass with `bun bd test <file>` - tests are invalid if they pass with USE_SYSTEM_BUN=1
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/js/node/test/{parallel,sequential}/*.js : For test/js/node/test/{parallel,sequential}/*.js files without a .test extension, use `bun bd <file>` instead of `bun bd test <file>` since these expect exit code 0 and don't use bun's test runner
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : When spawning Bun processes in tests, use `bunExe` and `bunEnv` from `harness` to ensure the same build of Bun is used and debug logging is silenced
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `-e` flag for single-file tests when spawning Bun processes
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Never use `bun test` directly - always use `bun bd test` to run tests with debug build changes
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Always use `await using` or `using` to ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `tempDir()` from harness to create temporary directories with files for multi-file tests instead of creating files manually
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().
Applied to files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive already maintains internal state to prevent issues from multiple ref/unref calls, so additional idempotence guards are not needed when calling poll_ref.ref() and poll_ref.unref().
Applied to files:
src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive uses a simple state machine (active/inactive/done) rather than reference counting, with internal status field preventing issues from multiple ref/unref calls, making additional idempotence guards unnecessary.
Applied to files:
src/bun.js/webcore/blob/write_file.zig
🔇 Additional comments (3)
test/js/bun/io/bun-write-append.test.ts (1)
1-51: Append behavior tests are clear, isolated, and follow harness conventionsThese four tests exercise both
Bun.writeandBun.file().writewithappend: truefor existing and non‑existent files, usetempDir+usingcorrectly, and assert both content and length. No issues spotted.src/bun.js/webcore/Blob.zig (2)
1206-1210: LGTM: WriteFileOptions extended with append field.The addition of the
appendfield toWriteFileOptionsis correctly implemented with an appropriate default value ofnull, and it's properly threaded through to the underlyingWriteFileandWriteFileWindowsconstructors.
4609-4617: Verify that all callers ofFileOpenerimplementgetOpenFlags()correctly.The new
getOpenFlagsForContexthelper dynamically determines open flags by checking if the context has:
- A
getOpenFlags()method (preferred), or- An
open_flagsfield (fallback)For append functionality to work correctly, contexts using
FileOpenermust implementgetOpenFlags()to return the appropriate flags (includingO_APPENDwhen needed).Please verify that:
WriteFileimplementsgetOpenFlags(this: *const WriteFile) c_intWriteFileWindowsimplements a similar method- These methods correctly check the
appendfield and returnO_APPENDinstead ofO_TRUNCwhenappend == true
Jarred-Sumner
left a comment
There was a problem hiding this comment.
Thanks for this
We need to handle the separate code path for when both src and dest are a file, like Bun.write(Bun.file(a), Bun.file(b), { append: true }). Instead we should make it use the read write fallback codepath for that case I think? Ideally we would simply append the contents and that is possible to do, I think for linux in most cases but it's tricky and will need to be tested. I don't think it's doable on macOS or Windows.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/bun.js/webcore/Blob.zig (1)
1051-1071: File-to-file copy silently ignoresappendoption.The PR description states that file-to-file copies are not supported in append mode, but this code path doesn't validate or throw an error when
options.appendis true. Users attemptingBun.write(fileA, fileB, { append: true })will have their append option silently ignored.Consider adding validation before the copy:
🔎 Proposed fix
// If this is file <> file, we can just copy the file else if (destination_type == .file and source_type == .file) { + if (options.append orelse false) { + return globalThis.throwInvalidArguments("Cannot use append option with file-to-file copy. Read the source file first, then write with append.", .{}); + } if (comptime Environment.isWindows) {
♻️ Duplicate comments (2)
src/bun.js/webcore/Blob.zig (2)
1548-1553: UsegetBooleanLooseinstead ofgetTruthyas previously suggested.A previous reviewer (Jarred-Sumner) suggested using
getBooleanLoosehere for parsing the boolean option.🔎 Proposed fix
- if (try options_object.getTruthy(globalThis, "append")) |append_value| { - if (!append_value.isBoolean()) { - return globalThis.throwInvalidArgumentType("write", "options.append", "boolean"); - } - append = append_value.toBoolean(); - } + if (try options_object.getBooleanLoose(globalThis, "append")) |append_value| { + append = append_value; + }
2312-2317: UsegetBooleanLooseinstead ofgetTruthyas previously suggested.A previous reviewer (Jarred-Sumner) suggested using
getBooleanLoosehere for parsing the boolean option.🔎 Proposed fix
- if (try options_object.getTruthy(globalThis, "append")) |append_value| { - if (!append_value.isBoolean()) { - return globalThis.throwInvalidArgumentType("write", "options.append", "boolean"); - } - append = append_value.toBoolean(); - } + if (try options_object.getBooleanLoose(globalThis, "append")) |append_value| { + append = append_value; + }
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/bun.js/webcore/Blob.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Private fields in Zig are fully supported using the#prefix:struct { #foo: u32 };
Use decl literals in Zig for declaration initialization:const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer@importat the bottom of the file (auto formatter will move them automatically)
Files:
src/bun.js/webcore/Blob.zig
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/Blob.zig
🧠 Learnings (8)
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-16T17:32:03.074Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/install/PackageManager/PackageManagerOptions.zig:187-193
Timestamp: 2025-10-16T17:32:03.074Z
Learning: In Bun's codebase (particularly in files like src/install/PackageManager/PackageManagerOptions.zig), mixing bun.EnvVar.*.get() and bun.EnvVar.*.platformGet() for environment variable lookups is intentional and safe. The code is protected by compile-time platform checks (Environment.isWindows, etc.), and compilation will fail if the wrong function is used on the wrong platform. This pattern should not be flagged as a consistency issue.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
src/bun.js/webcore/Blob.zig
🔇 Additional comments (3)
src/bun.js/webcore/Blob.zig (3)
4609-4617: Clean helper for dynamic open flag selection.The
getOpenFlagsForContexthelper nicely encapsulates the logic for determining open flags by checking for agetOpenFlagsmethod first, then falling back toopen_flagsfield, and finally defaulting toRDONLY. This enablesWriteFileto dynamically compute flags based on the append setting.
1256-1265: Fast path correctly bypassed for append operations.The logic to skip the fast path when
options.appendis true is correct since the fast path usesO_CREAT | O_WRONLYwithoutO_APPEND. Append operations require the async path that properly handles theO_APPENDflag.
1024-1039: Append option correctly propagated to WriteFile constructors.The
options.append orelse falseis properly passed to bothWriteFileWindows.createandWriteFile.create, enabling the underlying write logic to set appropriate flags.
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/bun.js/webcore/Blob.zig (2)
1050-1071: File-to-file copy silently ignoresappendoption.When both source and destination are files, the code uses
CopyFilewhich doesn't receive or handle theappendparameter. The PR summary states "file-to-file copies are not supported in append mode", but currently theappendflag is silently ignored rather than rejected.Consider adding an explicit check to throw an error when append mode is requested for file-to-file copies:
🔎 Proposed fix
// If this is file <> file, we can just copy the file else if (destination_type == .file and source_type == .file) { + if (options.append) { + return globalThis.throwInvalidArguments("Append mode is not supported for file-to-file copies", .{}); + } if (comptime Environment.isWindows) { return Blob.copy_file.CopyFileWindows.init(
850-862: Empty source incorrectly truncates file in append mode.When
options.appendis true but the source is empty (triggering this function), the file is still truncated to 0 bytes. Appending empty data should leave the file unchanged.🔎 Proposed fix
fn writeFileWithEmptySourceToDestination(ctx: *jsc.JSGlobalObject, destination_blob: *Blob, options: WriteFileOptions) bun.JSError!jsc.JSValue { // SAFETY: null-checked by caller const destination_store = destination_blob.store.?; defer destination_blob.detach(); switch (destination_store.data) { .file => |file| { + // In append mode with empty source, the file should remain unchanged + if (options.append) { + return jsc.JSPromise.resolvedPromiseValue(ctx, jsc.JSValue.jsNumber(0)); + } // TODO: make this async const node_fs = ctx.bunVM().nodeFS(); var result = node_fs.truncate(.{
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (1)
src/bun.js/webcore/Blob.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Private fields in Zig are fully supported using the#prefix:struct { #foo: u32 };
Use decl literals in Zig for declaration initialization:const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer@importat the bottom of the file (auto formatter will move them automatically)
Files:
src/bun.js/webcore/Blob.zig
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/Blob.zig
🧠 Learnings (8)
📓 Common learnings
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `-e` flag for single-file tests when spawning Bun processes
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` with files that end in `*.test.{ts,js,jsx,tsx,mjs,cjs}`
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
src/bun.js/webcore/Blob.zig
🔇 Additional comments (6)
src/bun.js/webcore/Blob.zig (6)
1206-1210: LGTM!The
append: boolfield is appropriately added toWriteFileOptions. All call sites explicitly provide this value.
1255-1266: LGTM!The fast path correctly skips when
appendis true, ensuring append operations go through the async write path that properly handles append semantics with the appropriate open flags.
1537-1559: LGTM!The
appendoption parsing inwriteFileis well-implemented:
- Defaults to
falsefor backward compatibility- Uses
getBooleanLooseper reviewer suggestion- Properly threads the value through to
writeFileInternal
2275-2322: LGTM!The
appendoption handling indoWrite(forBunFile.write) mirrors the implementation inwriteFile(forBun.write), ensuring consistent behavior across both APIs.
1022-1040: LGTM!The
appendflag is correctly passed to both Windows and non-Windows write file implementations.
3603-3665: LGTM!The
getOpenFlagsForContexthelper provides a clean abstraction for computing open flags:
- First checks for a
getOpenFlags()instance method (allowing dynamic flag computation based on options likeappend)- Falls back to a static
open_flagsconstant- Defaults to
RDONLYif neither existsThis enables write implementations to dynamically include
O_APPENDwhen needed.
d123fc4 to
cc203b1
Compare
|
@Jarred-Sumner good suggestion about read write loop. seems to be working just fine. while doing that I ended up adding append to noticed a weird thing though: Also fixed an inconsistency with source types between As for os optimized appends I will take investigate that separately. p.s the size caching issue is more noticeable now with appends because grabbing a file, appending and checking the content will keep returning the old one but #25702 addresses that |
append option to Bun.write and BunFile.writeappend option to Bun.write, BunFile.write and BunFile.writer
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
src/bun.js/webcore/Blob.zig (2)
2420-2450: S3 path silently ignoresappendparameter.The
pipeReadableStreamToBlobfunction accepts anappendparameter but when the destination is S3, it ignores the flag entirely. S3 object storage doesn't support append semantics natively.Consider throwing an error when
append: trueis used with S3 destinations to avoid silent data loss where users expect append behavior but get overwrite behavior instead.🔎 Proposed fix
pub fn pipeReadableStreamToBlob(this: *Blob, globalThis: *jsc.JSGlobalObject, readable_stream: jsc.WebCore.ReadableStream, extra_options: ?JSValue, append: bool) bun.JSError!jsc.JSValue { var store = this.store orelse { return jsc.JSPromise.dangerouslyCreateRejectedPromiseValueWithoutNotifyingVM(globalThis, globalThis.createErrorInstance("Blob is detached", .{})); }; if (this.isS3()) { + if (append) { + return globalThis.throwInvalidArguments("Append mode is not supported for S3 files", .{}); + } const s3 = &this.store.?.data.s3;
2651-2712: S3 path ingetWriterignoresappendoption.Similar to
pipeReadableStreamToBlob, the S3 path ingetWriterdoesn't check theappendflag. When users callfile.writer({ append: true })on an S3 file, the option is silently ignored.🔎 Proposed fix
if (this.isS3()) { + if (append) { + return globalThis.throwInvalidArguments("Append mode is not supported for S3 files", .{}); + } const s3 = &this.store.?.data.s3; const path = s3.path();packages/bun-types/bun.d.ts (1)
724-749: Bun.write append typings look correct; consider tightening docs around overwrite vs append semantics
- Extending the main
write(destination: BunFile | S3File | PathLike, …)overload to acceptReadableStream | Requestand threadingappend?: booleanthrough all the relevant overload option objects is type‑safe and matches the described behavior (defaultfalsepreserves existing truncate semantics).- The notes on the file‑to‑file overloads (“When
append: true, the optimized copy is not used”) are helpful and correctly scoped.One minor docs nit: the JSDoc for the
Responseoverloads and the copy overloads still state that the destination “will be overwritten / truncated” without mentioning theappendescape hatch. Consider adding a short clarification that those overwrite/truncate statements apply whenappendis omitted/false so the comments stay strictly accurate now that append is supported.Also applies to: 763-784, 796-817, 830-831, 874-875, 840-861, 883-905
♻️ Duplicate comments (1)
src/bun.js/webcore/blob/write_file.zig (1)
25-35: Append flag integration in WriteFile and open‑flag computation look goodAdding
append: bool = falsetoWriteFile, threading it throughcreateWithCtx/create, and usinggetOpenFlags()to switch betweenO.APPENDandO.TRUNCwhile preservingNONBLOCK|CREAT|WRONLYmaintains backwards‑compatible defaults and cleanly encodes append semantics for POSIX writes. No new issues spotted in this path.Also applies to: 78-99, 100-123
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (9)
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/FileSink.zigsrc/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/S3File.zigsrc/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/blob/write_file.zigsrc/bun.js/webcore/streams.zigtest/js/bun/io/bun-write-append.test.ts
🧰 Additional context used
📓 Path-based instructions (5)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}
📄 CodeRabbit inference engine (test/CLAUDE.md)
test/**/*.test.{ts,js,jsx,tsx,mjs,cjs}: Usebun:testwith files that end in*.test.{ts,js,jsx,tsx,mjs,cjs}
Do not write flaky tests. Never wait for time to pass in tests; always wait for the condition to be met instead of using an arbitrary amount of time
Never use hardcoded port numbers in tests. Always useport: 0to get a random port
Prefer concurrent tests over sequential tests usingtest.concurrentordescribe.concurrentwhen multiple tests spawn processes or write files, unless it's very difficult to make them concurrent
When spawning Bun processes in tests, usebunExeandbunEnvfromharnessto ensure the same build of Bun is used and debug logging is silenced
Use-eflag for single-file tests when spawning Bun processes
UsetempDir()from harness to create temporary directories with files for multi-file tests instead of creating files manually
Prefer async/await over callbacks in tests
When callbacks must be used and it's just a single callback, usePromise.withResolversto create a promise that can be resolved or rejected from a callback
Do not set a timeout on tests. Bun already has timeouts
UseBuffer.alloc(count, fill).toString()instead of'A'.repeat(count)to create repetitive strings in tests, as ''.repeat is very slow in debug JavaScriptCore builds
Usedescribeblocks for grouping related tests
Always useawait usingorusingto ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc
Always check exit codes and test error scenarios in error tests
Usedescribe.each()for parameterized tests
UsetoMatchSnapshot()for snapshot testing
UsebeforeAll(),afterEach(),beforeEach()for setup/teardown in tests
Track resources (servers, clients) in arrays for cleanup inafterEach()
Files:
test/js/bun/io/bun-write-append.test.ts
**/*.test.ts?(x)
📄 CodeRabbit inference engine (CLAUDE.md)
**/*.test.ts?(x): Never usebun testdirectly - always usebun bd testto run tests with debug build changes
For single-file tests, prefer-eflag overtempDir
For multi-file tests, prefertempDirandBun.spawnover single-file tests
UsenormalizeBunSnapshotto normalize snapshot output of tests
Never write tests that check for 'panic', 'uncaught exception', or similar strings in test output
UsetempDirfromharnessto create temporary directories - do not usetmpdirSyncorfs.mkdtempSync
When spawning processes in tests, expect stdout before expecting exit code for more useful error messages on test failure
Do not write flaky tests - do not usesetTimeoutin tests; instead await the condition to be met
Verify tests fail withUSE_SYSTEM_BUN=1 bun test <file>and pass withbun bd test <file>- tests are invalid if they pass with USE_SYSTEM_BUN=1
Test files must end with.test.tsor.test.tsx
Avoid shell commands likefindorgrepin tests - use Bun's Glob and built-in tools instead
Files:
test/js/bun/io/bun-write-append.test.ts
test/**/*.test.ts?(x)
📄 CodeRabbit inference engine (CLAUDE.md)
Always use
port: 0in tests - do not hardcode ports or use custom random port number functions
Files:
test/js/bun/io/bun-write-append.test.ts
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Private fields in Zig are fully supported using the#prefix:struct { #foo: u32 };
Use decl literals in Zig for declaration initialization:const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer@importat the bottom of the file (auto formatter will move them automatically)
Files:
src/bun.js/webcore/S3File.zigsrc/bun.js/webcore/streams.zigsrc/bun.js/webcore/blob/write_file.zigsrc/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/FileSink.zigsrc/bun.js/webcore/blob/copy_file.zig
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/S3File.zigsrc/bun.js/webcore/streams.zigsrc/bun.js/webcore/blob/write_file.zigsrc/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/FileSink.zigsrc/bun.js/webcore/blob/copy_file.zig
🧠 Learnings (26)
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output
Applied to files:
test/js/bun/io/bun-write-append.test.tspackages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` with files that end in `*.test.{ts,js,jsx,tsx,mjs,cjs}`
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : For multi-file tests, prefer `tempDir` and `Bun.spawn` over single-file tests
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-19T02:44:46.354Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/context-propagation.test.ts:1-1
Timestamp: 2025-10-19T02:44:46.354Z
Learning: In the Bun repository, standalone packages under packages/ (e.g., bun-vscode, bun-inspector-protocol, bun-plugin-yaml, bun-plugin-svelte, bun-debug-adapter-protocol, bun-otel) co-locate their tests with package source code using *.test.ts files. This follows standard npm/monorepo patterns. The test/ directory hierarchy (test/js/bun/, test/cli/, test/js/node/) is reserved for testing Bun's core runtime APIs and built-in functionality, not standalone packages.
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/js/node/test/{parallel,sequential}/*.js : For test/js/node/test/{parallel,sequential}/*.js files without a .test extension, use `bun bd <file>` instead of `bun bd test <file>` since these expect exit code 0 and don't use bun's test runner
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Verify tests fail with `USE_SYSTEM_BUN=1 bun test <file>` and pass with `bun bd test <file>` - tests are invalid if they pass with USE_SYSTEM_BUN=1
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `-e` flag for single-file tests when spawning Bun processes
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : When spawning Bun processes in tests, use `bunExe` and `bunEnv` from `harness` to ensure the same build of Bun is used and debug logging is silenced
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Applied to files:
test/js/bun/io/bun-write-append.test.tspackages/bun-types/bun.d.ts
📚 Learning: 2025-12-16T00:21:32.179Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-16T00:21:32.179Z
Learning: Applies to **/*.test.ts?(x) : Use `normalizeBunSnapshot` to normalize snapshot output of tests
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-24T18:37:30.259Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:30.259Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Always use `await using` or `using` to ensure proper resource cleanup in tests for APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-11-06T00:58:23.965Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24417
File: test/js/bun/spawn/spawn.test.ts:903-918
Timestamp: 2025-11-06T00:58:23.965Z
Learning: In Bun test files, `await using` with spawn() is appropriate for long-running processes that need guaranteed cleanup on scope exit or when explicitly testing disposal behavior. For short-lived processes that exit naturally (e.g., console.log scripts), the pattern `const proc = spawn(...); await proc.exited;` is standard and more common, as evidenced by 24 instances vs 4 `await using` instances in test/js/bun/spawn/spawn.test.ts.
Applied to files:
test/js/bun/io/bun-write-append.test.ts
📚 Learning: 2025-10-16T02:17:35.237Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 23710
File: src/analytics.zig:15-21
Timestamp: 2025-10-16T02:17:35.237Z
Learning: In src/analytics.zig and similar files using bun.EnvVar boolean environment variables: the new EnvVar API for boolean flags (e.g., bun.EnvVar.do_not_track.get(), bun.EnvVar.ci.get()) is designed to parse and return boolean values from environment variables, not just check for their presence. This is an intentional design change from the previous presence-based checks using bun.getenvZ().
Applied to files:
src/bun.js/webcore/streams.zigsrc/bun.js/webcore/FileSink.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive already maintains internal state to prevent issues from multiple ref/unref calls, so additional idempotence guards are not needed when calling poll_ref.ref() and poll_ref.unref().
Applied to files:
src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-15T20:47:57.118Z
Learnt from: cirospaciari
Repo: oven-sh/bun PR: 22696
File: src/sql/mysql/js/JSMySQLConnection.zig:306-322
Timestamp: 2025-09-15T20:47:57.118Z
Learning: bun.Async.KeepAlive uses a simple state machine (active/inactive/done) rather than reference counting, with internal status field preventing issues from multiple ref/unref calls, making additional idempotence guards unnecessary.
Applied to files:
src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-19T19:55:22.427Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 22568
File: src/valkey/js_valkey_functions.zig:853-854
Timestamp: 2025-09-19T19:55:22.427Z
Learning: In Bun's JSPromise API, `resolvedPromiseValue(globalThis: *JSGlobalObject, value: JSValue) JSValue` returns a JSValue directly (not a JSPromise that needs `.toJS()` called on it). This is different from `resolvedPromise()` which returns a *JSPromise that would need `.toJS()`.
Applied to files:
src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-11-24T18:37:47.899Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/AGENTS.md:0-0
Timestamp: 2025-11-24T18:37:47.899Z
Learning: Applies to src/bun.js/bindings/v8/**/<UNKNOWN> : <UNKNOWN>
Applied to files:
src/bun.js/webcore/blob/write_file.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.
Applied to files:
src/bun.js/webcore/FileSink.zigpackages/bun-types/bun.d.ts
📚 Learning: 2025-09-02T18:25:27.976Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 22227
File: src/allocators/allocation_scope.zig:284-314
Timestamp: 2025-09-02T18:25:27.976Z
Learning: In bun's custom Zig implementation, the `#` prefix for private fields is valid syntax and should not be flagged as invalid. The syntax `#fieldname` creates private fields that cannot be accessed from outside the defining struct, and usage like `self.#fieldname` is correct within the same struct. This applies to fields like `#parent`, `#state`, `#allocator`, `#trace`, etc. throughout the codebase.
Applied to files:
src/bun.js/webcore/FileSink.zig
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664
Applied to files:
packages/bun-types/bun.d.ts
🔇 Additional comments (32)
src/bun.js/webcore/S3File.zig (1)
126-169: LGTM: S3 writes correctly disable append.Both write paths (path-backed and blob-backed) explicitly set
append = false, which correctly reflects that S3 writes don't support append semantics.src/bun.js/webcore/S3Client.zig (1)
211-232: LGTM: S3Client write correctly disables append.Consistent with S3File changes, append is explicitly disabled for S3 write operations.
test/js/bun/io/bun-write-append.test.ts (3)
5-15: LGTM: Well-structured append test.Test correctly verifies that append: true appends to existing content and checks both content and size.
124-136: LGTM: Important truncation test.This test verifies that
append: falseproperly truncates existing content, ensuring the default truncate behavior is preserved.
138-148: LGTM: Critical edge case test.This test ensures that empty writes with
append: truedon't truncate the file, which is important for preserving file content when no new data is written.src/bun.js/webcore/FileSink.zig (1)
49-60: LGTM: Append flag correctly replaces truncate with inverted logic.The field change from
truncate: bool = truetoappend: bool = falsemaintains backward compatibility while adding append support. The flags() function correctly maps:
append = false→O.TRUNC(default: overwrite)append = true→O.APPEND(new: append)src/bun.js/webcore/streams.zig (2)
123-128: LGTM: Append flag parsing is safe and correct.Default value is
false, and the flag is only set to true if explicitly provided as a boolean in JS options.
115-182: LGTM: Append flag consistently propagated through all FileSink construction paths.The append flag is correctly threaded through all three FileSink construction scenarios:
- Path-based (line 143)
- FD-based (line 163)
- Default/fallback (line 179)
This ensures append behavior works regardless of how the FileSink is constructed.
src/bun.js/webcore/Blob.zig (11)
855-858: LGTM!The early return for append mode with empty source is correct—appending nothing should leave the file unchanged and return 0 bytes written.
1029-1086: LGTM!The
appendoption is consistently propagated through all write paths (WriteFileWindows, WriteFile, CopyFileWindows, CopyFile, and pipeReadableStreamToBlob).
1213-1217: LGTM!The
append: boolfield is correctly added toWriteFileOptions. All call sites explicitly initialize this field.
1263-1272: LGTM!Correctly skipping the fast path for append operations—the fast path doesn't support append semantics since it opens files without
O_APPEND.
1415-1425: LGTM!The
appendflag is correctly propagated toWriteFileWaitFromLockedValueTaskfor deferred body handling.
1492-1498: LGTM!ReadableStream handling correctly propagates the
appendflag topipeReadableStreamToBlob.
1554-1574: LGTM!Good implementation following the pattern suggested in past reviews: initializing
appendtofalseand usinggetBooleanLooseto parse the option.
2292-2337: LGTM!The
doWritemethod correctly handles theappendoption with the same pattern aswriteFile, maintaining API consistency betweenBun.write()andBunFile.write().
2640-2646: LGTM!The
getWritermethod correctly parses theappendoption, enabling append mode for file writers.
4629-4637: LGTM!Good abstraction for determining open flags. The function correctly checks for a
getOpenFlagsmethod first (allowing dynamic flags based on append mode), falls back to a staticopen_flagsfield, then defaults to read-only. This cleanly supports the append feature without duplicating flag logic.
4673-4691: LGTM!The
getOpenFlagsForContext(this)calls correctly use the new abstraction in both Windows and non-Windows file opening paths, enabling append mode support.packages/bun-types/bun.d.ts (1)
1324-1335: BunFile.writer/write append surface matches Bun.write and looks consistentThe new
append?: booleanoption onBunFile.writer()andBunFile.write()is wired consistently with the top‑levelBun.writeoverloads (same default and JSDoc contract), and the expandeddataunion (includingReadableStream,Request,Response,BunFile) aligns with the runtime behavior described elsewhere. No type‑level issues spotted here.Also applies to: 1376-1399
src/bun.js/webcore/blob/write_file.zig (2)
360-361: Windows append semantics and flag plumbing are consistent with POSIX pathOn the Windows side, the new
append: boolfield is correctly:
- Captured in
createWithCtx/createand stored on the struct.- Reflected in
open()viaflagschoosinguv.O.APPENDvsuv.O.TRUNCon top of the existing base flags.- Left intentionally unused for
.fdpathlikes, so existing descriptors (stdin/stdout/stderr or user‑provided FDs) keep whatever mode they were opened with.This matches the POSIX behavior and keeps default truncate semantics when
appendis false/omitted.Also applies to: 367-387, 424-438, 641-660
688-689: Append option correctly propagated through WriteFileWaitFromLockedValueTask to Blob.writeFileWithSourceDestinationExtending
WriteFileWaitFromLockedValueTaskwith anappend: bool = falseand forwarding it intoBlob.writeFileWithSourceDestinationvia.{ .mkdirp_if_not_exists = this.mkdirp_if_not_exists, .append = this.append }ensures the promise‑based/Body.Value path honors append semantics consistently with the direct write APIs. Lifetimes (file_blob.detach, promise deinit, and handler destruction) remain unchanged and look safe.Also applies to: 694-722
src/bun.js/webcore/blob/copy_file.zig (10)
21-21: LGTM!The
appendfield is correctly added with a sensible default offalse, preserving backward compatibility.
133-136: LGTM!The helper cleanly encapsulates the conditional flag selection for destination file opening.
420-420: LGTM!Correctly disabling the
clonefilefast path whenappendis true, asclonefilecreates a full copy rather than appending content.
601-603: LGTM!Correctly guards against truncation when in append mode, preserving the appended content.
625-625: LGTM!Consistent with the
CopyFilestruct's field addition.
856-892: LGTM!The
appendparameter is correctly threaded through, with appropriate open flags (O.APPENDvsO.TRUNC) selected based on the mode.
898-917: LGTM!Correctly passes
this.appendfor the destination andfalsefor the source, since only the destination file needs append semantics.
930-935: LGTM!Correctly bypasses
uv_fs_copyfilefor append mode, as the libuv API doesn't support appending. The read-write loop fallback is the appropriate mechanism.
27-51: LGTM!The
appendparameter is correctly threaded through thecreatefunction and used to initialize the struct.
827-854: LGTM!The
appendparameter is correctly threaded through theinitfunction, consistent with theCopyFile.createpattern.
append option to Bun.write, BunFile.write and BunFile.writerappend option to Bun.write, BunFile.write and FileSink (BunFile.writer)
| switch (bun.sys.open( | ||
| path, | ||
| bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK, | ||
| bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK | (if (append) bun.O.APPEND else bun.O.TRUNC), |
There was a problem hiding this comment.
This didn't previously use O_TRUNC so we should continue to not use O_TRUNC
| bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK | (if (append) bun.O.APPEND else bun.O.TRUNC), | |
| bun.O.WRONLY | bun.O.CREAT | bun.O.NONBLOCK | (if (append) bun.O.APPEND else 0), |
There was a problem hiding this comment.
updated though I find the non truncating behavior of the FileSink confusing as I mentioned in my message
There was a problem hiding this comment.
actually now that I think about it I think it's a bug. normal .write does not pass the trunc flag for performance but it still truncates the file after the write but for filesink it just starts writing over the file. I can handle that in a separate PR after this one
|
removed the truncation where there wasn't before |
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
src/bun.js/webcore/blob/copy_file.zig (1)
625-631: Windows append path risks truncating existing files inonCompleteThe Windows changes correctly:
- Add an
append: boolfield toCopyFileWindowsand thread it throughinit.- Pass
appendintopreparePathlikeso destinations are opened withWRONLY | CREAT | APPENDwhen appending.- Route
append: truethroughprepareReadWriteLoop()instead ofuv_fs_copyfile, disabling the optimized copy in append mode.However,
onComplete()still unconditionally usesthis.sizeto decide whether to truncate:pub fn onComplete(this: *CopyFileWindows, written_actual: usize) void { var written = written_actual; if (written != @as(@TypeOf(written), @intCast(this.size)) and this.size != Blob.max_size) { this.truncate(); written = @intCast(this.size); } ... }In append mode,
this.sizerepresents the expected number of bytes copied, not the final file size (which includes pre‑existing data). If this condition ever trips for an append operation (for example due to a short write whensizewas set from metadata),truncate()will shrink the entire destination file tothis.size, discarding existing content that should have been preserved by append.To keep append safe while leaving existing behavior unchanged for overwrite mode,
truncate()should be skipped whenappendis true:Suggested fix: guard truncation behind
!this.appendpub fn onComplete(this: *CopyFileWindows, written_actual: usize) void { var written = written_actual; - if (written != @as(@TypeOf(written), @intCast(this.size)) and this.size != Blob.max_size) { - this.truncate(); - written = @intCast(this.size); - } + if (!this.append and written != @as(@TypeOf(written), @intCast(this.size)) and this.size != Blob.max_size) { + this.truncate(); + written = @intCast(this.size); + } const globalThis = this.event_loop.global; const promise = this.promise.swap(); ... }This keeps non‑append semantics intact while ensuring append operations never retroactively truncate existing files.
Also applies to: 829-848, 858-895, 896-930, 932-937, 1103-1108
packages/bun-types/bun.d.ts (1)
763-785: Docs for Response/BunFile copy overloads should mentionappendsemanticsThe Response and BunFile copy overloads now correctly accept
append?: booleaninoptions, and you’ve added a note thatappend: truedisables the optimized copy path, which matches the Zig implementation.The remaining prose in these JSDoc blocks still says the destination “will be overwritten” and “destination will be truncated” without mentioning the
appendcase, which is now inaccurate whenappend: true.Consider updating the text to something like:
- “If
appendis not set orfalse, the file is overwritten…”- “When
append: true, data is appended and the existing contents are not truncated; optimized copy paths are disabled.”That keeps the behavior clear for both modes and avoids confusion when reading the docs.
Also applies to: 796-817, 819-905
♻️ Duplicate comments (1)
src/bun.js/webcore/blob/copy_file.zig (1)
130-137: Re‑introducingO.TRUNCfor destinations — confirm intended semantics/perf trade‑off
openDestinationFlags()now usesO.TRUNCwhenappendis false, sodoOpenFile()truncates the destination immediately on open in the non‑append case:fn openDestinationFlags(this: *const CopyFile) i32 { const mode: i32 = if (this.append) O.APPEND else O.TRUNC; return O.CLOEXEC | O.CREAT | O.WRONLY | mode; }Previously there was feedback (from Jarred) that
O_TRUNCwas intentionally avoided here for performance reasons (overwrite in place + ftruncate later). This helper changes that behavior again.If the new eager‑truncate semantics are intentional, consider documenting that decision; otherwise, it may be worth dropping
O.TRUNCand relying on the existing truncation logic after copy, to avoid the extra zeroing cost.Also applies to: 162-201
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/copy_file.zig
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Private fields in Zig are fully supported using the#prefix:struct { #foo: u32 };
Use decl literals in Zig for declaration initialization:const decl: Decl = .{ .binding = 0, .value = 0 };
Prefer@importat the bottom of the file (auto formatter will move them automatically)
Files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
🧠 Learnings (13)
📚 Learning: 2025-11-03T20:40:59.655Z
Learnt from: pfgithub
Repo: oven-sh/bun PR: 24273
File: src/bun.js/bindings/JSValue.zig:545-586
Timestamp: 2025-11-03T20:40:59.655Z
Learning: In Bun's Zig codebase, JSErrors (returned as `bun.JSError!T`) must always be properly handled. Using `catch continue` or `catch { break; }` to silently suppress JSErrors is a bug. Errors should either be explicitly handled or propagated with `try`. This applies to snapshot serializer error handling where Jest's behavior is to throw when serializers throw.
Applied to files:
src/bun.js/webcore/blob/copy_file.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.
Applied to files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
src/bun.js/webcore/Blob.zigpackages/bun-types/bun.d.ts
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-20T19:51:32.288Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24880
File: packages/bun-vscode/package.json:382-385
Timestamp: 2025-11-20T19:51:32.288Z
Learning: In the Bun repository, dependencies may be explicitly added to package.json files (even when not directly imported in code) to force version upgrades on transitive dependencies, particularly as part of Aikido security scanner remediation to ensure vulnerable transitive dependencies resolve to patched versions.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-19T04:55:33.099Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: test/js/bun/http/node-telemetry.test.ts:27-203
Timestamp: 2025-10-19T04:55:33.099Z
Learning: In test/js/bun/http/node-telemetry.test.ts and the Bun.telemetry._node_binding API, after the architecture refactor, the _node_binding interface only contains two methods: handleIncomingRequest(req, res) and handleWriteHead(res, statusCode). The handleRequestFinish hook and other lifecycle hooks were removed during simplification. Both current methods are fully tested.
Applied to files:
packages/bun-types/bun.d.ts
🧬 Code graph analysis (1)
packages/bun-types/bun.d.ts (2)
src/codegen/bindgenv2/internal/interfaces.ts (1)
Blob(21-40)src/codegen/bindgenv2/lib.ts (1)
Blob(10-10)
🔇 Additional comments (16)
src/bun.js/webcore/blob/copy_file.zig (4)
20-47: Append flag is correctly threaded throughCopyFile.createThe new
append: boolfield andcreate(..., append: bool)parameter are wired consistently into theCopyFileinitializer, so downstream logic can reliably distinguish append vs truncate behavior. No issues here.
420-467: Gatingclonefileon!appendis correct and avoids incompatible fast‑pathThe added
!this.appendcheck in the macOSclonefilefast path ensures append operations never go throughclonefile, which only supports whole‑file clones. That avoids subtle “append but actually overwrite” behavior and correctly forces append operations down the regular open/copy path.
522-538: Linux append fallback looks correct; double‑check offset usage for append casesThe Linux
appendbranch now:
- Unconditionally falls back to
copyFileUsingReadWriteLoopwhenthis.appendis true.- Correctly updates
read_lenfromtotal_written.- Calls
this.doClose()on both.errand.resultpaths, fixing the earlier FD leak.One thing to verify: this path ignores
this.offsetand just passesthis.source_fdinto the read/write loop. IfCopyFile.createis ever called with a non‑zero offset in append mode (e.g.Bun.write(dest, Bun.file(src).slice(begin), { append: true })), we’ll currently append from the start of the source file rather than fromoffset.If such combinations are valid, we probably need to either:
- Seek
source_fdtothis.offsetbefore entering the loop, or- Extend
copyFileUsingReadWriteLoopto accept an initial offset.If append + offset is supposed to be unsupported, consider asserting
this.offset == 0whenthis.appendis true.
580-607: macOS append fallback and truncation gating align with expected semanticsOn macOS, the new
appendbranch:
- Routes appends through
copyFileUsingReadWriteLoop(noclonefile/fcopyfilefast paths).- Ensures
this.doClose()runs on both success and error.- Gently changes the post‑copy truncation to only run when
!this.append:if (!this.append and stat.size != 0 and @as(SizeType, @intCast(stat.size)) > this.max_length) { _ = darwin.ftruncate(..., @intCast(this.max_length)); }This prevents accidental shrinking of an existing file when appending, while preserving previous truncate‑on‑short‑copy behavior for non‑append writes. Looks good.
packages/bun-types/bun.d.ts (2)
724-749: Top‑levelBun.writeoverload matches new runtime capabilitiesThe widened
inputunion (addingReadableStreamandRequest) and the newappend?: booleanoption are consistent with the runtime changes (stream sources and append semantics), and the JSDoc clearly explains overwrite vs append behavior and defaultcreatePath. This overload looks accurate and ready for external consumers.
1324-1332:BunFile.writerandBunFile.writeappend options and input unions align with Bun.writeThe updates to:
BunFile.writer(options?: { highWaterMark?: number; append?: boolean })BunFile.write(data: Blob | NodeJS.TypedArray | ArrayBufferLike | string | BlobPart[] | ReadableStream | Request | Response | BunFile, options?: { highWaterMark?: number; append?: boolean })bring the instance APIs in line with the top‑level
Bun.writeoverloads (same source types, same append semantics). The JSDoc forappendis clear and consistent with the new behavior. No issues from a typings standpoint.Also applies to: 1373-1396
src/bun.js/webcore/Blob.zig (10)
855-858: LGTM! Correct early return for append with empty source.Appending an empty source should leave the file unchanged, and returning immediately with a resolved promise (0 bytes written) is the correct behavior. This avoids the truncation logic below that applies to non-append writes.
1262-1273: LGTM! Fast path correctly skipped for append operations.The logic properly checks
options.append == falsebefore allowing the fast synchronous write path. This is intentional per the PR design, as append operations require proper file positioning that the fast path doesn't handle.
1492-1498: LGTM! ReadableStream support correctly implemented.The new ReadableStream source handling is well-implemented:
- Properly checks if the stream has already been used (disturbed)
- Correctly cleans up resources (detaches destination_blob) on error
- Threads the
appendflag through topipeReadableStreamToBlobThis aligns with the PR objective of adding ReadableStream support for
.write().
1554-1575: LGTM! Option extraction follows established patterns.The
appendoption is correctly extracted from the options object:
- Defaults to
false(preserve existing behavior)- Uses
getBooleanLoosefor proper coercion (as per past feedback)- Properly passed through to
writeFileInternal
2292-2337: LGTM! Consistent option handling in BunFile.write().The
appendoption extraction indoWrite(forBunFile.write()) mirrors the pattern used inwriteFile(forBun.write()), ensuring consistent behavior across both APIs.
2464-2465: LGTM! Open flags correctly use O_APPEND when appending.The conditional addition of
bun.O.APPENDbased on the append flag is correct. Note thatO_TRUNCis intentionally not used here (as confirmed by past review feedback), as truncation logic is handled separately in FileSink when appropriate.
2640-2646: LGTM! Append option properly added to FileSink writer.The append option extraction for
getWriter(which backsBun.file().writer()) is correctly implemented and consistent with the other write APIs. This fulfills the PR objective of extendingFileSinkto support append.
4629-4637: LGTM! Excellent abstraction for context-specific open flags.The
getOpenFlagsForContextfunction is a well-designed abstraction that allows different contexts to specify their own open flags (includingO_APPENDorO_TRUNCbased on append mode). The compile-time reflection using@hasDeclmakes this generic function work cleanly with multiple context types while maintaining type safety.This centralizes flag determination logic and makes
FileOpenermore maintainable.
4676-4691: LGTM! Consistent use of getOpenFlagsForContext abstraction.Both file open paths (Windows/libuv and POSIX) correctly use
getOpenFlagsForContext(this)to obtain the appropriate flags from the context. This allows WriteFile, CopyFile, and other contexts to specify their own flags (includingO_APPENDwhen append mode is enabled) while maintaining consistent baseline flags (O_NONBLOCK | O_CLOEXEC).
1216-1216: Overall: Well-implemented append functionality across all write paths.The
appendoption has been cleanly integrated throughout the Blob/File write infrastructure:✅ Consistent API design: The option is uniformly extracted and validated across
Bun.write(),BunFile.write(), andBunFile.writer()✅ Correct semantics:
- Empty source + append = no-op (file unchanged)
- Fast path correctly skipped for append operations
- Open flags properly use
O_APPENDwhen needed✅ Good abstractions: The
getOpenFlagsForContexthelper cleanly separates flag determination logic✅ Feature additions: ReadableStream support integrates well with the append functionality
The implementation aligns with the PR objectives and handles edge cases appropriately.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In @src/bun.js/webcore/Blob.zig:
- Line 1220: The new append: bool field in the Blob type lacks documentation;
add a short doc comment above the append field explaining its purpose and
behavior (e.g., when append == true the blob write should append to existing
data, when false the write should truncate/overwrite), note any default
semantics and how it interacts with existing write/truncate logic (e.g., whether
truncation occurs only on false or on open modes), and keep the comment concise
and placed immediately above the append field declaration to clarify expected
runtime behavior.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (4)
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/S3File.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/S3File.zigsrc/bun.js/webcore/Blob.zig
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Use the#prefix for private fields in Zig structs, e.g.,struct { #foo: u32 };
Use Decl literals in Zig, e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };
Place@importstatements at the bottom of the file in Zig (auto formatter will handle positioning)
Never use@import()inline inside functions in Zig; always place imports at the bottom of the file or containing struct
Files:
src/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/S3File.zigsrc/bun.js/webcore/Blob.zig
🧠 Learnings (15)
📚 Learning: 2026-01-05T16:32:07.551Z
Learnt from: alii
Repo: oven-sh/bun PR: 25474
File: src/bun.js/event_loop/Sigusr1Handler.zig:0-0
Timestamp: 2026-01-05T16:32:07.551Z
Learning: In Zig codebases (e.g., Bun), treat std.posix.sigaction as returning void and do not perform runtime error handling for its failure. The Zig standard library views sigaction failures as programmer errors (unreachable) because they only occur with invalid signals like SIGKILL/SIGSTOP. Apply this pattern across Zig files that call sigaction (e.g., crash_handler.zig, main.zig, filter_run.zig, process.zig) and ensure failures are not handled as recoverable errors; prefer reaching an explicit unreachable/compile-time assumption when such failures are detected.
Applied to files:
src/bun.js/webcore/S3Client.zigsrc/bun.js/webcore/S3File.zigsrc/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zig
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun bd test <...test file>` to run tests with compiled code changes. Do not use `bun test` as it will not include your changes.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-20T19:51:32.288Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24880
File: packages/bun-vscode/package.json:382-385
Timestamp: 2025-11-20T19:51:32.288Z
Learning: In the Bun repository, dependencies may be explicitly added to package.json files (even when not directly imported in code) to force version upgrades on transitive dependencies, particularly as part of Aikido security scanner remediation to ensure vulnerable transitive dependencies resolve to patched versions.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` for files ending in `*.test.{ts,js,jsx,tsx,mjs,cjs}`. For test files without .test extension in test/js/node/test/{parallel,sequential}/*.js, use `bun bd <file>` instead of `bun bd test <file>` since they expect exit code 0.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:47.899Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/AGENTS.md:0-0
Timestamp: 2025-11-24T18:37:47.899Z
Learning: Applies to src/bun.js/bindings/v8/**/<UNKNOWN> : <UNKNOWN>
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/bun.js/webcore/Blob.zig
🔇 Additional comments (15)
src/bun.js/webcore/Blob.zig (6)
855-858: LGTM - Correct handling of append with empty source.The early return for append mode with an empty source is correct—appending nothing should be a no-op that leaves the file unchanged. The comment clearly explains the intent.
1498-1504: LGTM - ReadableStream support properly implemented.The new ReadableStream handling correctly checks if the stream is disturbed before piping, properly detaches the destination blob on error, and passes the append flag through to pipeReadableStreamToBlob.
1560-1572: LGTM - Option parsing is correct and maintains backward compatibility.The append option defaults to
false, preserving existing behavior. UsinggetBooleanLoosefor parsing allows flexible coercion of truthy values.
2472-2472: File opening flags are correct for append mode.The conditional addition of
bun.O.APPENDwhenappendis true correctly implements append semantics at the OS level. When append is false, the file is opened withWRONLY | CREAT | NONBLOCKwithoutO_TRUNC, which is deliberate per past review feedback for performance reasons.
2648-2654: LGTM - getWriter correctly reads and defaults the append option.The append option parsing follows the same pattern as other write methods, defaulting to
falsefor backward compatibility.
4639-4647: Good refactoring to consolidate file opening flag logic.The new
getOpenFlagsForContexthelper provides a clean way for different contexts to specify their open flags while ensuring common flags likeNONBLOCKandCLOEXECare always added. The append behavior is appropriately delegated to context-specific implementations throughgetOpenFlags()oropen_flags.src/bun.js/webcore/S3File.zig (1)
160-160: LGTM - Explicitly disabling append for S3 operations is correct.S3 doesn't support atomic append operations, so explicitly passing
append: falseis appropriate. The explicit false makes the intent clear and documents that append is not supported for S3 writes.Also applies to: 166-166
src/bun.js/webcore/S3Client.zig (1)
232-232: LGTM - Consistent with S3File, correctly disabling append for S3.Like S3File.zig, this correctly passes
append: falsesince S3 doesn't support atomic append operations.packages/bun-types/bun.d.ts (7)
724-749: LGTM! Expanded input types and append option properly added.The input type expansion to include
ReadableStream | Requestaligns with the PR objectives. Theappendoption is well-documented with clear behavior description and correct default value.
763-784: LGTM! Append option correctly added for Response input.The append option is properly documented and consistent with other overloads.
796-817: LGTM! Append option properly documented.Consistent implementation across Response input overloads.
830-861: LGTM! Good documentation of performance implications.The note at lines 830-831 about optimized copy paths being disabled when
append: trueis valuable information for users. The append option is properly documented.
874-904: LGTM! Consistent documentation for file copy operations.The performance note about optimized copy paths and the append option are both properly documented, consistent with the BunFile destination overload.
1324-1331: LGTM! FileSink writer now supports append mode.The append option is properly added to
BunFile.writer()with clear documentation, enabling append support for FileSink as mentioned in the PR objectives.
1373-1396: LGTM! BunFile.write() types aligned with Bun.write().The expanded input types (including ReadableStream, Request, Response, and BunFile) properly align the supported source types between
Bun.write()andBunFile.write()as stated in the PR objectives. The append option is well-documented and consistent with other APIs.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/bun-types/bun.d.ts (1)
778-845: Docs forappendsemantics look good; consider cross-referencingappendin the generic overload docs.
The Response-specific overloads clearly state truncate vs append behavior (Lines 782-784, 817-819). That clarity is missing from the “generic input” overload (Lines 767-775) where users are most likely to look first. Consider adding a brief “append=false truncates” sentence to the generic overload JSDoc as well (or referencing these overloads).
🤖 Fix all issues with AI agents
In @packages/bun-types/bun.d.ts:
- Around line 1379-1386: The JSDoc for BunFile.writer's options is ambiguous
about append=false; update the comment on the writer(options?: { append?:
boolean }) signature (the writer method that returns FileSink) to explicitly
state that when append is false or omitted the file is truncated (overwritten)
rather than preserved, and keep @default false to match Bun.write docs and the
PR behavior.
- Around line 1428-1451: Introduce shared type aliases for the duplicated input
union and options and use them in both Bun.write and BunFile.write signatures:
create a type alias (e.g., WriteInput = Blob | NodeJS.TypedArray |
ArrayBufferLike | string | BlobPart[] | ReadableStream | Request | Response |
BunFile) and an options alias (e.g., WriteAppendOptions = { highWaterMark?:
number; append?: boolean }) and replace the inline union and options object in
the write(...) overloads with these aliases so both Bun.write and BunFile.write
reference the single source of truth.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (3)
packages/bun-types/bun.d.tssrc/bun.js/webcore/Blob.zigsrc/bun.js/webcore/blob/copy_file.zig
🧰 Additional context used
📓 Path-based instructions (2)
**/*.zig
📄 CodeRabbit inference engine (CLAUDE.md)
In Zig code, be careful with allocators and use defer for cleanup
Files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
src/**/*.zig
📄 CodeRabbit inference engine (src/CLAUDE.md)
src/**/*.zig: Use the#prefix for private fields in Zig structs, e.g.,struct { #foo: u32 };
Use Decl literals in Zig, e.g.,const decl: Decl = .{ .binding = 0, .value = 0 };
Place@importstatements at the bottom of the file in Zig (auto formatter will handle positioning)
Never use@import()inline inside functions in Zig; always place imports at the bottom of the file or containing struct
Files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
🧠 Learnings (15)
📚 Learning: 2025-11-03T20:40:59.655Z
Learnt from: pfgithub
Repo: oven-sh/bun PR: 24273
File: src/bun.js/bindings/JSValue.zig:545-586
Timestamp: 2025-11-03T20:40:59.655Z
Learning: In Bun's Zig codebase, JSErrors (returned as `bun.JSError!T`) must always be properly handled. Using `catch continue` or `catch { break; }` to silently suppress JSErrors is a bug. Errors should either be explicitly handled or propagated with `try`. This applies to snapshot serializer error handling where Jest's behavior is to throw when serializers throw.
Applied to files:
src/bun.js/webcore/blob/copy_file.zig
📚 Learning: 2025-09-02T19:17:26.376Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 0
File: :0-0
Timestamp: 2025-09-02T19:17:26.376Z
Learning: In Bun's Zig codebase, when handling error unions where the same cleanup operation (like `rawFree`) needs to be performed regardless of success or failure, prefer using boolean folding with `else |err| switch (err)` over duplicating the cleanup call in multiple switch branches. This approach avoids code duplication while maintaining compile-time error checking.
Applied to files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
📚 Learning: 2026-01-05T16:32:07.551Z
Learnt from: alii
Repo: oven-sh/bun PR: 25474
File: src/bun.js/event_loop/Sigusr1Handler.zig:0-0
Timestamp: 2026-01-05T16:32:07.551Z
Learning: In Zig codebases (e.g., Bun), treat std.posix.sigaction as returning void and do not perform runtime error handling for its failure. The Zig standard library views sigaction failures as programmer errors (unreachable) because they only occur with invalid signals like SIGKILL/SIGSTOP. Apply this pattern across Zig files that call sigaction (e.g., crash_handler.zig, main.zig, filter_run.zig, process.zig) and ensure failures are not handled as recoverable errors; prefer reaching an explicit unreachable/compile-time assumption when such failures are detected.
Applied to files:
src/bun.js/webcore/blob/copy_file.zigsrc/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/src/napi/napi.zig : For each new V8 C++ method, add both GCC/Clang and MSVC mangled symbol names to the V8API struct in src/napi/napi.zig using extern fn declarations
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-11-14T16:07:01.064Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 24719
File: docs/bundler/executables.mdx:527-560
Timestamp: 2025-11-14T16:07:01.064Z
Learning: In the Bun repository, certain bundler features like compile with code splitting (--compile --splitting) are CLI-only and not supported in the Bun.build() JavaScript API. Tests for CLI-only features use backend: "cli" flag (e.g., test/bundler/bundler_compile_splitting.test.ts). The CompileBuildConfig interface correctly restricts these with splitting?: never;. When documenting CLI-only bundler features, add a note clarifying they're not available via the programmatic API.
Applied to files:
src/bun.js/webcore/Blob.zigpackages/bun-types/bun.d.ts
📚 Learning: 2025-10-24T10:43:09.398Z
Learnt from: fmguerreiro
Repo: oven-sh/bun PR: 23774
File: src/install/PackageManager/updatePackageJSONAndInstall.zig:548-548
Timestamp: 2025-10-24T10:43:09.398Z
Learning: In Bun's Zig codebase, the `as(usize, intCast(...))` cast pattern triggers a Zig compiler bug that causes compilation to hang indefinitely when used in complex control flow contexts (loops + short-circuit operators + optional unwrapping). Avoid this pattern and use simpler alternatives like just `intCast(...)` if type casting is necessary.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-09-12T18:16:50.754Z
Learnt from: RiskyMH
Repo: oven-sh/bun PR: 22606
File: src/glob/GlobWalker.zig:449-452
Timestamp: 2025-09-12T18:16:50.754Z
Learning: For Bun codebase: prefer using `std.fs.path.sep` over manual platform separator detection, and use `bun.strings.lastIndexOfChar` instead of `std.mem.lastIndexOfScalar` for string operations.
Applied to files:
src/bun.js/webcore/Blob.zig
📚 Learning: 2025-10-19T02:52:37.412Z
Learnt from: theshadow27
Repo: oven-sh/bun PR: 23798
File: packages/bun-otel/tsconfig.json:1-15
Timestamp: 2025-10-19T02:52:37.412Z
Learning: In the Bun repository, packages under packages/ (e.g., bun-otel) can follow a TypeScript-first pattern where package.json exports point directly to .ts files (not compiled .js files). Bun natively runs TypeScript, so consumers import .ts sources directly and receive full type information without needing compiled .d.ts declaration files. For such packages, adding "declaration": true or "outDir" in tsconfig.json is unnecessary and would break the export structure.
<!-- [remove_learning]
ceedde95-980e-4898-a2c6-40ff73913664
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:36:59.706Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/bun.js/bindings/v8/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:36:59.706Z
Learning: Applies to src/bun.js/bindings/v8/test/v8/v8.test.ts : Add corresponding test cases to test/v8/v8.test.ts using checkSameOutput() function to compare Node.js and Bun output
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-17T20:50:58.644Z
Learnt from: taylordotfish
Repo: oven-sh/bun PR: 23755
File: src/bun.js/api/bun/socket/Handlers.zig:154-159
Timestamp: 2025-10-17T20:50:58.644Z
Learning: In Bun socket configuration error messages (src/bun.js/api/bun/socket/Handlers.zig), use the user-facing JavaScript names "data" and "drain" instead of internal field names "onData" and "onWritable", as these are the names users see in the API according to SocketConfig.bindv2.ts.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun bd test <...test file>` to run tests with compiled code changes. Do not use `bun test` as it will not include your changes.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-24T18:37:11.466Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: src/js/CLAUDE.md:0-0
Timestamp: 2025-11-24T18:37:11.466Z
Learning: Write JS builtins for Bun's Node.js compatibility and APIs, and run `bun bd` after changes
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-10-26T01:32:04.844Z
Learnt from: Jarred-Sumner
Repo: oven-sh/bun PR: 24082
File: test/cli/test/coverage.test.ts:60-112
Timestamp: 2025-10-26T01:32:04.844Z
Learning: In the Bun repository test files (test/cli/test/*.test.ts), when spawning Bun CLI commands with Bun.spawnSync for testing, prefer using stdio: ["inherit", "inherit", "inherit"] to inherit stdio streams rather than piping them.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2025-11-20T19:51:32.288Z
Learnt from: markovejnovic
Repo: oven-sh/bun PR: 24880
File: packages/bun-vscode/package.json:382-385
Timestamp: 2025-11-20T19:51:32.288Z
Learning: In the Bun repository, dependencies may be explicitly added to package.json files (even when not directly imported in code) to force version upgrades on transitive dependencies, particularly as part of Aikido security scanner remediation to ensure vulnerable transitive dependencies resolve to patched versions.
Applied to files:
packages/bun-types/bun.d.ts
📚 Learning: 2026-01-05T23:04:01.518Z
Learnt from: CR
Repo: oven-sh/bun PR: 0
File: test/CLAUDE.md:0-0
Timestamp: 2026-01-05T23:04:01.518Z
Learning: Applies to test/**/*.test.{ts,js,jsx,tsx,mjs,cjs} : Use `bun:test` for files ending in `*.test.{ts,js,jsx,tsx,mjs,cjs}`. For test files without .test extension in test/js/node/test/{parallel,sequential}/*.js, use `bun bd <file>` instead of `bun bd test <file>` since they expect exit code 0.
Applied to files:
packages/bun-types/bun.d.ts
🧬 Code graph analysis (1)
packages/bun-types/bun.d.ts (1)
src/codegen/bindgenv2/internal/interfaces.ts (1)
Blob(21-40)
🔇 Additional comments (31)
src/bun.js/webcore/blob/copy_file.zig (12)
22-22: LGTM!The
appendfield is properly added with a sensible default offalse, and correctly propagated through thecreatefunction to the struct initializer.Also applies to: 37-37, 49-49
154-157: LGTM!The
openDestinationFlagsmethod correctly computes the destination open flags, choosingO.APPENDfor append mode andO.TRUNCfor normal writes.
189-189: LGTM!Correctly uses the dynamic
openDestinationFlags()method instead of hardcoded flags.
442-442: LGTM!Correctly skips the
clonefilefast path when appending, sinceclonefilecreates a new copy and cannot append to an existing file.
554-570: LGTM!The Linux append path correctly falls back to the read-write loop, which will work with the
O_APPENDflag set on the destination file descriptor.
612-628: LGTM!The macOS append path correctly mirrors the Linux implementation, falling back to the read-write loop for append operations.
635-635: LGTM!Correctly skips truncation when appending, preserving the existing file content that was just appended to.
663-663: LGTM!The
appendfield is properly added toCopyFileWindowsand correctly propagated through theinitfunction.Also applies to: 870-870, 884-884
896-907: LGTM!The
preparePathlikefunction correctly uses theappendparameter to determine open flags for writing, addingO.APPENDwhen needed.
938-938: LGTM!Correctly passes
this.appendfor the destination andfalsefor the source, since append only applies to write operations.Also applies to: 951-951
970-975: LGTM!Correctly bypasses
uv_fs_copyfilewhen appending, since that syscall cannot append to files.
1143-1147: LGTM!Correctly skips truncation in
onCompletewhen appending, preventing data loss.src/bun.js/webcore/Blob.zig (17)
855-858: LGTM!Correct optimization: appending an empty source should be a no-op, so returning early with 0 bytes written is appropriate.
1029-1029: LGTM!The
appendflag is correctly propagated to both Windows and non-Windows write file implementations.Also applies to: 1044-1044
1063-1063: LGTM!The
appendflag is correctly propagated to the file copy implementations for file-to-file operations.Also applies to: 1077-1077
1088-1088: LGTM!The
appendflag is correctly passed when piping from S3 to a file destination.
1218-1223: LGTM!The
WriteFileOptionsstruct correctly includes theappendfield, and since it's a private struct, having it as a required field is appropriate.
1268-1278: LGTM!Correctly skips the fast write path when appending, since the fast path doesn't support
O_APPENDsemantics.
1427-1427: LGTM!The
appendflag is correctly propagated toWriteFileWaitFromLockedValueTaskfor both Response and Request locked bodies.Also applies to: 1490-1490
1500-1506: LGTM!Correctly handles
ReadableStreamas a source and pipes it to the blob with theappendflag. This addresses the PR objective of adding ReadableStream support.
1563-1563: LGTM!The
writeFilefunction correctly parses theappendoption from the options object and propagates it towriteFileInternal.Also applies to: 1585-1587, 1596-1596
2315-2315: LGTM!The
doWritefunction correctly parses theappendoption and passes it towriteFileInternal.Also applies to: 2348-2350, 2356-2360
2443-2443: LGTM!The
pipeReadableStreamToBlobfunction signature correctly includes theappendparameter.
2488-2489: LGTM!Correctly adds
O.APPENDto the open flags when appending on Windows.
2564-2564: LGTM!The
appendflag is correctly passed to theFileSinkstream start configuration.
2664-2670: LGTM!The
getWriterfunction correctly parses theappendoption from the options object.
2748-2748: LGTM!Both Windows and non-Windows paths in
getWritercorrectly use theappendflag when opening/configuring the file writer.Also applies to: 2824-2824
4655-4663: LGTM!The
getOpenFlagsForContextfunction provides a flexible mechanism for types to specify dynamic open flags (e.g., based onappend), with sensible fallbacks.
4702-4702: LGTM!Both Windows and non-Windows paths in
getFdByOpeningcorrectly use the dynamicgetOpenFlagsForContextfunction.Also applies to: 4717-4717
packages/bun-types/bun.d.ts (2)
846-960: Good: explicit “optimized copy disabled when appending”; verify behavior for append+copy edge cases.
The note about skipping optimized copy paths whenappend: trueis helpful (Lines 857-862, 915-920). One thing to sanity-check in tests/behavior (if not already):append: truewithinput === destination(same file) and with non-empty destination—ensure it either errors or produces deterministic results.
751-776: Add explicitBun.write()overloads for S3File with Response, or restrict S3File to Blob-like inputs only in the generic overload.
The firstwrite()overload includesS3Fileas a destination withRequestandReadableStreamin the input union (line 753), but there's no correspondingResponseoverload for S3File. SinceBunFilehas dedicatedResponseoverloads and tests don't validateBun.write(s3file, Request), clarify whether Request/ReadableStream are supported for S3File destinations or restrict them to filesystem/BunFile operations only. If S3File should support Response bodies, add a matching overload; if not, narrow the first overload's input union to exclude Request/ReadableStream when the destination is S3File.
| writer(options?: { | ||
| highWaterMark?: number; | ||
| /** | ||
| * If `true`, append to the end of the file. | ||
| * @default false | ||
| */ | ||
| append?: boolean; | ||
| }): FileSink; |
There was a problem hiding this comment.
BunFile.writer({ append }) docs are ambiguous about the non-append default (truncate vs overwrite-in-place).
Right now it only says “append to the end” and @default false (Lines 1382-1385), but doesn’t state what false does. Given the PR fixes truncation behavior when not appending, please spell out “If false/omitted, the file is truncated (overwritten)” to align with Bun.write docs.
Proposed doc tweak
writer(options?: {
highWaterMark?: number;
/**
* If `true`, append to the end of the file.
+ *
+ * If `false` or omitted, the file will be truncated (overwritten).
* @default false
*/
append?: boolean;
}): FileSink;📝 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.
| writer(options?: { | |
| highWaterMark?: number; | |
| /** | |
| * If `true`, append to the end of the file. | |
| * @default false | |
| */ | |
| append?: boolean; | |
| }): FileSink; | |
| writer(options?: { | |
| highWaterMark?: number; | |
| /** | |
| * If `true`, append to the end of the file. | |
| * | |
| * If `false` or omitted, the file will be truncated (overwritten). | |
| * @default false | |
| */ | |
| append?: boolean; | |
| }): FileSink; |
🤖 Prompt for AI Agents
In @packages/bun-types/bun.d.ts around lines 1379 - 1386, The JSDoc for
BunFile.writer's options is ambiguous about append=false; update the comment on
the writer(options?: { append?: boolean }) signature (the writer method that
returns FileSink) to explicitly state that when append is false or omitted the
file is truncated (overwritten) rather than preserved, and keep @default false
to match Bun.write docs and the PR behavior.
| write( | ||
| data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer | Request | Response | BunFile, | ||
| options?: { highWaterMark?: number }, | ||
| data: | ||
| | Blob | ||
| | NodeJS.TypedArray | ||
| | ArrayBufferLike | ||
| | string | ||
| | BlobPart[] | ||
| | ReadableStream | ||
| | Request | ||
| | Response | ||
| | BunFile, | ||
|
|
||
| options?: { | ||
| highWaterMark?: number; | ||
| /** | ||
| * If `true`, append to the end of the file instead of overwriting it. | ||
| * | ||
| * If `false` or omitted, the file will be truncated (overwritten). | ||
| * | ||
| * @default false | ||
| */ | ||
| append?: boolean; | ||
| }, | ||
| ): Promise<number>; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Avoid type drift: factor shared “write input” / “append options” aliases used by Bun.write + BunFile.write.
The input union and the append option block are now duplicated across multiple overloads (Lines 1429-1450 and earlier). This is likely to drift over time (e.g., adding a new accepted type to one but not the others). Consider introducing internal aliases (e.g., type WriteAppendOptions = { highWaterMark?: number; append?: boolean }) and reusing them.
Possible direction (illustrative)
type BlobPart = string | Blob | BufferSource;
+ type WriteAppendOptions = {
+ highWaterMark?: number;
+ /**
+ * If `true`, append to the end of the file instead of overwriting it.
+ *
+ * If `false` or omitted, the file will be truncated (overwritten).
+ *
+ * @default false
+ */
+ append?: boolean;
+ };
interface BunFile extends Blob {
writer(options?: {
highWaterMark?: number;
/**
* If `true`, append to the end of the file.
*
* If `false` or omitted, the file will be truncated (overwritten).
* @default false
*/
append?: boolean;
}): FileSink;
write(
data:
| Blob
| NodeJS.TypedArray
| ArrayBufferLike
| string
| BlobPart[]
| ReadableStream
| Request
| Response
| BunFile,
- options?: {
- highWaterMark?: number;
- /**
- * If `true`, append to the end of the file instead of overwriting it.
- *
- * If `false` or omitted, the file will be truncated (overwritten).
- *
- * @default false
- */
- append?: boolean;
- },
+ options?: WriteAppendOptions,
): Promise<number>;
}🤖 Prompt for AI Agents
In @packages/bun-types/bun.d.ts around lines 1428 - 1451, Introduce shared type
aliases for the duplicated input union and options and use them in both
Bun.write and BunFile.write signatures: create a type alias (e.g., WriteInput =
Blob | NodeJS.TypedArray | ArrayBufferLike | string | BlobPart[] |
ReadableStream | Request | Response | BunFile) and an options alias (e.g.,
WriteAppendOptions = { highWaterMark?: number; append?: boolean }) and replace
the inline union and options object in the write(...) overloads with these
aliases so both Bun.write and BunFile.write reference the single source of
truth.
|
Closing as stale: this PR predates the Rust rewrite. Every If the underlying change is still wanted, it will need to be redone against the current Rust/C++ tree. Apologies for the churn, and thank you for the contribution. |
Closes #10473
Closes #16768
Add support for appending with
.write()without truncating the file by adding anappendoption.Essentially it just replaces the truncate flag with append. The fast write path is skipped when appending and file to file copies use read write fallback instead of optimized syscalls.
append?: booleanoption toBun.write()andBunFile.write()append?: booleanoption toFileSink(Bun.file().writer())ReadableStreamas a source for.write()Bun.writeandBunFile.write