Skip to content

fix(link-bins): reapply executable bit to restored bins - #13630

Merged
zkochan merged 2 commits into
pnpm:mainfrom
david-wasser:david-wasser/pnpm-exec-linking-fix
Aug 7, 2026
Merged

zkochan merged 2 commits into
pnpm:mainfrom
david-wasser:david-wasser/pnpm-exec-linking-fix

Conversation

@david-wasser

@david-wasser david-wasser commented Aug 4, 2026 •

Copy link
Copy Markdown

Summary

When a pnpm install fails we may re-copy a bin script from the store when pnpm install is rerun. After #11069 though, we don't reapply the executable bit to the bin script that we did on the first install attempt. This change fixes that by reapplying the executable bit when necessary. This should fix #12742.

Squash Commit Body

When a `pnpm install` fails we may re-copy a bin script from the store when `pnpm install` is rerun.
After pnpm/pnpm#11069 though, we don't reapply the executable bit to the bin script that we did on
the first install attempt. This change fixes that by reapplying the executable bit when necessary.
This should fix pnpm/pnpm#12742.

Checklist

  • I checked the referenced issue and verified that none of the PRs
    already linked to it solves it.
  • Added a changeset (pnpm changeset) if this PR changes any published
    package. Keep it short and written for pnpm users — it becomes a release note.
  • Added or updated tests.

View with [code]smith Autofix with [code]smith
Need help on this PR? Tag @codesmith-bot with what you need. Autofix is disabled.

Summary by CodeRabbit

  • Bug Fixes
    • Fixed an issue where executable permissions could be lost when an existing link or shim already pointed to a binary.
    • Improved handling of binaries with Windows-style shebangs to ensure they remain executable.

@david-wasser
david-wasser requested a review from zkochan as a code owner August 4, 2026 06:01
@welcome

welcome Bot commented Aug 4, 2026

Copy link
Copy Markdown

💖 Thanks for opening this pull request! 💖
Please be patient and we will get back to you as soon as we can.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@zkochan, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 1 minute

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 45c533d0-7d2b-48c5-8f5c-9261f1265428

📥 Commits

Reviewing files that changed from the base of the PR and between 96eb87f and bc4ca23.

📒 Files selected for processing (3)
  • .changeset/reapply-executable-bit-to-restored-bins.md
  • pnpm11/bins/linker/src/index.ts
  • pnpm11/bins/linker/test/index.ts
📝 Walkthrough

Walkthrough

The linker now tracks matching existing symlinks and shims, then restores executable permissions or normalizes Windows shebangs when needed. A POSIX regression test verifies permission restoration during relinking.

Changes

Bin relinking

Layer / File(s) Summary
Conditional executable normalization
pnpm11/bins/linker/src/index.ts
Matching targets now trigger ensureExecutableIfNeeded, which normalizes non-executable files and Windows-style shebangs.
POSIX permission regression coverage
pnpm11/bins/linker/test/index.ts
A POSIX-only test removes execute permissions, relinks the bin, and verifies mode 755.

Estimated code review effort: 2 (Simple) | ~10 minutes

Suggested labels: product: pnpm@11

Suggested reviewers: zkochan

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

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

@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Reviews (3): Last reviewed commit: "fix(link-bins): skip the executable-bit ..." | Re-trigger Greptile

@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.

🧹 Nitpick comments (2)
pnpm11/bins/linker/test/index.ts (1)

102-113: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use asynchronous filesystem APIs in this async test.

fs.chmodSync and fs.statSync block the Jest worker. Use the repository's asynchronous filesystem helpers and await both operations.

Example
-  fs.chmodSync(binSource, 0o644)
+  await fs.promises.chmod(binSource, 0o644)

-  expect(fs.statSync(binSource).mode & 0o777).toBe(0o755)
+  expect((await fs.promises.stat(binSource)).mode & 0o777).toBe(0o755)

As per coding guidelines, prefer asynchronous filesystem APIs and async/await.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm11/bins/linker/test/index.ts` around lines 102 - 113, Update the test
around linkBins() repairs a non-executable source to replace fs.chmodSync and
fs.statSync with the repository’s asynchronous filesystem helpers, awaiting both
operations while preserving the existing permissions assertion.

Source: Coding guidelines

pnpm11/bins/linker/src/index.ts (1)

278-284: 🚀 Performance & Scalability | 🔵 Trivial

Measure the added warm-install filesystem work.

Every matching bin now calls ensureExecutableIfNeeded. That helper performs fs.stat and, for executable files, opens and reads up to 2 KiB to check hasWindowsShebang. Aliases that share cmd.path repeat the same work.

Cache the result per source path within one linkBins run, or measure and document why this extra hot-path I/O is acceptable.

As per path instructions, avoid unnecessary filesystem work on the linking hot path.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@pnpm11/bins/linker/src/index.ts` around lines 278 - 284, Update the linkBins
flow around ensureExecutableIfNeeded to cache the executable/shebang-check
result by cmd.path for the duration of a single run, so aliases sharing a source
path do not repeat stat/read I/O. Reuse the cached result for subsequent
matching bins while preserving the existing executable-bit behavior.

