Skip to content

fix(cli): render clean/purge Removing paths relative to cwd on Windows - #13046

Merged
zkochan merged 2 commits into
mainfrom
fix-win-ci
Jul 15, 2026
Merged

zkochan merged 2 commits into
mainfrom
fix-win-ci

Conversation

@zkochan

@zkochan zkochan commented Jul 15, 2026 •

Copy link
Copy Markdown
Member

Summary

The Rust CI / Test / windows job started failing on main (run 29437828132) in the newly added clean / purge command tests (pnpm/crates/cli/tests/clean.rs), which had never run on Windows before.

pnpm clean / pnpm purge built its Removing <path> lines by stripping std::env::current_dir() from targets that are anchored on the symlink-canonicalized --dir (dispatch runs dunce::canonicalize). On Windows those two representations diverge (casing, 8.3 short names, junctions), so the prefix strip found no common base and leaked the full absolute path (C:\Users\...\workspace\node_modules) instead of the relative node_modules.

The fix derives the relative path against the canonicalized working directory, so the base shares the targets' representation. The clean_works_in_a_workspace test now builds its expected Removing pkg/node_modules text with the platform separator instead of a hard-coded /.

This is a pacquet-only fix: the TypeScript CLI already uses path.relative(process.cwd(), p) and does not canonicalize its dir, so it never had this bug.

Follow-up (addressing review feedback)

  • The canonicalized cwd is computed once per clean run and threaded into print_removing, instead of once per removed path.
  • The relative-path computation is now the shared pacquet_fs::relative_path, extracted from symlink_dir's existing root-guarded diff. It carries the Windows same_path_root guard, so a target on a different drive / UNC share renders as the absolute path (matching Node's path.relative) rather than a re-anchored garbage path; symlink_dir delegates to the same helper instead of duplicating it.

Squash Commit Body

fix(cli): render clean/purge Removing paths relative to cwd on Windows

`pnpm clean` / `pnpm purge` built its `Removing <path>` lines by stripping
the raw `current_dir()` from targets that are anchored on the
symlink-canonicalized `--dir`. On Windows those two representations diverge
(casing, 8.3 short names, junctions), so the prefix strip found no common
base and leaked the full absolute path into the output, failing the Windows
`clean` integration tests on main.

Derive the relative path against the canonicalized working directory, so the
base shares the targets' representation. The relative-path computation is the
shared `pacquet_fs::relative_path` helper, extracted from `symlink_dir`'s
root-guarded diff: on a Windows `Prefix` mismatch (different drive / UNC
share) it returns the absolute path, matching Node's `path.relative`, rather
than a re-anchored garbage path. The canonicalized cwd is computed once per
clean run. The workspace test builds its expected `Removing pkg/node_modules`
text with the platform separator instead of a hard-coded `/`.

Checklist

  • The change is implemented in both the TypeScript CLI and the Rust
    pnpm/ port, or the description notes what still needs porting.
  • Added or updated tests.

Written by an agent (Claude Code, claude-opus-4-8).

`pnpm clean` / `pnpm purge` built its `Removing <path>` lines by stripping
the raw `current_dir()` from targets that are anchored on the
symlink-canonicalized `--dir`. On Windows those two representations diverge
(casing, 8.3 short names, junctions), so the prefix strip found no common
base and leaked the full absolute path into the output, failing the Windows
`clean` integration tests on main.

Derive the relative path against the canonicalized working directory via
`pathdiff::diff_paths` (which mirrors Node's `path.relative`, including
walk-ups), so the base shares the targets' representation. The workspace
test now builds its expected `Removing pkg/node_modules` text with the
platform separator instead of a hard-coded `/`.
Copilot AI review requested due to automatic review settings July 15, 2026 18:28

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The filesystem crate adds shared platform-aware relative path computation. The clean command uses it for canonicalized removal output, symlink target generation delegates to it, and workspace cleanup tests construct platform-correct expected paths.

Changes

Relative path handling

