Skip to content

fix(pnpm migration): fix "lockfileVersion" number parsing - #23232

Merged
Jarred-Sumner merged 7 commits into
mainfrom
dylan/fix-pnpm-lockfile-version-number
Oct 4, 2025
Merged

Jarred-Sumner merged 7 commits into
mainfrom
dylan/fix-pnpm-lockfile-version-number

Conversation

@dylan-conway

Copy link
Copy Markdown
Member

What does this PR do?

Parsing would fail because the lockfile version might be parsing as a non-whole float instead of a string (5.4 vs '5.4') and the migration would have the wrong error.

How did you verify your code works?

Added a test

@robobun

robobun commented Oct 4, 2025 •

Copy link
Copy Markdown
Collaborator
Updated 12:39 AM PT - Oct 4th, 2025

❌ @dylan-conway, your commit 55d0f78 has 2 failures in Build #27968 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 23232

That installs a local version of the PR into your bun-23232 executable, so you can run:

bun-23232 --bun

@coderabbitai

coderabbitai Bot commented Oct 4, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

PNPM lockfile version parsing changed from integer to floating-point (f64); validation no longer enforces a u32 upper bound or integer coercion. Migration error branches were simplified to return errors via LoadResult. A test for a dotted numeric lockfile version was added.

Changes

Cohort / File(s) Change Summary
PNPM lockfile parsing
src/install/pnpm.zig
Switched lockfile_version_num from u32 to f64; replaced unsigned-integer parsing with float parsing; removed max-u32 upper-bound check and integer coercion; validation now only checks non-negative and treats < v7 as too old.
Migration error handling
src/install/migration.zig
Removed debug-only error logging/abort branches for lockfile migrations; on migration error now calls log.reset() and returns a LoadResult containing the error instead of terminating.
Migration tests
test/cli/install/migration/pnpm-migration.test.ts
Added test "version is number with dot" using pnpm/version-number-dot fixture; runs bun install, awaits output, and asserts exit code 0 with error output containing "pnpm-lock.yaml version is too old (< v7)".

Possibly related PRs

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title succinctly indicates that this PR fixes the lockfileVersion number parsing in the pnpm migration code by specifying the affected field, matching the main change in the diff.
Description Check ✅ Passed The pull request description follows the repository’s template with both “What does this PR do?” and “How did you verify your code works?” sections filled out, clearly describing the parsing issue and the added test.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch dylan/fix-pnpm-lockfile-version-number

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
test/cli/install/migration/pnpm-migration.test.ts (1)

58-58: Remove unused packageJson variable.

The packageJson variable is destructured but never used in the test.

Apply this diff:

-  const { packageDir, packageJson } = await verdaccio.createTestDir({
+  const { packageDir } = await verdaccio.createTestDir({
     files: join(import.meta.dir, "pnpm/version-number-dot"),
   });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between e3bd036 and f94b288.

⛔ Files ignored due to path filters (1)
  • test/cli/install/migration/pnpm/version-number-dot/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • src/install/pnpm.zig (1 hunks)
  • test/cli/install/migration/pnpm-migration.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
test/**

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

Place all tests under the test/ directory

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/cli/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/**/*.test.ts

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.ts: Name test files *.test.ts and use bun:test
Do not write flaky tests: never wait for arbitrary time; wait for conditions instead
Never hardcode port numbers in tests; use port: 0 to get a random port
When spawning Bun in tests, use bunExe() and bunEnv from harness
Prefer async/await in tests; for a single callback, use Promise.withResolvers()
Do not set explicit test timeouts; rely on Bun’s built-in timeouts
Use tempDir/tempDirWithFiles from harness for temporary files and directories in tests
For large/repetitive strings in tests, prefer Buffer.alloc(count, fill).toString() over "A".repeat(count)
Import common test utilities from harness (e.g., bunExe, bunEnv, tempDirWithFiles, tmpdirSync, platform checks, GC helpers)
In error tests, assert non-zero exit codes for failing processes and use toThrow for synchronous errors
Use describe blocks for grouping, describe.each for parameterized tests, snapshots with toMatchSnapshot, and lifecycle hooks (beforeAll, beforeEach, afterEach); track resources for cleanup in afterEach
Use using/await using with Bun resources (e.g., Bun.listen/connect/spawn/serve) to ensure cleanup in tests

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

test/**/*.test.{ts,tsx}: Test files must be placed under test/ and end with .test.ts or .test.tsx
In tests, always use port: 0; do not hardcode ports or use custom random port functions
In tests, use normalizeBunSnapshot when asserting snapshots
Never write tests that merely assert absence of "panic" or "uncaught exception" in output
Avoid shell commands (e.g., find, grep) in tests; use Bun.Glob and built-ins instead
Prefer snapshot tests over exact stdout equality assertions

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Format JavaScript/TypeScript files with Prettier (bun run prettier)

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/install/pnpm.zig
**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)

**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue

**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup

Files:

  • src/install/pnpm.zig
🧬 Code graph analysis (1)
test/cli/install/migration/pnpm-migration.test.ts (1)
test/harness.ts (1)
  • bunExe (103-106)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Format
🔇 Additional comments (3)
test/cli/install/migration/pnpm-migration.test.ts (1)

57-76: Test structure looks good.

The test correctly verifies the fix for parsing numeric lockfile versions with dots. It properly:

  • Uses the fixture directory pattern
  • Spawns the install process with correct environment
  • Asserts the expected failure with appropriate error message

Note: Address the console.log and unused variable in the comments above.

src/install/pnpm.zig (2)

108-108: LGTM: Type change to f64 enables non-integer versions.

Changing from u32 to f64 correctly allows parsing lockfile versions that contain decimal points (e.g., "5.4").


112-116: LGTM: Simplified validation and return for float versions.

The changes correctly:

  • Remove the unnecessary maxInt(u32) upper bound check
  • Validate only that the version is non-negative
  • Return the float value directly without conversion

This is appropriate for floating-point version numbers.

Comment thread src/install/pnpm.zig
Comment on lines 121 to +122
const end = strings.indexOfChar(str, '.') orelse str.len;
break :lockfile_version std.fmt.parseUnsigned(u32, str[0..end], 10) catch break :err;
break :lockfile_version std.fmt.parseFloat(f64, str[0..end]) catch break :err;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Verify: Parsing only major version, not full decimal version.

The code finds the first dot and parses only up to that point: str[0..end] where end = indexOfChar(str, '.') orelse str.len.

For a version string like "5.4":

  • end would be 1 (index of the first dot)
  • str[0..end] would be "5"
  • Result: only the major version 5.0 is parsed, not 5.4

This contradicts the PR description stating that versions like 5.4 should be handled. If the intent is to parse the full version including the decimal component, the code should parse the entire string, not just up to the first dot.

If this is intentional (only major version matters for the version check at line 132), please clarify. Otherwise, apply this diff:

                .e_string => |version_str| {
                    const str = version_str.slice(allocator);
-
-                    const end = strings.indexOfChar(str, '.') orelse str.len;
-                    break :lockfile_version std.fmt.parseFloat(f64, str[0..end]) catch break :err;
+                    break :lockfile_version std.fmt.parseFloat(f64, str) catch break :err;
                },

Run this script to check if the test fixture uses a version with a decimal component:


🏁 Script executed:

#!/bin/bash
# Check the pnpm-lock.yaml fixture for lockfileVersion value
fd -t f "pnpm-lock.yaml" test/cli/install/migration/pnpm/version-number-dot --exec cat {} \; | head -20

Length of output: 20


Parse full version string for lockfileVersion
The code slices at the first dot and only parses the major version, but the fixture uses lockfileVersion: 5.4, so this yields 5.0 instead of 5.4. Replace lines 121–122 with:

-    const end = strings.indexOfChar(str, '.') orelse str.len;
-    break :lockfile_version std.fmt.parseFloat(f64, str[0..end]) catch break :err;
+    break :lockfile_version std.fmt.parseFloat(f64, str) catch break :err;

This ensures decimal versions like 5.4 are parsed correctly.

📝 Committable suggestion

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

Suggested change
const end = strings.indexOfChar(str, '.') orelse str.len;
break :lockfile_version std.fmt.parseUnsigned(u32, str[0..end], 10) catch break :err;
break :lockfile_version std.fmt.parseFloat(f64, str[0..end]) catch break :err;
break :lockfile_version std.fmt.parseFloat(f64, str) catch break :err;
🤖 Prompt for AI Agents
In src/install/pnpm.zig around lines 121 to 122, the code slices the version
string at the first dot and thus only parses the major version (yielding 5
instead of 5.4); replace the slice+parse with calling std.fmt.parseFloat on the
full str (i.e., remove the 0..end slice and pass str directly) and keep the same
error handling so decimal lockfileVersion values like "5.4" are parsed
correctly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
test/cli/install/migration/pnpm-migration.test.ts (1)

57-60: Remove unused packageJson variable.

The packageJson variable is destructured but never used in this test. Consider removing it to keep the code clean.

Apply this diff:

-  const { packageDir, packageJson } = await verdaccio.createTestDir({
+  const { packageDir } = await verdaccio.createTestDir({
     files: join(import.meta.dir, "pnpm/version-number-dot"),
   });
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f94b288 and 2eb7194.

📒 Files selected for processing (1)
  • test/cli/install/migration/pnpm-migration.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
test/**

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

Place all tests under the test/ directory

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/cli/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

test/cli/**/*.{js,ts}: Place CLI command tests (e.g., bun install, bun init) under test/cli/
When testing Bun as a CLI, use spawn with bunExe() and bunEnv from harness, and capture stdout/stderr via pipes

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/writing-tests.mdc)

test/**/*.{js,ts}: Write tests in JavaScript or TypeScript using Bun’s Jest-style APIs (test, describe, expect) and run with bun test
Prefer data-driven tests (e.g., test.each) to reduce boilerplate
Use shared utilities from test/harness.ts where applicable

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/**/*.test.ts

📄 CodeRabbit inference engine (test/CLAUDE.md)

test/**/*.test.ts: Name test files *.test.ts and use bun:test
Do not write flaky tests: never wait for arbitrary time; wait for conditions instead
Never hardcode port numbers in tests; use port: 0 to get a random port
When spawning Bun in tests, use bunExe() and bunEnv from harness
Prefer async/await in tests; for a single callback, use Promise.withResolvers()
Do not set explicit test timeouts; rely on Bun’s built-in timeouts
Use tempDir/tempDirWithFiles from harness for temporary files and directories in tests
For large/repetitive strings in tests, prefer Buffer.alloc(count, fill).toString() over "A".repeat(count)
Import common test utilities from harness (e.g., bunExe, bunEnv, tempDirWithFiles, tmpdirSync, platform checks, GC helpers)
In error tests, assert non-zero exit codes for failing processes and use toThrow for synchronous errors
Use describe blocks for grouping, describe.each for parameterized tests, snapshots with toMatchSnapshot, and lifecycle hooks (beforeAll, beforeEach, afterEach); track resources for cleanup in afterEach
Use using/await using with Bun resources (e.g., Bun.listen/connect/spawn/serve) to ensure cleanup in tests

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
test/**/*.test.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

test/**/*.test.{ts,tsx}: Test files must be placed under test/ and end with .test.ts or .test.tsx
In tests, always use port: 0; do not hardcode ports or use custom random port functions
In tests, use normalizeBunSnapshot when asserting snapshots
Never write tests that merely assert absence of "panic" or "uncaught exception" in output
Avoid shell commands (e.g., find, grep) in tests; use Bun.Glob and built-ins instead
Prefer snapshot tests over exact stdout equality assertions

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Format JavaScript/TypeScript files with Prettier (bun run prettier)

Files:

  • test/cli/install/migration/pnpm-migration.test.ts
🧬 Code graph analysis (1)
test/cli/install/migration/pnpm-migration.test.ts (1)
test/harness.ts (1)
  • bunExe (103-106)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Format
🔇 Additional comments (2)
test/cli/install/migration/pnpm-migration.test.ts (2)

62-68: LGTM!

The process spawning follows the test patterns correctly, using bunExe() and env from harness with proper stdout/stderr capture.


70-73: LGTM!

The assertions correctly validate that the migration fails with exit code 1 and produces the expected error message for numeric lockfile versions below v7. This directly tests the fix described in the PR.

Claude Bot and others added 4 commits October 4, 2025 05:02
The version check was returning an error but not logging a message,
causing the test to fail. Added proper error logging when the
pnpm-lock.yaml version is less than v7.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/install/migration.zig (1)

124-124: LGTM! Resetting the log before returning error prevents stale state.

The log.reset() call correctly clears accumulated errors after the switch statement has printed relevant diagnostics. This ensures that if the migration fails but the install continues with a fresh install (as indicated by the comment on lines 116-117), stale migration errors won't pollute subsequent operations.

Placement is correct—after all log.print() calls (lines 93, 99, 119) have completed.

Consider adding log.reset() to npm and yarn paths for consistency.

While the npm (line 20) and yarn (line 52) error handlers don't explicitly print from the log like pnpm does, their underlying migration functions may still accumulate log entries. Resetting the log in those paths would ensure consistent cleanup behavior across all three migration flows.

Apply this diff to the npm error handler:

         const migrate_result = migrateNPMLockfile(this, manager, allocator, log, data, lockfile_path) catch |err| {
             if (err == error.NPMLockfileVersionMismatch) {
                 Output.prettyErrorln(
                     \\<red><b>error<r><d>:<r> Please upgrade package-lock.json to lockfileVersion 2 or 3
                     \\
                     \\Run 'npm i --lockfile-version 3 --frozen-lockfile' to upgrade your lockfile without changing dependencies.
                 , .{});
                 Global.exit(1);
             }
+            log.reset();
             return LoadResult{ .err = .{

Apply this diff to the yarn error handler:

         const migrate_result = @import("./yarn.zig").migrateYarnLockfile(this, manager, allocator, log, data, dir) catch |err| {
+            log.reset();
             return LoadResult{ .err = .{
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 061c9f1 and 55d0f78.

📒 Files selected for processing (3)
  • src/install/migration.zig (1 hunks)
  • src/install/pnpm.zig (1 hunks)
  • test/cli/install/migration/pnpm-migration.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/install/pnpm.zig
  • test/cli/install/migration/pnpm-migration.test.ts
🧰 Additional context used
📓 Path-based instructions (2)
src/**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/building-bun.mdc)

Implement debug logs in Zig using const log = bun.Output.scoped(.${SCOPE}, false); and invoking log("...", .{})

Files:

  • src/install/migration.zig
**/*.zig

📄 CodeRabbit inference engine (.cursor/rules/javascriptcore-class.mdc)

**/*.zig: Declare the extern C symbol in Zig and export a Zig-friendly alias for use
Wrap the Bun____toJS extern in a Zig method that takes a JSGlobalObject and returns JSC.JSValue

**/*.zig: Format Zig files with zig-format (bun run zig-format)
In Zig, manage memory carefully with allocators and use defer for cleanup

Files:

  • src/install/migration.zig
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Format

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants