Skip to content

Commit 8491f8e

Browse files
authored
feat(cli): implement prefix command (#12728)
Adds the `prefix` command that prints the local prefix path (the nearest ancestor directory that contains a package.json, node_modules, pnpm-workspace.yaml, package.json5, or package.yaml). With --global it prints the global prefix. TypeScript: new cmd/prefix.ts module, registered in cmd/index.ts and removed from notImplemented.ts. Full integration test suite in test/prefix.ts. Rust (pacquet): PrefixArgs struct and find_local_prefix walk-up in cli_args/prefix.rs; subcommand wired through cli_command.rs, dispatch.rs, and dispatch_query.rs. Integration tests in crates/cli/tests/prefix.rs.
1 parent 72b1927 commit 8491f8e

12 files changed

Lines changed: 332 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"pnpm": minor
3+
---
4+
5+
Added the `prefix` command which prints the current package prefix directory (or global prefix directory if `-g` / `--global` is used).

‎pacquet/crates/cli/src/cli_args.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ pub mod patch_commit;
3333
pub mod patch_remove;
3434
pub(crate) mod patch_state;
3535
pub mod ping;
36+
pub mod prefix;
3637
pub mod prune;
3738
pub mod rebuild;
3839
pub mod recursive;

‎pacquet/crates/cli/src/cli_args/cli_command.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ use super::{
3131
patch_commit::PatchCommitArgs,
3232
patch_remove::PatchRemoveArgs,
3333
ping::PingArgs,
34+
prefix::PrefixArgs,
3435
prune::PruneArgs,
3536
rebuild::RebuildArgs,
3637
remove::RemoveArgs,
@@ -210,6 +211,8 @@ pub enum CliCommand {
210211
Bin(BinArgs),
211212
/// Print the effective `node_modules` directory.
212213
Root(RootArgs),
214+
/// Print the current package prefix.
215+
Prefix(PrefixArgs),
213216
/// Manage the pnpm configuration files.
214217
#[clap(visible_alias = "c")]
215218
Config(ConfigArgs),

‎pacquet/crates/cli/src/cli_args/dispatch.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,7 @@ fn route<'a>(command: CliCommand, ctx: &RunCtx<'a>) -> miette::Result<CommandFut
254254
CliCommand::Runtime(args) => dispatch_install::runtime(ctx, args),
255255
CliCommand::Bin(args) => dispatch_query::bin(ctx, args),
256256
CliCommand::Root(args) => dispatch_query::root(ctx, args),
257+
CliCommand::Prefix(args) => dispatch_query::prefix(ctx, args),
257258
CliCommand::Config(args) => dispatch_query::config(ctx, args),
258259
CliCommand::PackApp(args) => dispatch_query::pack_app(ctx, args),
259260
CliCommand::Store(command) => dispatch_query::store(ctx, command),

‎pacquet/crates/cli/src/cli_args/dispatch_query.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use super::{
1717
pack::PackArgs,
1818
pack_app::PackAppArgs,
1919
ping::PingArgs,
20+
prefix::PrefixArgs,
2021
repo::RepoArgs,
2122
reporter::ReporterType,
2223
root::RootArgs,
@@ -178,6 +179,11 @@ pub(super) fn root<'a>(ctx: &RunCtx<'a>, args: RootArgs) -> miette::Result<Comma
178179
Ok(Box::pin(std::future::ready(Ok(()))))
179180
}
180181

182+
pub(super) fn prefix<'a>(ctx: &RunCtx<'a>, args: PrefixArgs) -> miette::Result<CommandFuture<'a>> {
183+
args.run(ctx.dir)?;
184+
Ok(Box::pin(std::future::ready(Ok(()))))
185+
}
186+
181187
pub(super) fn config<'a>(ctx: &RunCtx<'a>, args: ConfigArgs) -> miette::Result<CommandFuture<'a>> {
182188
args.run((ctx.config)()?, ctx.dir)?;
183189
Ok(Box::pin(std::future::ready(Ok(()))))
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
use clap::Args;
2+
use derive_more::{Display, Error};
3+
use miette::Diagnostic;
4+
use std::path::{Path, PathBuf};
5+
6+
/// `pacquet prefix`: print the current package prefix.
7+
///
8+
/// Ports pnpm's `prefix` handler, walking up to find the nearest
9+
/// package prefix directory (containing package.json, `node_modules`, etc.).
10+
#[derive(Debug, Args)]
11+
pub struct PrefixArgs {
12+
/// Print the global prefix
13+
#[clap(short = 'g', long)]
14+
pub global: bool,
15+
}
16+
17+
/// Errors specific to `pacquet prefix`.
18+
#[derive(Debug, Display, Error, Diagnostic)]
19+
#[non_exhaustive]
20+
pub enum PrefixError {
21+
/// `--global` is rejected because the global-dir machinery (pnpm's
22+
/// `@pnpm/global.commands`) is not ported to pacquet yet; refuse rather
23+
/// than print a wrong path.
24+
#[display(
25+
"`pacquet prefix --global` is not supported yet; global package management has not been ported to pacquet."
26+
)]
27+
#[diagnostic(code(pacquet_cli::prefix_global_unsupported))]
28+
GlobalUnsupported,
29+
30+
/// IO error while looking up the prefix.
31+
#[display("failed to access {}: {source}", path.display())]
32+
#[diagnostic(code(pacquet_cli::prefix_io_error))]
33+
Io { path: PathBuf, source: std::io::Error },
34+
}
35+
36+
/// Find the nearest directory containing package.json, `node_modules`, etc.
37+
/// Port of findLocalPrefix from pnpm.
38+
pub fn find_local_prefix(start_dir: &Path) -> miette::Result<PathBuf> {
39+
let mut name = start_dir.to_path_buf();
40+
41+
while name.file_name().is_some_and(|f| f == "node_modules") {
42+
if let Some(parent) = name.parent() {
43+
name = parent.to_path_buf();
44+
} else {
45+
break;
46+
}
47+
}
48+
49+
if name == start_dir { find_prefix_up(&name, &name) } else { Ok(name) }
50+
}
51+
52+
fn find_prefix_up(name: &Path, original: &Path) -> miette::Result<PathBuf> {
53+
let mut current = name.to_path_buf();
54+
let targets =
55+
["node_modules", "package.json", "package.json5", "package.yaml", "pnpm-workspace.yaml"];
56+
57+
loop {
58+
for target in &targets {
59+
let target_path = current.join(target);
60+
match target_path.try_exists() {
61+
Ok(true) => return Ok(current),
62+
Ok(false) => continue,
63+
Err(e) => {
64+
return Err(PrefixError::Io { path: target_path, source: e }.into());
65+
}
66+
}
67+
}
68+
69+
match current.parent() {
70+
Some(parent) => {
71+
if parent == current {
72+
return Ok(original.to_path_buf());
73+
}
74+
current = parent.to_path_buf();
75+
}
76+
None => return Ok(original.to_path_buf()),
77+
}
78+
}
79+
}
80+
81+
impl PrefixArgs {
82+
pub fn run(self, dir: &Path) -> miette::Result<()> {
83+
if self.global {
84+
return Err(PrefixError::GlobalUnsupported.into());
85+
}
86+
let prefix_dir = find_local_prefix(dir)?;
87+
println!("{}", prefix_dir.display());
88+
Ok(())
89+
}
90+
}

‎pacquet/crates/cli/tests/prefix.rs‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
use assert_cmd::prelude::*;
2+
use command_extra::CommandExtra;
3+
use pacquet_testing_utils::bin::CommandTempCwd;
4+
use pretty_assertions::assert_eq;
5+
use std::{
6+
fs,
7+
path::{Path, PathBuf},
8+
process::Command,
9+
};
10+
11+
fn canonicalize(path: &Path) -> PathBuf {
12+
dunce::canonicalize(path).expect("canonicalize path")
13+
}
14+
15+
#[test]
16+
fn prefix_prints_the_local_prefix_dir() {
17+
let CommandTempCwd { pacquet, root, workspace, .. } = CommandTempCwd::init();
18+
fs::write(workspace.join("package.json"), r#"{ "name": "root-pkg" }"#)
19+
.expect("write package.json");
20+
21+
let output = pacquet.with_args(["prefix"]).output().expect("run pacquet prefix");
22+
dbg!(&output);
23+
assert!(output.status.success(), "pacquet prefix should succeed");
24+
25+
let expected = format!("{}\n", canonicalize(&workspace).display());
26+
assert_eq!(String::from_utf8_lossy(&output.stdout), expected);
27+
28+
drop(root);
29+
}
30+
31+
#[test]
32+
fn prefix_walks_up_to_find_package_json() {
33+
let CommandTempCwd { root, workspace, .. } = CommandTempCwd::init();
34+
fs::write(workspace.join("package.json"), r#"{ "name": "root-pkg" }"#)
35+
.expect("write package.json");
36+
37+
let member = workspace.join("sub/dir/deep");
38+
fs::create_dir_all(&member).expect("create member dir");
39+
40+
let pacquet_out = Command::cargo_bin("pacquet")
41+
.expect("find the pacquet binary")
42+
.with_current_dir(&member)
43+
.with_args(["prefix"])
44+
.output()
45+
.expect("run pacquet prefix in the subdir");
46+
assert!(pacquet_out.status.success(), "pacquet prefix should succeed in the subdir");
47+
48+
let expected = format!("{}\n", canonicalize(&workspace).display());
49+
assert_eq!(String::from_utf8_lossy(&pacquet_out.stdout), expected);
50+
51+
drop(root);
52+
}
53+
54+
#[test]
55+
fn prefix_walks_up_from_node_modules() {
56+
let CommandTempCwd { root, workspace, .. } = CommandTempCwd::init();
57+
fs::write(workspace.join("package.json"), r#"{ "name": "root-pkg" }"#)
58+
.expect("write package.json");
59+
60+
let nm_dir = workspace.join("node_modules/some-pkg");
61+
fs::create_dir_all(&nm_dir).expect("create node_modules/some-pkg dir");
62+
63+
let pacquet_out = Command::cargo_bin("pacquet")
64+
.expect("find the pacquet binary")
65+
.with_current_dir(&nm_dir)
66+
.with_args(["prefix"])
67+
.output()
68+
.expect("run pacquet prefix from inside node_modules");
69+
assert!(pacquet_out.status.success(), "pacquet prefix should succeed from inside node_modules");
70+
71+
let expected = format!("{}\n", canonicalize(&workspace).display());
72+
assert_eq!(String::from_utf8_lossy(&pacquet_out.stdout), expected);
73+
74+
drop(root);
75+
}
76+
77+
#[test]
78+
fn prefix_global_is_not_supported_yet() {
79+
let CommandTempCwd { pacquet, root, .. } = CommandTempCwd::init();
80+
81+
let output = pacquet.with_args(["prefix", "-g"]).output().expect("run pacquet prefix -g");
82+
dbg!(&output);
83+
assert!(!output.status.success(), "pacquet prefix -g should fail until global support lands");
84+
85+
let stderr = String::from_utf8_lossy(&output.stderr);
86+
assert!(stderr.contains("not supported yet"), "stderr should explain the gap: {stderr}");
87+
88+
drop(root);
89+
}
90+
91+
#[test]
92+
fn prefix_resolves_from_a_workspace_subdir() {
93+
let CommandTempCwd { root, workspace, .. } = CommandTempCwd::init();
94+
95+
fs::write(workspace.join("package.json"), r#"{ "name": "wsroot", "version": "1.0.0" }"#)
96+
.expect("write workspace-root package.json");
97+
let member = workspace.join("packages/foo");
98+
fs::create_dir_all(&member).expect("create workspace member dir");
99+
fs::write(member.join("package.json"), r#"{ "name": "foo", "version": "1.0.0" }"#)
100+
.expect("write member package.json");
101+
102+
let sub_member = member.join("src/utils");
103+
fs::create_dir_all(&sub_member).expect("create sub_member dir");
104+
105+
let pacquet_out = Command::cargo_bin("pacquet")
106+
.expect("find the pacquet binary")
107+
.with_current_dir(&sub_member)
108+
.with_args(["prefix"])
109+
.output()
110+
.expect("run pacquet prefix in the subdir");
111+
assert!(pacquet_out.status.success(), "pacquet prefix should succeed in the subdir");
112+
113+
// From the workspace subdir the nearest package.json parent is the member
114+
let expected = format!("{}\n", canonicalize(&member).display());
115+
assert_eq!(String::from_utf8_lossy(&pacquet_out.stdout), expected);
116+
117+
drop(root);
118+
}

‎pnpm11/pnpm/src/cmd/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import * as ci from './cleanInstall.js'
3434
import { createHelp } from './help.js'
3535
import * as installTest from './installTest.js'
3636
import { NOT_IMPLEMENTED_COMMAND_SET, notImplementedCommandDefinitions } from './notImplemented.js'
37+
import * as prefix from './prefix.js'
3738
import * as recursive from './recursive.js'
3839
import * as root from './root.js'
3940

@@ -167,6 +168,7 @@ const commands: CommandDefinition[] = [
167168
patchRemove,
168169
peers,
169170
ping,
171+
prefix,
170172
prune,
171173
publish,
172174
stage,

‎pnpm11/pnpm/src/cmd/notImplemented.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ const NOT_IMPLEMENTED_COMMANDS = [
66
'access',
77
'edit',
88
'issues',
9-
'prefix',
109
'profile',
1110
'set-script',
1211
'team',

‎pnpm11/pnpm/src/cmd/prefix.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import path from 'node:path'
2+
3+
import { docsUrl } from '@pnpm/cli.utils'
4+
import { types as allTypes } from '@pnpm/config.reader'
5+
import { PnpmError } from '@pnpm/error'
6+
import { pick } from 'ramda'
7+
import { renderHelp } from 'render-help'
8+
9+
export const rcOptionsTypes = cliOptionsTypes
10+
11+
export function cliOptionsTypes (): Record<string, unknown> {
12+
return pick([
13+
'global',
14+
], allTypes)
15+
}
16+
17+
export const commandNames = ['prefix']
18+
19+
export function help (): string {
20+
return renderHelp({
21+
description: 'Print the current package prefix.',
22+
descriptionLists: [
23+
{
24+
title: 'Options',
25+
26+
list: [
27+
{
28+
description: 'Print the global prefix',
29+
name: '--global',
30+
shortAlias: '-g',
31+
},
32+
],
33+
},
34+
],
35+
url: docsUrl('prefix'),
36+
usages: ['pnpm prefix [-g]'],
37+
})
38+
}
39+
40+
export async function handler (
41+
opts: {
42+
dir: string
43+
global?: boolean
44+
globalPkgDir?: string
45+
}
46+
): Promise<string> {
47+
if (opts.global) {
48+
if (!opts.globalPkgDir) {
49+
throw new PnpmError('MISSING_GLOBAL_PACKAGE_DIR', 'The global package directory could not be resolved.')
50+
}
51+
return path.dirname(opts.globalPkgDir)
52+
}
53+
return opts.dir
54+
}

0 commit comments

Comments
 (0)