Layer / File(s) Summary
Shared relative-path utility
pnpm/crates/fs/src/lib.rs, pnpm/crates/fs/src/relative_path.rs
Adds and publicly re-exports relative_path, including Windows root compatibility checks and absolute-path fallback behavior.
Cleanup and symlink integration
pnpm/crates/cli/src/cli_args/clean.rs, pnpm/crates/cli/tests/clean.rs, pnpm/crates/fs/src/symlink_dir.rs
Cleanup output uses a canonicalized base and platform-aware relative paths; symlink targets use the shared utility, and workspace assertions use platform-correct formatting.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

  • pnpm/pnpm#11684: Reworks relative symlink-target computation in symlink_dir.rs.
  • pnpm/pnpm#11721: Addresses Windows drive-root handling for relative symlink targets.
  • pnpm/pnpm#12999: Changes the related CLI clean path-rendering code and tests.

Suggested labels: product: pacquet

Suggested reviewers: copilot

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-win-ci

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.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Fix clean/purge “Removing …” paths to be cwd-relative on Windows

🐞 Bug fix 🧪 Tests 🕐 10-20 Minutes

Grey Divider

AI Description

• Canonicalize cwd and compute relative removal paths with pathdiff::diff_paths.
• Remove Windows-only case-insensitive prefix stripping that leaked absolute paths.
• Make workspace clean test assert platform-specific path separators.
Diagram

graph TD
  A["pacquet clean/purge"] --> F["cwd (canonicalized)"] --> D["print_removing()"] --> E["stdout: Removing <rel>"]
  A --> B["--dir (canonicalized)"] --> C["targets to remove"] --> D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Canonicalize both sides then `strip_prefix`
  • ➕ Keeps dependency surface minimal (no diff_paths call at print site)
  • ➕ More direct when you only expect descendant paths
  • ➖ Doesn’t match Node’s path.relative behavior (walk-ups, base mismatch cases)
  • ➖ Still needs careful Windows handling for representation differences and edge-cases like empty->'.'
2. Render paths relative to non-canonicalized cwd (current behavior in TS CLI)
  • ➕ Avoids filesystem canonicalization cost and failure modes
  • ➖ Diverges from Rust command dispatch which already canonicalizes --dir
  • ➖ Reintroduces Windows representation mismatch (junctions/8.3/casing) between base and targets

Recommendation: The chosen approach (canonicalize cwd and use pathdiff::diff_paths) is the best fit: it aligns Rust output with pnpm/Node path.relative semantics, handles walk-ups and the empty->'.' case, and eliminates fragile Windows-specific prefix stripping.

Files changed (2) +15 / -30

Bug fix (1) +8 / -28
clean.rsCompute “Removing …” paths via 'diff_paths' against canonicalized cwd +8/-28

Compute “Removing …” paths via 'diff_paths' against canonicalized cwd

• Updates 'print_removing()' to canonicalize 'current_dir()' and compute a relative path using 'pathdiff::diff_paths'. Removes the Windows-only case-insensitive prefix-stripping fallback that could leak absolute paths when cwd and '--dir' representations differ.

pnpm/crates/cli/src/cli_args/clean.rs

Tests (1) +7 / -2
clean.rsMake workspace clean assertions platform-separator aware +7/-2

Make workspace clean assertions platform-separator aware

• Builds expected "Removing pkg*/node_modules" strings using 'Path::join()' and 'display()' instead of hard-coding '/'. This makes the integration test stable across Windows and Unix path separators.

pnpm/crates/cli/tests/clean.rs

@greptile-apps

greptile-apps Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5

The change is a narrowly-scoped Windows path display fix with no impact on package installation or filesystem state; the refactored relative_path helper preserves the exact same logic previously in symlink_dir.rs.

The extraction of relative_path into its own module is a mechanical move with identical logic, verified by diffing the old Windows-specific relative_target_inner + same_path_root in symlink_dir.rs against the new relative_path.rs. The clean.rs change correctly hoists cwd canonicalization out of the per-call print_removing function. Argument order in pathdiff::diff_paths is preserved across the refactor. No data-path, lockfile, or store-layout logic is touched.

No files require special attention.

Reviews (2): Last reviewed commit: "refactor(fs): extract root-guarded relat..." | Re-trigger Greptile

Comment thread pnpm/crates/cli/src/cli_args/clean.rs Resolved
Comment thread pnpm/crates/cli/src/cli_args/clean.rs Resolved

@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 (1)
pnpm/crates/cli/src/cli_args/clean.rs (1)

198-203: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Cache the canonicalized CWD for the clean operation.

