Skip to content

Commit 3600b05

Browse files
authored
fix: remove a dependency whose manifest is malformed (#17828)
`removeBinsOfDependency` read the removed dependency's manifest with `safeReadPackageJsonFromDir`, which throws on a malformed `package.json`. The isolated linker's prune, the hoisted stale-link pass with a real `.bin`, and the hoisted orphan cleanup all go through it, so a malformed manifest failed the install before the dependency was removed. v12 skips the bins and removes the dependency. A new `safeReadDependencyManifest` returns `undefined` for a missing or malformed manifest, or one under a path that is not a directory, and rethrows other errors, as v12 does. `removeBinsOfDependency` and the hoisted stale-link pass both use it. Both stacks' tests now cover the removal under each linker, with and without a real `.bin`. Closes pnpm/tasks#295
1 parent cd94a25 commit 3600b05

9 files changed

Lines changed: 94 additions & 39 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@pnpm/bins.remover": patch
3+
"@pnpm/installing.deps-restorer": patch
4+
"pnpm": patch
5+
---
6+
7+
pnpm no longer fails to remove a dependency whose `package.json` is malformed. It removes the dependency and keeps its bins [pnpm/tasks#295](https://github.com/pnpm/tasks/issues/295).

‎pnpm-lock.yaml‎

Lines changed: 3 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm/crates/cli/tests/suite/stale_link_prune.rs‎

Lines changed: 49 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -122,32 +122,66 @@ fn a_removed_link_dependency_is_reported() {
122122
}
123123
}
124124

125-
#[test]
126-
fn a_removed_link_dependency_with_a_malformed_manifest_is_unlinked() {
125+
/// Whether the removed dependency declares a bin. With one, the link
126+
/// leaves a real `.bin`, so the removal reads the manifest to remove its
127+
/// bins.
128+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129+
enum LinkedBins {
130+
None,
131+
One,
132+
}
133+
134+
/// What [`remove_a_link_dependency_with_a_malformed_manifest`] saw.
135+
#[derive(Debug)]
136+
struct MalformedManifestRemoval {
137+
has_bins_dir: bool,
138+
present_after: bool,
139+
/// The `(alias, version)` of each [`removals`] entry.
140+
removed: Vec<(String, Value)>,
141+
}
142+
143+
fn remove_a_link_dependency_with_a_malformed_manifest(bins: LinkedBins) {
127144
let observed = under_each_linker(|pacquet, workspace| {
128-
write_json(
129-
&workspace.join("lib/package.json"),
130-
&json!({ "name": "lib", "version": "1.0.0" }),
131-
);
145+
let mut manifest = json!({ "name": "lib", "version": "1.0.0" });
146+
if bins == LinkedBins::One {
147+
manifest["bin"] = json!("cli.js");
148+
}
149+
write_json(&workspace.join("lib/package.json"), &manifest);
150+
fs::write(workspace.join("lib/cli.js"), "#!/usr/bin/env node\n").expect("write the bin");
132151
write_root_manifest(workspace, &json!({ "lib": "link:lib" }));
133152
install(pacquet);
153+
let has_bins_dir = workspace.join("node_modules/.bin").is_dir();
134154
fs::write(workspace.join("lib/package.json"), "{").expect("break the manifest");
135155

136156
write_root_manifest(workspace, &json!({}));
137157
let records = install(pacquet_in(workspace));
138-
let removed: Vec<_> = removals(&records)
139-
.into_iter()
140-
.map(|(_, alias, version)| (alias, version))
141-
.collect();
142-
(fs::symlink_metadata(workspace.join("node_modules/lib")).is_ok(), removed)
158+
MalformedManifestRemoval {
159+
has_bins_dir,
160+
present_after: fs::symlink_metadata(workspace.join("node_modules/lib")).is_ok(),
161+
removed: removals(&records)
162+
.into_iter()
163+
.map(|(_, alias, version)| (alias, version))
164+
.collect(),
165+
}
143166
});
144-
dbg!(&observed);
145-
for (linker, (present_after, removed)) in observed {
146-
assert!(!present_after, "nodeLinker: {linker}");
147-
assert_eq!(removed, [("lib".to_owned(), Value::Null)], "nodeLinker: {linker}");
167+
dbg!(bins, &observed);
168+
for (linker, removal) in observed {
169+
assert_eq!(removal.has_bins_dir, bins == LinkedBins::One, "nodeLinker: {linker}");
170+
assert!(!removal.present_after, "nodeLinker: {linker}");
171+
assert_eq!(removal.removed, [("lib".to_owned(), Value::Null)], "nodeLinker: {linker}");
148172
}
149173
}
150174

175+
#[test]
176+
fn a_removed_link_dependency_with_a_malformed_manifest_is_unlinked() {
177+
remove_a_link_dependency_with_a_malformed_manifest(LinkedBins::None);
178+
}
179+
180+
#[test]
181+
fn a_removed_link_dependency_with_bins_and_a_malformed_manifest_is_unlinked() {
182+
remove_a_link_dependency_with_a_malformed_manifest(LinkedBins::One);
183+
}
184+
151185
/// The root names `packages/shared` as `link:packages/shared`, the project
152186
/// as `link:../shared`: one target, so the root's link dedupes the
153187
/// project's.

‎pnpm11/bins/remover/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
"dependencies": {
3434
"@pnpm/bins.resolver": "workspace:*",
3535
"@pnpm/core-loggers": "workspace:*",
36+
"@pnpm/error": "workspace:*",
3637
"@pnpm/pkg-manifest.reader": "workspace:*",
3738
"@pnpm/types": "workspace:*",
3839
"@zkochan/rimraf": "catalog:",

‎pnpm11/bins/remover/src/index.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
import { removeBin, removeBinsOfDependency } from './removeBins.js'
1+
import { removeBin, removeBinsOfDependency, safeReadDependencyManifest } from './removeBins.js'
22

33
export {
44
removeBin,
55
removeBinsOfDependency,
6+
safeReadDependencyManifest,
67
}

‎pnpm11/bins/remover/src/removeBins.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { getBinsFromPackageManifest } from '@pnpm/bins.resolver'
44
import {
55
removalLogger,
66
} from '@pnpm/core-loggers'
7+
import { isError } from '@pnpm/error'
78
import { safeReadPackageJsonFromDir } from '@pnpm/pkg-manifest.reader'
89
import type { DependencyManifest } from '@pnpm/types'
910
import { rimraf } from '@zkochan/rimraf'
@@ -42,8 +43,7 @@ export async function removeBinsOfDependency (
4243
binsDir: string
4344
}
4445
): Promise<DependencyManifest | undefined> {
45-
const uninstalledPkgJson = await safeReadPackageJsonFromDir(dependencyDir) as DependencyManifest
46-
46+
const uninstalledPkgJson = await safeReadDependencyManifest(dependencyDir)
4747
if (!uninstalledPkgJson) return
4848
const cmds = await getBinsFromPackageManifest(uninstalledPkgJson, dependencyDir)
4949

@@ -57,3 +57,19 @@ export async function removeBinsOfDependency (
5757

5858
return uninstalledPkgJson
5959
}
60+
61+
/**
62+
* Returns `undefined` when the manifest is missing or malformed, or its path
63+
* runs through a file, so that its bins are left in place instead of blocking
64+
* the dependency's removal. Rethrows every other read error.
65+
*/
66+
export async function safeReadDependencyManifest (dependencyDir: string): Promise<DependencyManifest | undefined> {
67+
try {
68+
return (await safeReadPackageJsonFromDir(dependencyDir) as DependencyManifest | null) ?? undefined
69+
} catch (err: unknown) {
70+
if (isError(err) && 'code' in err && (err.code === 'ERR_PNPM_BAD_PACKAGE_JSON' || err.code === 'ENOTDIR')) {
71+
return undefined
72+
}
73+
throw err
74+
}
75+
}

‎pnpm11/bins/remover/tsconfig.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@
1212
{
1313
"path": "../../core/core-loggers"
1414
},
15+
{
16+
"path": "../../core/error"
17+
},
1518
{
1619
"path": "../../core/logger"
1720
},

‎pnpm11/installing/deps-installer/test/install/staleLinkPrune.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -65,15 +65,19 @@ test.each(LINKERS)('a removed link: dependency is reported (nodeLinker: %s)', as
6565
expect(removals(reporter)).toStrictEqual([':[email protected]'])
6666
})
6767

68-
// The isolated linker and a real `.bin` read the manifest to remove its bins, so
69-
// a malformed one fails the install there.
70-
test('a removed link: dependency with a malformed manifest is unlinked (nodeLinker: hoisted)', async () => {
71-
const nodeLinker = 'hoisted'
68+
// With a bin, the link leaves a real `.bin`, so the removal reads the manifest
69+
// to remove its bins.
70+
test.each(LINKERS.flatMap((nodeLinker) => [
71+
{ nodeLinker, withBin: false },
72+
{ nodeLinker, withBin: true },
73+
]))('a removed link: dependency with a malformed manifest is unlinked (nodeLinker: $nodeLinker, withBin: $withBin)', async ({ nodeLinker, withBin }) => {
7274
const { allProjects, importers } = prepareWorkspace({
7375
'': { name: 'root', dependencies: { lib: 'link:lib' } },
7476
})
75-
writeManifest('lib', { name: 'lib', version: '1.0.0' })
77+
writeManifest('lib', { name: 'lib', version: '1.0.0', ...(withBin ? { bin: 'cli.js' } : {}) })
78+
fs.writeFileSync('lib/cli.js', '#!/usr/bin/env node\n')
7679
await mutateModules(importers, testDefaults({ allProjects, nodeLinker }))
80+
expect(fs.existsSync('node_modules/.bin')).toBe(withBin)
7781
fs.writeFileSync('lib/package.json', '{')
7882

7983
allProjects[0].manifest.dependencies = {}

‎pnpm11/installing/deps-restorer/src/unlinkStaleDirectLinks.ts‎

Lines changed: 2 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
import { promises as fs } from 'node:fs'
22
import path from 'node:path'
33

4-
import { removeBinsOfDependency } from '@pnpm/bins.remover'
4+
import { removeBinsOfDependency, safeReadDependencyManifest } from '@pnpm/bins.remover'
55
import { rootLogger } from '@pnpm/core-loggers'
6-
import { isError } from '@pnpm/error'
76
import { safeJoinModulesDir } from '@pnpm/fs.symlink-dependency'
87
import { isProvidedByRoot } from '@pnpm/installing.linking.modules-cleaner'
98
import type { LockfileObject, ProjectSnapshot } from '@pnpm/lockfile.fs'
10-
import { safeReadPackageJsonFromDir } from '@pnpm/pkg-manifest.reader'
119
import { DEPENDENCIES_FIELDS, type ProjectId } from '@pnpm/types'
1210

1311
import type { HeadlessContext } from './context.js'
@@ -93,23 +91,11 @@ async function unlinkDirectLink (modulesDir: string, alias: string, binsDir: str
9391
// Unlinking through a symlinked `.bin` would delete files outside the project.
9492
const version = await isRealDir(binsDir)
9593
? (await removeBinsOfDependency(link, { binsDir }))?.version
96-
: await readManifestVersion(link)
94+
: (await safeReadDependencyManifest(link))?.version
9795
await unlinkIfSymlink(link)
9896
return { version }
9997
}
10098

101-
/** A malformed or missing manifest leaves the version out rather than blocking the unlink. */
102-
async function readManifestVersion (pkgDir: string): Promise<string | undefined> {
103-
try {
104-
return (await safeReadPackageJsonFromDir(pkgDir))?.version
105-
} catch (err: unknown) {
106-
if (isError(err) && 'code' in err && (err.code === 'ERR_PNPM_BAD_PACKAGE_JSON' || err.code === 'ENOTDIR')) {
107-
return undefined
108-
}
109-
throw err
110-
}
111-
}
112-
11399
async function isRealDir (dir: string): Promise<boolean> {
114100
const stats = await fs.lstat(dir).catch(() => undefined)
115101
return stats?.isDirectory() === true

0 commit comments

Comments
 (0)