Source: Path instructions

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@pnpm11/bins/linker/src/index.ts`:
- Around line 278-284: Update the linkBins flow around ensureExecutableIfNeeded
to cache the executable/shebang-check result by cmd.path for the duration of a
single run, so aliases sharing a source path do not repeat stat/read I/O. Reuse
the cached result for subsequent matching bins while preserving the existing
executable-bit behavior.

In `@pnpm11/bins/linker/test/index.ts`:
- Around line 102-113: Update the test around linkBins() repairs a
non-executable source to replace fs.chmodSync and fs.statSync with the
repository’s asynchronous filesystem helpers, awaiting both operations while
preserving the existing permissions assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c4b5d95e-2cbb-4561-92db-94eb476e89c3

📥 Commits

Reviewing files that changed from the base of the PR and between 46d7d3e and 3a8d892.

📒 Files selected for processing (2)
  • pnpm11/bins/linker/src/index.ts
  • pnpm11/bins/linker/test/index.ts

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Aug 4, 2026
When a `pnpm install` fails, on a rerun we may re-copy a bin script from the
store. After pnpm#11069 though, we wouldn't reapply the executable bit to
the bin script that we did on the first install attempt. This change fixes that
by reapplying the executable bit when necessary. This should fix pnpm#12742
@zkochan
zkochan force-pushed the david-wasser/pnpm-exec-linking-fix branch from 3a8d892 to fe8988f Compare August 7, 2026 13:39
… missing

A correctly linked shim whose source file has vanished must not fail the
install: the skip path previously returned without touching the source,
and pacquet swallows NotFound in the same spot. Also add the missing
changeset for pnpm#12742.

Co-Authored-By: Claude Fable 5 <[email protected]>
@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (2) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. ensureExecutableIfNeeded comment historical 📘 Rule violation ⚙ Maintainability
Description
New comments document behavior using historical/temporal phrasing (e.g., "before this repair step"
and "If a previous install failed") instead of stating the current invariant/contract. This violates
the comments policy because such narration can become outdated and is disallowed in source comments.
Code

pnpm11/bins/linker/src/index.ts[R463-466]

+// A missing or unreadable source is skipped rather than failing the install:
+// the existing bin was accepted as correctly linked, and before this repair
+// step the skip path returned without touching the source at all.
+async function ensureExecutableIfNeeded (file: string, mode: number): Promise<void> {
Relevance

●●● Strong

Team has accepted rewriting comments to avoid historical phrasing and state current invariants.

PR-#13383

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The cited additions include phrasing like "before this repair step" and "If a previous install
failed," which describe behavior in terms of prior states or past scenarios rather than expressing
the present-tense intent, rationale, or contract of the code; the rule explicitly flags this kind of
temporal/historical narration as noncompliant and requires comments to be written as current, stable
documentation of behavior.

Rule 772199: Comments must describe current behavior, not historical implementations
pnpm11/bins/linker/src/index.ts[463-470]
pnpm11/bins/linker/src/index.ts[279-283]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Comments near `ensureExecutableIfNeeded` and the related logic use historical/temporal phrasing (e.g., describing what happened "before this repair step" or referencing a "previous install" failure) rather than documenting the current behavior, invariant, or contract.

## Issue Context
Per the comments policy, source comments should describe current behavior/intent and rationale in a stable, present-tense way, avoiding narration about past implementations or prior failure scenarios that can quickly become outdated.

## Fix Focus Areas
- pnpm11/bins/linker/src/index.ts[279-282]
- pnpm11/bins/linker/src/index.ts[463-466]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Warm-path I/O regression 🐞 Bug ➹ Performance
Description
linkBin()’s “already correctly linked” fast-path now calls ensureExecutableIfNeeded(cmd.path)
which adds extra filesystem work (stat + often open/read) per bin even on warm installs. This scales
with bin count and conflicts with pnpm’s performance guidance to avoid adding thousands of
filesystem ops in install/linking hot paths.
Code

pnpm11/bins/linker/src/index.ts[R282-285]

+    if (EXECUTABLE_SHEBANG_SUPPORTED) {
+      await ensureExecutableIfNeeded(cmd.path, 0o755)
+    }
+    return
Relevance

●● Moderate

Perf hot-path I/O concerns are plausible, but similar perf-optimization requests were previously
rejected; uncertain here.

PR-#12777

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
_linkBins() invokes linkBin() for every discovered command, so any additional per-bin filesystem
work is multiplied by the total bin count. The PR adds ensureExecutableIfNeeded(cmd.path) to the
previously-fast early return path, and ensureExecutableIfNeeded() performs fs.stat() and for
already-executable files calls hasWindowsShebang() which opens and reads 2048 bytes. This
contradicts the nearby comment claiming the fast-path “avoids redundant I/O on warm installs” and
triggers the repo’s performance rule about avoiding thousands of FS ops in install/linking hot
paths.

pnpm11/bins/linker/src/index.ts[133-155]
pnpm11/bins/linker/src/index.ts[261-286]
pnpm11/bins/linker/src/index.ts[463-489]
REVIEW_GUIDE.md[115-127]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`linkBin()` now performs additional source-file validation/repair work in the warm-path where the external bin is already correctly linked. The new `ensureExecutableIfNeeded()` does a `stat()` and (for already-executable files) calls `hasWindowsShebang()` which `open()`s and reads the file. On large installs with many bins, this adds significant extra filesystem I/O.

### Issue Context
This work is triggered in the `isCorrectlyLinked` early-return block, which is specifically documented as a warm-install optimization to avoid redundant I/O.

### Fix Focus Areas
- pnpm11/bins/linker/src/index.ts[261-286]
- pnpm11/bins/linker/src/index.ts[463-489]

### Implementation direction (one viable approach)
- Narrow the warm-path repair to the minimal condition needed for this PR’s regression: only call `ensureExecutable(...)` when the execute bit is actually missing (based on `stat.mode & 0o111`).
- Avoid calling `hasWindowsShebang()` in the warm path for already-executable files (it forces an open+read on every bin). Rely on the existing non-warm paths (initial link / relink) to normalize CRLF shebangs, and let `ensureExecutable()` handle CRLF when it is invoked due to missing exec bits.
- If CRLF normalization must be preserved on rerun even when exec bits are already set, consider adding a cheap marker/caching strategy to avoid repeating `hasWindowsShebang()` reads per bin on warm installs.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

3. Pacquet bin repair not synced 📘 Rule violation ⌂ Architecture
Description
This PR changes pnpm TypeScript bin-linking behavior to repair the source script (including
CRLF-shebang cases) even when the existing bin is already correctly linked, but there is no
corresponding pacquet update or PR-description callout. This can leave pnpm and pacquet with
divergent on-disk behavior for repaired bins.
Code

pnpm11/bins/linker/src/index.ts[R282-285]

+    if (EXECUTABLE_SHEBANG_SUPPORTED) {
+      await ensureExecutableIfNeeded(cmd.path, 0o755)
+    }
+    return
Relevance

● Weak

Parity/sync-with-pacquet requests have a close rejected precedent; divergence accepted before.

PR-#13536

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The TypeScript linker now calls ensureExecutableIfNeeded(cmd.path, 0o755) on the warm-path early
return when a bin is already correctly linked, making a user-visible permissions/shebang repair in
pnpm. In pacquet's bin-linking, the analogous path ensures executable bits on the target but
explicitly does so "without rewriting CRLF shebangs", indicating the new pnpm behavior is not
matched (and the PR description does not document a known divergence).

Rule 713428: Keep pnpm TypeScript and pacquet Rust user-visible behavior changes in sync
pnpm11/bins/linker/src/index.ts[278-285]
pnpm/crates/cmd-shim/src/link_bins.rs[556-592]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
pnpm TypeScript now repairs the bin source (chmod + CRLF shebang fix) even when the existing bin is already correctly linked, but pacquet Rust does not appear to implement the same repair semantics (or the PR description does not call out the divergence).

## Issue Context
Compliance requires pnpm TypeScript and pacquet Rust user-visible behavior changes to stay in sync, or be explicitly called out in the PR description.

## Fix Focus Areas
- pnpm11/bins/linker/src/index.ts[278-286]
- pnpm/crates/cmd-shim/src/link_bins.rs[556-592]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context used
✅ Compliance rules (platform): 18 rules

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

@qodo-code-review

Copy link
Copy Markdown

PR Code Suggestions ✨

Warning

/improve is deprecated. Use /agentic_review instead (removal date not yet scheduled).

No code suggestions found for the PR.

@zkochan
zkochan merged commit d01029b into pnpm:main Aug 7, 2026
27 checks passed
@welcome

welcome Bot commented Aug 7, 2026

Copy link
Copy Markdown

Congrats on merging your first pull request! 🎉🎉🎉

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

Labels

product: pnpm@11 reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Installed bin script loses its execute bit after retrying failed pnpm install

2 participants