print_removing performs current_dir() and dunce::canonicalize for every emitted path. Workspace cleanup can invoke this repeatedly, adding unnecessary filesystem work to the output path hot path. Compute the base once in clean_builtin and pass it into this helper.

🤖 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 `@pnpm/crates/cli/src/cli_args/clean.rs` around lines 198 - 203, Update
clean_builtin to compute the canonicalized current working directory once per
clean operation, then pass that base path into print_removing. Remove the
current_dir and canonicalize calls from print_removing while preserving its
relative-path fallback and “.” handling.

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 `@pnpm/crates/cli/src/cli_args/clean.rs`:
- Around line 198-203: Update clean_builtin to compute the canonicalized current
working directory once per clean operation, then pass that base path into
print_removing. Remove the current_dir and canonicalize calls from
print_removing while preserving its relative-path fallback and “.” handling.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 719461f5-a66d-4190-88fb-f453a3aa87a9

📥 Commits

Reviewing files that changed from the base of the PR and between d768a84 and 5f1d1a6.

📒 Files selected for processing (2)
  • pnpm/crates/cli/src/cli_args/clean.rs
  • pnpm/crates/cli/tests/clean.rs

@github-actions github-actions Bot added the reviewed: coderabbit CodeRabbit submitted an approving review label Jul 15, 2026
@qodo-code-review

qodo-code-review Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

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

Context used
✅ Compliance rules (platform): 18 rules

Grey Divider


Remediation recommended

1. Empty cwd fallback leaks paths 🐞 Bug ⛨ Security ⭐ New
Description
clean_builtin() falls back to an empty PathBuf when current_dir() or dunce::canonicalize()
fails, which makes print_removing() compute a relative path against "" and often print the full
absolute target path again (privacy leak in logs/CI output and inconsistent formatting). This only
triggers on error, but it reintroduces the exact class of "absolute path leakage" the change is
trying to eliminate when cwd resolution fails.
Code

pnpm/crates/cli/src/cli_args/clean.rs[105]

+    let cwd = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
Evidence
The new code uses unwrap_or_default() for the canonicalized cwd, which can produce an empty base
path; the new relative_path helper explicitly falls back to returning the original path when it
cannot compute a diff (including when Windows path roots/prefixes don't match), so an empty base
causes the printed Removing ... path to become absolute again.

pnpm/crates/cli/src/cli_args/clean.rs[97-105]
pnpm/crates/cli/src/cli_args/clean.rs[195-203]
pnpm/crates/fs/src/relative_path.rs[12-24]

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

## Issue description
`clean_builtin()` currently computes `cwd` using `unwrap_or_default()`, which yields an empty path (`""`) on failure. When `print_removing()` calls `relative_path(base, path)` with an empty base, the helper frequently returns the absolute `path`, so `Removing <path>` lines can leak full absolute paths again.

## Issue Context
The goal of this PR is to keep `Removing <path>` output relative to the (canonicalized) cwd. Falling back to an empty base undermines that goal in the error path.

## Fix Focus Areas
- pnpm/crates/cli/src/cli_args/clean.rs[100-105]

### Suggested fix
Prefer a non-empty base fallback:
- If `canonicalize(cwd)` fails, fall back to the non-canonicalized `cwd` (not `""`).
- If `current_dir()` itself fails, use `PathBuf::from(".")` (or another deliberate, non-empty base).

Example:
```rust
let cwd = std::env::current_dir()
 .map(|d| dunce::canonicalize(&d).unwrap_or(d))
 .unwrap_or_else(|_| PathBuf::from("."));
```

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


2. Repeated cwd canonicalize I/O ✓ Resolved 🐞 Bug ➹ Performance
Description
print_removing() canonicalizes current_dir() on every invocation, adding repeated filesystem
work to what should be a cheap formatting path when cleaning many workspace projects. This is
avoidable by computing the canonicalized base once per command run and reusing it across all
Removing ... prints.
Code

pnpm/crates/cli/src/cli_args/clean.rs[R199-200]

+    let base = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
+    let relative = pathdiff::diff_paths(path, &base).unwrap_or_else(|| path.to_path_buf());
Evidence
clean_builtin prints once per project directory and calls print_removing, while print_removing
recomputes the canonicalized cwd each time, which is filesystem work that can be hoisted.

pnpm/crates/cli/src/cli_args/clean.rs[99-146]
pnpm/crates/cli/src/cli_args/clean.rs[189-204]

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

### Issue description
`print_removing()` currently does `current_dir()` + `dunce::canonicalize` every time it prints a removal line. In large workspaces, this repeats filesystem canonicalization work.

### Issue Context
`clean_builtin()` may call `print_removing()` once per workspace project (plus lockfile / virtual store), so repeated canonicalization is avoidable overhead.

### Fix
Compute the canonicalized base once in `clean_builtin()` and pass it into `print_removing(path, base)` (or capture it in a closure), so canonicalization happens once per command.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/clean.rs[99-146]
- pnpm/crates/cli/src/cli_args/clean.rs[189-204]

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


3. Unguarded Windows root mismatch ✓ Resolved 🐞 Bug ☼ Reliability
Description
print_removing() calls pathdiff::diff_paths(path, base) without guarding for Windows
path-root/prefix incompatibility, which this repo has previously found can cause invalid/garbage
relative paths in cross-root cases. When users run pnpm --dir <other drive> clean (cwd and target
on different roots), the output may be misleading; adding a root/prefix check on Windows avoids
invoking diff_paths in cases it can’t safely relate.
Code

pnpm/crates/cli/src/cli_args/clean.rs[R199-200]

+    let base = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
+    let relative = pathdiff::diff_paths(path, &base).unwrap_or_else(|| path.to_path_buf());
Evidence
The repo already documents a Windows CI regression where cross-drive inputs caused
pathdiff::diff_paths to produce a garbage path, and print_removing now calls diff_paths
directly without any such guard.

pnpm/crates/cli/src/cli_args/clean.rs[189-204]
pnpm/crates/fs/src/symlink_dir.rs[92-120]
pnpm/crates/fs/src/symlink_dir/tests.rs[123-134]

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

### Issue description
On Windows, `pathdiff::diff_paths` is not always safe to call when the two paths can’t be related (different drive letters / incompatible prefixes). This repo already has a regression test documenting `diff_paths` producing a re-anchored garbage path in a cross-drive scenario.

### Issue Context
`print_removing()` uses `diff_paths(path, base)` unconditionally. If `base` (canonicalized cwd) and `path` are on different roots/prefixes, avoid calling `diff_paths` and just print the absolute `path` (or otherwise choose a documented fallback).

### Fix
Add a Windows-only root/prefix compatibility check (similar in spirit to `same_path_root` used in `pacquet_fs::symlink_dir`) before calling `diff_paths`. If roots differ, skip `diff_paths` and fall back to `path.to_path_buf()`.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/clean.rs[189-204]
- pnpm/crates/fs/src/symlink_dir.rs[92-120]
- pnpm/crates/fs/src/symlink_dir/tests.rs[123-134]

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


Grey Divider

Previous review results

Review updated until commit 3c81b50

Results up to commit 5f1d1a6


🐞 Bugs (0) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)


Remediation recommended
1. Unguarded Windows root mismatch ✓ Resolved 🐞 Bug ☼ Reliability
Description
print_removing() calls pathdiff::diff_paths(path, base) without guarding for Windows
path-root/prefix incompatibility, which this repo has previously found can cause invalid/garbage
relative paths in cross-root cases. When users run pnpm --dir <other drive> clean (cwd and target
on different roots), the output may be misleading; adding a root/prefix check on Windows avoids
invoking diff_paths in cases it can’t safely relate.
Code

pnpm/crates/cli/src/cli_args/clean.rs[R199-200]

+    let base = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
+    let relative = pathdiff::diff_paths(path, &base).unwrap_or_else(|| path.to_path_buf());
Evidence
The repo already documents a Windows CI regression where cross-drive inputs caused
pathdiff::diff_paths to produce a garbage path, and print_removing now calls diff_paths
directly without any such guard.

pnpm/crates/cli/src/cli_args/clean.rs[189-204]
pnpm/crates/fs/src/symlink_dir.rs[92-120]
pnpm/crates/fs/src/symlink_dir/tests.rs[123-134]

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

### Issue description
On Windows, `pathdiff::diff_paths` is not always safe to call when the two paths can’t be related (different drive letters / incompatible prefixes). This repo already has a regression test documenting `diff_paths` producing a re-anchored garbage path in a cross-drive scenario.

### Issue Context
`print_removing()` uses `diff_paths(path, base)` unconditionally. If `base` (canonicalized cwd) and `path` are on different roots/prefixes, avoid calling `diff_paths` and just print the absolute `path` (or otherwise choose a documented fallback).

### Fix
Add a Windows-only root/prefix compatibility check (similar in spirit to `same_path_root` used in `pacquet_fs::symlink_dir`) before calling `diff_paths`. If roots differ, skip `diff_paths` and fall back to `path.to_path_buf()`.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/clean.rs[189-204]
- pnpm/crates/fs/src/symlink_dir.rs[92-120]
- pnpm/crates/fs/src/symlink_dir/tests.rs[123-134]

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


2. Repeated cwd canonicalize I/O ✓ Resolved 🐞 Bug ➹ Performance
Description
print_removing() canonicalizes current_dir() on every invocation, adding repeated filesystem
work to what should be a cheap formatting path when cleaning many workspace projects. This is
avoidable by computing the canonicalized base once per command run and reusing it across all
Removing ... prints.
Code

pnpm/crates/cli/src/cli_args/clean.rs[R199-200]

+    let base = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
+    let relative = pathdiff::diff_paths(path, &base).unwrap_or_else(|| path.to_path_buf());
Evidence
clean_builtin prints once per project directory and calls print_removing, while print_removing
recomputes the canonicalized cwd each time, which is filesystem work that can be hoisted.

pnpm/crates/cli/src/cli_args/clean.rs[99-146]
pnpm/crates/cli/src/cli_args/clean.rs[189-204]

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

### Issue description
`print_removing()` currently does `current_dir()` + `dunce::canonicalize` every time it prints a removal line. In large workspaces, this repeats filesystem canonicalization work.

### Issue Context
`clean_builtin()` may call `print_removing()` once per workspace project (plus lockfile / virtual store), so repeated canonicalization is avoidable overhead.

### Fix
Compute the canonicalized base once in `clean_builtin()` and pass it into `print_removing(path, base)` (or capture it in a closure), so canonicalization happens once per command.

### Fix Focus Areas
- pnpm/crates/cli/src/cli_args/clean.rs[99-146]
- pnpm/crates/cli/src/cli_args/clean.rs[189-204]

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


Qodo Logo

@github-actions

github-actions Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Micro-Benchmark Results

Linux

group                          main                                   pr
-----                          ----                                   --
lockfile/parse_pnpm_lock       1.00     24.2±0.33ms    15.5 MB/sec    1.00     24.1±0.18ms    15.6 MB/sec
packument/parse                1.00     80.0±2.05µs   829.3 MB/sec    1.00     80.1±0.40µs   827.9 MB/sec
tarball/download_dependency    1.01      6.7±0.28ms   645.0 KB/sec    1.00      6.6±0.07ms   653.5 KB/sec

@qodo-code-review

qodo-code-review Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

PR Code Suggestions ✨

Latest suggestions up to 3c81b50

Warning

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

CategorySuggestion                                                                                                                                    Impact
General
Preserve cwd after canonicalization failure

Fallback to the uncanonicalized current directory instead of an empty path if
canonicalization fails.

pnpm/crates/cli/src/cli_args/clean.rs [105]

-let cwd = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
+let cwd = std::env::current_dir()
+    .map(|cwd| dunce::canonicalize(&cwd).unwrap_or(cwd))
+    .unwrap_or_default();
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: It prevents a rare edge case where canonicalization failure results in an empty base path for relative path computations, improving code robustness.

Medium
  • More

Previous suggestions

✅ Suggestions up to commit 5f1d1a6
CategorySuggestion                                                                                                                                    Impact
General
✅ Cache canonicalized current directory to avoid redundant I/O
Suggestion Impact:The commit canonicalizes the current directory once in clean_builtin and passes it into every print_removing call. This achieves the suggested caching intent, although it uses a local value and function parameter rather than OnceLock.

code diff:

@@ -97,6 +97,12 @@
 /// Remove `node_modules` contents and (optionally) lockfiles from the
 /// current project or every workspace project.
 fn clean_builtin(ctx: &RunCtx<'_>, config: &Config, remove_lockfile: bool) -> miette::Result<()> {
+    // The `Removing <path>` lines render each target relative to the cwd.
+    // It is canonicalized once here so it shares the symlink-resolved
+    // representation of the paths built from the canonicalized `--dir`; on
+    // Windows the raw `current_dir()` can differ (casing, 8.3 short names,
+    // junctions) and defeat the relative-path computation.
+    let cwd = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
     // `pnpm clean` resolves the modules dir relative to each project
     // directory, not against a single absolute prefix, so strip the
     // config anchor back to the leaf and rejoin per project.
@@ -111,14 +117,14 @@
     for dir in &dirs {
         let full_modules_dir = dir.join(modules_leaf);
         if has_contents_to_remove(&full_modules_dir) {
-            print_removing(&full_modules_dir);
+            print_removing(&cwd, &full_modules_dir);
             remove_modules_dir_contents(&full_modules_dir)?;
         }
     }
     if remove_lockfile {
         let lockfile_path = root_dir.join("pnpm-lock.yaml");
         if lockfile_path.exists() {
-            print_removing(&lockfile_path);
+            print_removing(&cwd, &lockfile_path);
             std::fs::remove_file(&lockfile_path)
                 .or_else(|error| {
                     if error.kind() == std::io::ErrorKind::NotFound { Ok(()) } else { Err(error) }
@@ -140,7 +146,7 @@
         && is_subdir(root_dir, &resolved_virtual_store_dir)
         && resolved_virtual_store_dir.exists()
     {
-        print_removing(&resolved_virtual_store_dir);
+        print_removing(&cwd, &resolved_virtual_store_dir);
         remove_path(&resolved_virtual_store_dir)?;
     }
     Ok(())
@@ -186,18 +192,11 @@
     !name.starts_with('.') || PNPM_HIDDEN_ENTRIES.contains(&name)
 }
 
-/// Print `Removing <path>` relative to the current working directory,
-/// matching pnpm's `path.relative(process.cwd(), p)` formatting. An
-/// empty relative path renders as `.`.
-///
-/// The cwd is canonicalized so it shares the symlink-resolved
-/// representation of the paths built from the canonicalized `--dir`.
-/// On Windows the raw `current_dir()` can differ from that form (casing,
-/// 8.3 short names, junctions), which would otherwise leave the two paths
-/// without a common prefix and leak the full absolute path.
-fn print_removing(path: &Path) {
-    let base = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
-    let relative = pathdiff::diff_paths(path, &base).unwrap_or_else(|| path.to_path_buf());
+/// Print `Removing <path>`, with `path` rendered relative to `base` (the
+/// canonicalized cwd), matching pnpm's `path.relative(process.cwd(), p)`
+/// formatting. An empty relative path renders as `.`.
+fn print_removing(base: &Path, path: &Path) {
+    let relative = relative_path(base, path);

Cache the canonicalized current directory using std::sync::OnceLock to avoid
redundant syscalls.

pnpm/crates/cli/src/cli_args/clean.rs [198-204]

 fn print_removing(path: &Path) {
-    let base = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
-    let relative = pathdiff::diff_paths(path, &base).unwrap_or_else(|| path.to_path_buf());
+    static BASE: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
+    let base = BASE.get_or_init(|| {
+        std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default()
+    });
+    let relative = pathdiff::diff_paths(path, base).unwrap_or_else(|| path.to_path_buf());
     let owned: PathBuf =
         if relative.as_os_str().is_empty() { PathBuf::from(".") } else { relative };
     println!("Removing {}", owned.display());
 }
Suggestion importance[1-10]: 4

__

Why: While caching the canonicalized current directory prevents redundant syscalls, the overall performance gain is marginal given that print_removing is called infrequently relative to the much slower directory deletion operations.

Low

@codecov-commenter

codecov-commenter commented Jul 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.53%. Comparing base (d768a84) to head (3c81b50).
⚠️ Report is 3 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #13046   +/-   ##
=======================================
  Coverage   85.53%   85.53%           
=======================================
  Files         497      498    +1     
  Lines       79544    79541    -3     
=======================================
- Hits        68038    68037    -1     
+ Misses      11506    11504    -2     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…clean

Address PR review feedback on the clean/purge Windows path fix:

- Hoist the `current_dir()` + `dunce::canonicalize` out of `print_removing`
  into `clean_builtin`, so the cwd is canonicalized once per command instead
  of once per removed path.
- Replace the bare `pathdiff::diff_paths` call with a shared
  `pacquet_fs::relative_path`, extracted from `symlink_dir`'s
  `relative_target_inner`. It carries the Windows `same_path_root` guard,
  so a target on a different drive/UNC share renders as the absolute path
  (matching Node's `path.relative`) instead of a re-anchored garbage path.
  `symlink_dir` now delegates to the same helper rather than duplicating it.
- Move the canonicalization rationale from the `print_removing` rustdoc into
  an implementation `//` comment at the cwd computation.
Copilot AI review requested due to automatic review settings July 15, 2026 18:48

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@zkochan

zkochan commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

Thanks for the reviews. Follow-up commit 3c81b50 addresses the automated feedback:

  • Repeated cwd canonicalization (Qodo option to for .store location #1, CodeRabbit, Greptile): the current_dir() + dunce::canonicalize is now computed once in clean_builtin and threaded into print_removing(base, path), instead of once per removed path.
  • Unguarded Windows cross-drive diff_paths (Qodo Add one more layer in .store for prod vs dev (vs others?) #2): rather than duplicate the same_path_root guard, I extracted symlink_dir's existing root-guarded diff into a shared pacquet_fs::relative_path(base, path) and reused it in both places. On a Prefix mismatch (a different drive or UNC share) it now returns the absolute path, matching Node's path.relative, instead of a re-anchored garbage path.
  • Doc-comment rationale (Greptile): the Windows canonicalization rationale moved from the print_removing rustdoc into an implementation // comment.

Written by an agent (Claude Code, claude-opus-4-8).

@qodo-code-review

Copy link
Copy Markdown

Code review by qodo was updated up to the latest commit 3c81b50

@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 (1)
pnpm/crates/cli/src/cli_args/clean.rs (1)

100-105: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider preserving the uncanonicalized directory on failure.

Currently, if dunce::canonicalize fails (for example, due to missing read permissions on an ancestor directory), it drops the valid current_dir and falls back to an empty path, which disables relative path formatting entirely. Falling back to the uncanonicalized current directory is slightly more resilient.

♻️ Proposed refactor
     // Windows the raw `current_dir()` can differ (casing, 8.3 short names,
     // junctions) and defeat the relative-path computation.
-    let cwd = std::env::current_dir().and_then(dunce::canonicalize).unwrap_or_default();
+    let cwd = std::env::current_dir()
+        .map(|d| dunce::canonicalize(&d).unwrap_or(d))
+        .unwrap_or_default();
     // `pnpm clean` resolves the modules dir relative to each project
🤖 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 `@pnpm/crates/cli/src/cli_args/clean.rs` around lines 100 - 105, Update the cwd
initialization near the `dunce::canonicalize` call to preserve the successfully
retrieved uncanonicalized `current_dir` when canonicalization fails, instead of
falling back directly to an empty path. Keep the empty-path fallback only for
failure to obtain the current directory.
🤖 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 `@pnpm/crates/cli/src/cli_args/clean.rs`:
- Around line 100-105: Update the cwd initialization near the
`dunce::canonicalize` call to preserve the successfully retrieved
uncanonicalized `current_dir` when canonicalization fails, instead of falling
back directly to an empty path. Keep the empty-path fallback only for failure to
obtain the current directory.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 029ce116-dd6a-4eb9-afe3-554067db1888

📥 Commits

Reviewing files that changed from the base of the PR and between 5f1d1a6 and 3c81b50.

📒 Files selected for processing (4)
  • pnpm/crates/cli/src/cli_args/clean.rs
  • pnpm/crates/fs/src/lib.rs
  • pnpm/crates/fs/src/relative_path.rs
  • pnpm/crates/fs/src/symlink_dir.rs

@zkochan
zkochan merged commit b49c224 into main Jul 15, 2026
35 checks passed
@zkochan
zkochan deleted the fix-win-ci branch July 15, 2026 18:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

product: pacquet reviewed: coderabbit CodeRabbit submitted an approving review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants