diff --git a/Cargo.lock b/Cargo.lock index 4fcaa797c8..68737aee27 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8383,7 +8383,6 @@ version = "1.8.0" dependencies = [ "anyhow", "async-trait", - "base64-simd", "clap", "console", "cow-utils", @@ -8403,7 +8402,7 @@ dependencies = [ "tempfile", "tokio", "tracing", - "uuid", + "vp_app_target", "vp_cli_help", "vp_command", "vp_error", @@ -8415,20 +8414,39 @@ dependencies = [ "vt", "vt_casefold", "vt_path", - "vt_select", "vt_str", "vt_workspace", "wax", ] +[[package]] +name = "vp_app_target" +version = "0.0.0" +dependencies = [ + "anyhow", + "base64-simd", + "serde_json", + "tempfile", + "uuid", + "vp_shared", + "vp_static_config", + "vt_path", + "vt_select", + "vt_str", + "vt_workspace", +] + [[package]] name = "vp_cli_help" version = "0.0.0" dependencies = [ "clap", "console", + "serde_json", "terminal_size", "vp_shared", + "vt_path", + "vt_workspace", ] [[package]] @@ -8526,6 +8544,7 @@ dependencies = [ "tracing", "url", "uuid", + "vp_app_target", "vp_cli_help", "vp_command", "vp_error", diff --git a/Cargo.toml b/Cargo.toml index 6739fbdf6e..af2bdc87c4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -304,6 +304,7 @@ typedmap = "0.6.0" url = "2.5.9" uuid = "1.27.0" vfs = "0.13.0" +vp_app_target = { path = "crates/vp_app_target" } vp_command = { path = "crates/vp_command" } vp_cli_help = { path = "crates/vp_cli_help" } vp_error = { path = "crates/vp_error" } @@ -349,7 +350,9 @@ oxc = { version = "0.156.0", features = [ oxc_allocator = { version = "0.156.0", features = ["pool"] } oxc_ast = "0.156.0" oxc_ecmascript = "0.156.0" -oxc_parser = "0.156.0" +# Only `vp_static_config` uses the parser directly. It reads plain config values, so the +# global `vp` skips the regular expression parser. The `oxc` crate enables it for the binding. +oxc_parser = { version = "0.156.0", default-features = false } oxc_span = "0.156.0" oxc_napi = "0.156.0" oxc_str = "0.156.0" diff --git a/crates/vp_app_target/Cargo.toml b/crates/vp_app_target/Cargo.toml new file mode 100644 index 0000000000..af4bf7e739 --- /dev/null +++ b/crates/vp_app_target/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "vp_app_target" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license.workspace = true +publish = false +rust-version.workspace = true + +[dependencies] +anyhow = { workspace = true } +base64-simd = { workspace = true } +serde_json = { workspace = true } +uuid = { workspace = true, features = ["v4"] } +vp_shared = { workspace = true } +vp_static_config = { workspace = true } +vt_path = { workspace = true } +vt_select = { workspace = true } +vt_str = { workspace = true } +vt_workspace = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } + +[lints] +workspace = true + +[lib] +doctest = false diff --git a/packages/cli/binding/src/cli/app_target.rs b/crates/vp_app_target/src/lib.rs similarity index 73% rename from packages/cli/binding/src/cli/app_target.rs rename to crates/vp_app_target/src/lib.rs index bc58059bad..e0593f1cbb 100644 --- a/packages/cli/binding/src/cli/app_target.rs +++ b/crates/vp_app_target/src/lib.rs @@ -1,27 +1,30 @@ //! Target elicitation for bare app commands at a workspace root. //! //! A bare `vp dev`/`build`/`preview`/`pack` at a workspace root has no target -//! and would silently run against the root. Explicit `-C` and any subcommand -//! arguments skip target selection. An exact bare command uses -//! `defaultPackage`, a root intent signal, or the package picker. See -//! rfcs/cwd-flag.md. +//! and would silently run against the root. Both CLI entry points call this +//! resolver only for bare app commands without an explicit `-C`. It uses +//! `defaultPackage`, a root intent signal, or the package picker. The global +//! CLI resolves the target first, so the selected directory gets its own +//! Node.js runtime and `vite-plus` installation. See rfcs/cwd-flag.md. -use vp_error::Error; +#![deny(clippy::print_stdout)] + +use anyhow::Result; use vp_shared::{env_vars, output}; -use vt::ExitStatus; use vt_path::{AbsolutePath, AbsolutePathBuf}; +use vt_str::format; use vt_workspace::WorkspaceFile; -use super::types::SynthesizableSubcommand; - /// Where a bare app command should run. -pub(super) enum AppTarget { +pub enum AppTarget { /// No elicitation applies; run in the invocation directory as today. - CurrentDir, + /// Carries the workspace root found for that directory, when the lookup + /// succeeded, so the caller can skip a second `find_workspace_root` walk. + CurrentDir(Option), /// Run as if invoked in this directory (implicit `-C`). Dir(AbsolutePathBuf), /// Elicitation printed its output and decided the exit code. - Exit(ExitStatus), + Exit(u8), } struct PackageRow { @@ -31,15 +34,14 @@ struct PackageRow { likely_runnable: bool, } -/// App commands are the single-target subcommands; everything else never -/// goes through elicitation. -fn app_command_parts(subcommand: &SynthesizableSubcommand) -> Option<(&'static str, &[String])> { - match subcommand { - SynthesizableSubcommand::Dev { args } => Some(("dev", args)), - SynthesizableSubcommand::Build { args } => Some(("build", args)), - SynthesizableSubcommand::Preview { args } => Some(("preview", args)), - SynthesizableSubcommand::Pack { args } => Some(("pack", args)), - _ => None, +/// Do these app command arguments leave target selection to the CLI? Any +/// argument skips selection, except a lone `--`, which build and dev pass on +/// to Vite unchanged. +pub fn is_bare_app_command(args: &[impl AsRef]) -> bool { + match args { + [] => true, + [separator] => separator.as_ref() == "--", + _ => false, } } @@ -99,7 +101,7 @@ fn resolve_default_package( ) -> AppTarget { let fail = |msg: &str| { output::error(msg); - AppTarget::Exit(ExitStatus(1)) + AppTarget::Exit(1) }; match value { vp_static_config::FieldValue::Json(serde_json::Value::String(dir)) => { @@ -126,13 +128,13 @@ fn resolve_default_package( /// window-title update) for the tests to synchronize on, same gate and /// protocol as packages/prompts/src/milestone.ts; real terminals never see /// the marker as content. -fn run_package_picker(command: &str, rows: &[PackageRow]) -> Result, Error> { +fn run_package_picker(command: &str, rows: &[PackageRow]) -> Result> { let emit_milestones = std::env::var_os(env_vars::VP_EMIT_MILESTONES).is_some_and(|value| value == "1"); let items: Vec = rows .iter() .map(|row| vt_select::SelectItem { - label: vt_str::format!("{} {}", row.name, row.path), + label: format!("{} {}", row.name, row.path), display_name: row.name.clone(), description: row.path.clone(), group: None, @@ -157,12 +159,10 @@ fn run_package_picker(command: &str, rows: &[PackageRow]) -> Result Some(selected_index), vt_select::SelectResult::Cancelled => None, @@ -192,8 +192,8 @@ fn emit_milestone_title(name: &str) { /// picker. Slightly over-approximates (an empty workspace reports true), in /// which case the script merely spawns the real binary, which then behaves /// identically to a direct invocation. -pub(super) fn needs_elicitation(subcommand: &SynthesizableSubcommand, cwd: &AbsolutePath) -> bool { - matches!(classify(subcommand, cwd, false), Classification::Elicit(..)) +pub fn needs_elicitation(command: &str, cwd: &AbsolutePath) -> bool { + !matches!(classify(command, cwd), Classification::RunInPlace(_)) } /// Outcome of classifying a bare app command. @@ -204,13 +204,6 @@ enum Classification { /// inside a large monorepo, where the walk is the only per-invocation /// cost this feature adds. RunInPlace(Option), - /// Elicit a target: `defaultPackage`, or the picker/listing at a - /// workspace root. - Elicit(&'static str, Elicitation), -} - -/// Why a bare app command needs target elicitation. -enum Elicitation { /// The invocation root's config explicitly declares `defaultPackage` /// (with this value — possibly invalid, which the resolver reports). DefaultPackage(vp_static_config::FieldValue), @@ -236,10 +229,8 @@ fn default_package_for_command( } } -/// The RFC's resolution order, written once for both entry points. An explicit -/// `-C` or any subcommand argument runs in place. An exact bare app command -/// then uses `defaultPackage` at the invocation root or checks the workspace -/// root itself. `defaultPackage` is a root-pointer concept: it applies where +/// A bare app command uses `defaultPackage` at the invocation root or checks +/// the workspace root itself. `defaultPackage` applies where /// the invocation directory is its own root (a workspace root, a standalone /// package, or a framework directory with no package.json ancestry). Below a /// workspace root, the current directory identifies the target. A member's @@ -248,17 +239,7 @@ fn default_package_for_command( /// The one `find_workspace_root` walk here rides back out on /// [`Classification::RunInPlace`] whenever the command ends up running in /// `cwd`, so a bare command in a sub-package walks the tree once, not twice. -fn classify( - subcommand: &SynthesizableSubcommand, - cwd: &AbsolutePath, - explicit_chdir: bool, -) -> Classification { - let Some((command, args)) = app_command_parts(subcommand) else { - return Classification::RunInPlace(None); - }; - if explicit_chdir || !args.is_empty() { - return Classification::RunInPlace(None); - } +fn classify(command: &str, cwd: &AbsolutePath) -> Classification { let workspace = vt_workspace::find_workspace_root(cwd); let at_invocation_root = workspace.as_ref().map_or(true, |(_, rel_from_root)| rel_from_root.as_str().is_empty()); @@ -270,7 +251,7 @@ fn classify( .and_then(|config| config.get_declared("defaultPackage")) .and_then(|value| default_package_for_command(command, value)) { - return Classification::Elicit(command, Elicitation::DefaultPackage(value)); + return Classification::DefaultPackage(value); } // The picker/listing needs workspace metadata; anything unresolvable // keeps today's behavior (the caller surfaces its own workspace errors). @@ -295,33 +276,22 @@ fn classify( if root_has_intent_signal(&root_config, &workspace_root.path, command) { return Classification::RunInPlace(Some(workspace_root)); } - Classification::Elicit(command, Elicitation::WorkspaceRoot(workspace_root)) + Classification::WorkspaceRoot(workspace_root) } -/// Resolve an app command's target. The second tuple element is the workspace -/// root already found for `cwd`. It is present only when the command runs in -/// the unchanged `cwd`, so it matches a fresh lookup there. The caller reuses -/// it to skip a second `find_workspace_root` walk. -pub(super) fn resolve_app_target( - subcommand: &SynthesizableSubcommand, - cwd: &AbsolutePath, - explicit_chdir: bool, -) -> Result<(AppTarget, Option), Error> { - let (command, elicitation) = match classify(subcommand, cwd, explicit_chdir) { +/// Resolve the target of a bare `dev`, `build`, `preview`, or `pack` command. +pub fn resolve_app_target(command: &str, cwd: &AbsolutePath) -> Result { + let workspace_root = match classify(command, cwd) { Classification::RunInPlace(workspace_root) => { - return Ok((AppTarget::CurrentDir, workspace_root)); + return Ok(AppTarget::CurrentDir(workspace_root)); } - Classification::Elicit(command, elicitation) => (command, elicitation), - }; - let workspace_root = match elicitation { - Elicitation::DefaultPackage(value) => { - return Ok((resolve_default_package(command, cwd, value), None)); + Classification::DefaultPackage(value) => { + return Ok(resolve_default_package(command, cwd, value)); } - Elicitation::WorkspaceRoot(workspace_root) => workspace_root, + Classification::WorkspaceRoot(workspace_root) => workspace_root, }; - let graph = - vt_workspace::load_package_graph(&workspace_root).map_err(|e| Error::Anyhow(e.into()))?; + let graph = vt_workspace::load_package_graph(&workspace_root)?; let mut root_row = None; let mut rows: Vec = graph .node_weights() @@ -348,7 +318,7 @@ pub(super) fn resolve_app_target( if rows.is_empty() { // The workspace root is the only target. Static extraction can miss // plugin-provided config, so run the command in place. - return Ok((AppTarget::CurrentDir, Some(workspace_root))); + return Ok(AppTarget::CurrentDir(Some(workspace_root))); } rows.sort_by(|a, b| { (!a.likely_runnable, a.path.as_str()).cmp(&(!b.likely_runnable, b.path.as_str())) @@ -371,14 +341,14 @@ pub(super) fn resolve_app_target( run_package_picker(command, &rows)? }; let Some(index) = picked else { - return Ok((AppTarget::Exit(ExitStatus(130)), None)); + return Ok(AppTarget::Exit(130)); }; let row = &rows[index]; - // Deliberately stdout via println!: these lines belong to the - // command's own output stream, like the tool output that follows. - println!("Selected package: {} ({})", row.name, row.path); - println!("Tip: run this directly with `vp -C {} {command}`", row.path); - return Ok((AppTarget::Dir(row.absolute.clone()), None)); + output::print_stdout_line(format_args!( + "Selected package: {} ({})\nTip: run this directly with `vp -C {} {command}`", + row.name, row.path, row.path + )); + return Ok(AppTarget::Dir(row.absolute.clone())); } output::error(&format!("`vp {command}` at the workspace root needs a target package.")); @@ -392,7 +362,7 @@ pub(super) fn resolve_app_target( let example = &rows[0].path; output::raw_stderr(&format!(" Pass a directory: vp -C {example} {command}")); output::raw_stderr(&format!(" Or run every package's {command} script: vp run -r {command}")); - Ok((AppTarget::Exit(ExitStatus(1)), None)) + Ok(AppTarget::Exit(1)) } #[cfg(test)] @@ -401,6 +371,24 @@ mod tests { use super::*; + #[test] + fn only_bare_arguments_select_a_target() { + let no_args: [&str; 0] = []; + assert!(is_bare_app_command(&no_args)); + assert!(is_bare_app_command(&["--"])); + for args in [ + &["--", "--mode"][..], + &["--watch"], + &["--ssr"], + &["apps/web"], + &["--host"], + &["--help"], + &["--root", "src"], + ] { + assert!(!is_bare_app_command(args), "{args:?}"); + } + } + #[test] fn vite_commands_share_root_intent_signals() { let temp = tempfile::tempdir().expect("temporary directory should exist"); @@ -409,7 +397,8 @@ mod tests { for field in ["root", "build", "input", "environments", "appType"] { fs::write( temp.path().join("vite.config.ts"), - format!("const value = {{}}; export default {{ {field}: value }};"), + vt_str::format!("const value = {{}}; export default {{ {field}: value }};") + .as_bytes(), ) .expect("config should be written"); let config = vp_static_config::resolve_static_config(&dir); @@ -442,40 +431,4 @@ mod tests { assert!(!root_has_intent_signal(&config, &dir, command)); } } - - #[test] - fn arguments_and_explicit_chdir_run_in_place() { - let cwd = AbsolutePathBuf::new(std::env::current_dir().expect("cwd should exist")) - .expect("cwd should be absolute"); - let commands = [ - SynthesizableSubcommand::Build { args: vec!["--watch".into()] }, - SynthesizableSubcommand::Build { args: vec!["--ssr".into()] }, - SynthesizableSubcommand::Build { args: vec!["apps/web".into()] }, - SynthesizableSubcommand::Dev { args: vec!["--host".into()] }, - SynthesizableSubcommand::Preview { args: vec!["--help".into()] }, - SynthesizableSubcommand::Pack { args: vec!["--root".into(), "src".into()] }, - ]; - - for command in &commands { - assert!(matches!(classify(command, &cwd, false), Classification::RunInPlace(None))); - } - assert!(matches!( - classify(&SynthesizableSubcommand::Build { args: vec![] }, &cwd, true), - Classification::RunInPlace(None) - )); - } - - #[test] - fn only_app_commands_elicit() { - for (subcommand, expected) in [ - (SynthesizableSubcommand::Dev { args: vec![] }, Some("dev")), - (SynthesizableSubcommand::Build { args: vec![] }, Some("build")), - (SynthesizableSubcommand::Preview { args: vec![] }, Some("preview")), - (SynthesizableSubcommand::Pack { args: vec![] }, Some("pack")), - (SynthesizableSubcommand::Lint { args: vec![] }, None), - (SynthesizableSubcommand::Test { args: vec![] }, None), - ] { - assert_eq!(app_command_parts(&subcommand).map(|(name, _)| name), expected); - } - } } diff --git a/crates/vp_cli_help/Cargo.toml b/crates/vp_cli_help/Cargo.toml index 455f5fd3bd..184388388d 100644 --- a/crates/vp_cli_help/Cargo.toml +++ b/crates/vp_cli_help/Cargo.toml @@ -13,8 +13,11 @@ doctest = false [dependencies] clap = { workspace = true } console = { workspace = true } +serde_json = { workspace = true } terminal_size = { workspace = true } vp_shared = { workspace = true } +vt_path = { workspace = true } +vt_workspace = { workspace = true } [lints] workspace = true diff --git a/crates/vp_cli_help/src/lib.rs b/crates/vp_cli_help/src/lib.rs index 95f99f1761..9fd88315cd 100644 --- a/crates/vp_cli_help/src/lib.rs +++ b/crates/vp_cli_help/src/lib.rs @@ -7,6 +7,7 @@ //! Shared help documents and diagnostics for Vite+ command-line interfaces. pub mod error; +pub mod script_note; use std::{borrow::Cow, fmt::Write as _, io::Write as _}; diff --git a/packages/cli/binding/src/cli/script_note.rs b/crates/vp_cli_help/src/script_note.rs similarity index 91% rename from packages/cli/binding/src/cli/script_note.rs rename to crates/vp_cli_help/src/script_note.rs index 299293433d..865e3c7a47 100644 --- a/packages/cli/binding/src/cli/script_note.rs +++ b/crates/vp_cli_help/src/script_note.rs @@ -6,8 +6,7 @@ //! uses points at `vpr`. use console::style; -use vp_shared::output; -use vt::MARKER_ENV_NAME; +use vp_shared::{env_vars, output}; use vt_path::AbsolutePath; const NPM_LIFECYCLE_EVENT_ENV_NAME: &str = "npm_lifecycle_event"; @@ -18,12 +17,12 @@ const NPM_LIFECYCLE_EVENT_ENV_NAME: &str = "npm_lifecycle_event"; /// `command` is the built-in as the user spelled it: the global binary forwards /// the invoked subcommand, so `vp format` stays `format` here. A direct local /// invocation takes the first argument before help normalization. -pub(super) fn print(command: Option<&str>, cwd: &AbsolutePath) { - let Some(command) = command else { return }; +pub fn print(command: Option<&str>, cwd: &AbsolutePath) { + let Some(command) = command.filter(|command| !command.is_empty()) else { return }; // A task spawned this command, so the user is already on a script-running // path. npm-compatible runners set `npm_lifecycle_event`; Vite Task uses // its own marker. - if std::env::var_os(MARKER_ENV_NAME).is_some() + if std::env::var_os(env_vars::VP_RUN).is_some() || std::env::var_os(NPM_LIFECYCLE_EVENT_ENV_NAME).is_some_and(|event| !event.is_empty()) { return; diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/.node-version b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/.node-version new file mode 100644 index 0000000000..ce62013c39 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/.node-version @@ -0,0 +1 @@ +24.22.1 diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/app/.node-version b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/app/.node-version new file mode 100644 index 0000000000..b8b23ca93c --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/app/.node-version @@ -0,0 +1 @@ +22.23.4 diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/app/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/app/package.json new file mode 100644 index 0000000000..0a2d4152f2 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/app/package.json @@ -0,0 +1,4 @@ +{ + "name": "app", + "private": true +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/package.json b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/package.json new file mode 100644 index 0000000000..fd16b98491 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/package.json @@ -0,0 +1,4 @@ +{ + "name": "root", + "private": true +} diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/probe.mjs b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/probe.mjs new file mode 100644 index 0000000000..441f1e7f96 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/probe.mjs @@ -0,0 +1,22 @@ +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { readFileSync, realpathSync } from 'node:fs'; + +// A stand-in for the selected package's Vite+ CLI. It checks that the global +// CLI runs it as `vp -C ` would: in the package, with the package's +// Node.js pin, and with the directory already fixed. +const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')); +const { name } = JSON.parse(readFileSync('package.json', 'utf8')); +const expectedNode = `v${readFileSync('.node-version', 'utf8').trim()}`; +const pathNode = execFileSync('node', ['--version'], { encoding: 'utf8' }).trim(); +assert.equal(name, 'app'); +assert.equal(process.version, expectedNode); +assert.equal(pathNode, expectedNode); +assert.equal(process.env.VP_EXPLICIT_CHDIR, '1'); +if (process.platform !== 'win32' && realpathSync(process.env.PWD) !== realpathSync(process.cwd())) { + throw new Error('PWD differs from cwd'); +} + +console.log(`Vite+ ${version}: ${process.argv.slice(2).join(' ')} in ${name}`); +console.log(`Process Node.js: ${process.version}`); +console.log(`PATH Node.js: ${pathNode}`); diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots.toml b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots.toml new file mode 100644 index 0000000000..e32244f7a8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots.toml @@ -0,0 +1,36 @@ +[[case]] +name = "default_package_uses_target_toolchain" +vp = "global" +comment = "The global CLI resolves defaultPackage first, so the target runs with its own Node.js and Vite+, as -C does." +steps = [ + { argv = ["vpt", "mkdir", "-p", "app/node_modules/vite-plus/dist"], snapshot = false }, + { argv = ["vpt", "write-file", "app/node_modules/vite-plus/package.json", '{"name":"vite-plus","version":"1.8.0","type":"module"}'], snapshot = false }, + { argv = ["vpt", "cp", "probe.mjs", "app/node_modules/vite-plus/dist/bin.js"], snapshot = false }, + ["vp", "build"], + ["vp", "build", "--"], + ["vp", "dev"], + ["vp", "-C", "app", "build"], +] + +[[case]] +name = "workspace_uses_selected_members_runtime" +vp = "global" +comment = "Auto-selection and the picker run the member with its own Node.js pin and the shared Vite+ installation." +steps = [ + { argv = ["vpt", "rm", "vite.config.ts"], snapshot = false }, + { argv = ["vpt", "write-file", "pnpm-workspace.yaml", "packages:\n - app\n - other\n"], snapshot = false }, + { argv = ["vpt", "touch-file", "app/index.html"], snapshot = false }, + { argv = ["vpt", "write-file", "other/package.json", '{"name":"other","private":true}'], snapshot = false }, + { argv = ["vpt", "mkdir", "-p", "node_modules/vite-plus/dist"], snapshot = false }, + { argv = ["vpt", "write-file", "node_modules/vite-plus/package.json", '{"name":"vite-plus","version":"1.8.0","type":"module"}'], snapshot = false }, + { argv = ["vpt", "cp", "probe.mjs", "node_modules/vite-plus/dist/bin.js"], snapshot = false }, + ["vp", "-C", "app", "build"], + ["vp", "build"], + { argv = ["vpt", "touch-file", "other/index.html"], snapshot = false }, + { argv = ["vp", "build"], interactions = [ + { "expect-milestone" = "package-select::0" }, + { "write" = "app" }, + { "expect-milestone" = "package-select:app:0" }, + { "write-key" = "enter" }, + ] }, +] diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots/default_package_uses_target_toolchain.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots/default_package_uses_target_toolchain.md new file mode 100644 index 0000000000..7d933f77a8 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots/default_package_uses_target_toolchain.md @@ -0,0 +1,55 @@ +# default_package_uses_target_toolchain + +The global CLI resolves defaultPackage first, so the target runs with its own Node.js and Vite+, as -C does. + +## `vpt mkdir -p app/node_modules/vite-plus/dist` + + +## `vpt write-file app/node_modules/vite-plus/package.json '{"name":"vite-plus","version":"1.8.0","type":"module"}'` + + +## `vpt cp probe.mjs app/node_modules/vite-plus/dist/bin.js` + + +## `vp build` + +``` +VITE+ - The Unified Toolchain for the Web + +note: vp build: using ./app (defaultPackage in vite.config.ts) +Vite+ : build in app +Process Node.js: +PATH Node.js: +``` + +## `vp build --` + +``` +VITE+ - The Unified Toolchain for the Web + +note: vp build: using ./app (defaultPackage in vite.config.ts) +Vite+ : build -- in app +Process Node.js: +PATH Node.js: +``` + +## `vp dev` + +``` +VITE+ - The Unified Toolchain for the Web + +note: vp dev: using ./app (defaultPackage in vite.config.ts) +Vite+ : dev in app +Process Node.js: +PATH Node.js: +``` + +## `vp -C app build` + +``` +VITE+ - The Unified Toolchain for the Web + +Vite+ : build in app +Process Node.js: +PATH Node.js: +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots/workspace_uses_selected_members_runtime.md b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots/workspace_uses_selected_members_runtime.md new file mode 100644 index 0000000000..507c065e9e --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/snapshots/workspace_uses_selected_members_runtime.md @@ -0,0 +1,90 @@ +# workspace_uses_selected_members_runtime + +Auto-selection and the picker run the member with its own Node.js pin and the shared Vite+ installation. + +## `vpt rm vite.config.ts` + + +## `vpt write-file pnpm-workspace.yaml 'packages: + - app + - other +'` + + +## `vpt touch-file app/index.html` + + +## `vpt write-file other/package.json '{"name":"other","private":true}'` + + +## `vpt mkdir -p node_modules/vite-plus/dist` + + +## `vpt write-file node_modules/vite-plus/package.json '{"name":"vite-plus","version":"1.8.0","type":"module"}'` + + +## `vpt cp probe.mjs node_modules/vite-plus/dist/bin.js` + + +## `vp -C app build` + +``` +VITE+ - The Unified Toolchain for the Web + +Vite+ : build in app +Process Node.js: +PATH Node.js: +``` + +## `vp build` + +``` +VITE+ - The Unified Toolchain for the Web + +Selected package: app (app) +Tip: run this directly with `vp -C app build` +Vite+ : build in app +Process Node.js: +PATH Node.js: +``` + +## `vpt touch-file other/index.html` + + +## `vp build` + +**→ expect-milestone:** `package-select::0` + +``` +VITE+ - The Unified Toolchain for the Web + +Select a package to build (↑/↓, Enter to run, type to search): + + › app app + other other + root . +``` + +**← write:** `app` + +**→ expect-milestone:** `package-select:app:0` + +``` +VITE+ - The Unified Toolchain for the Web + +Select a package to build (↑/↓, Enter to run, type to search): app + + › app app +``` + +**← write-key:** `enter` + +``` +VITE+ - The Unified Toolchain for the Web + +Selected package: app (app) +Tip: run this directly with `vp -C app build` +Vite+ : build in app +Process Node.js: +PATH Node.js: +``` diff --git a/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/vite.config.ts b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/vite.config.ts new file mode 100644 index 0000000000..876ab15d90 --- /dev/null +++ b/crates/vp_cli_snapshots/tests/cli_snapshots/fixtures/app_target_toolchain/vite.config.ts @@ -0,0 +1 @@ +export default { defaultPackage: './app' }; diff --git a/crates/vp_global_cli/Cargo.toml b/crates/vp_global_cli/Cargo.toml index 466ebeeefe..1e9fea8388 100644 --- a/crates/vp_global_cli/Cargo.toml +++ b/crates/vp_global_cli/Cargo.toml @@ -37,6 +37,7 @@ indexmap = { workspace = true } indoc = { workspace = true } jiff = { workspace = true } js-semver = { workspace = true } +vp_app_target = { workspace = true } vp_error = { workspace = true } vp_js_runtime = { workspace = true } vp_pm_cli = { workspace = true } diff --git a/crates/vp_global_cli/src/commands/delegate.rs b/crates/vp_global_cli/src/commands/delegate.rs index bf2dee8eb7..36dd322f8c 100644 --- a/crates/vp_global_cli/src/commands/delegate.rs +++ b/crates/vp_global_cli/src/commands/delegate.rs @@ -2,6 +2,8 @@ use std::process::{ExitStatus, Output}; +use vp_app_target::AppTarget; +use vp_cli_help::script_note; use vt_path::AbsolutePathBuf; use crate::{error::Error, js_executor::JsExecutor}; @@ -16,10 +18,15 @@ pub async fn execute( args: &[String], raw_subcommand: Option<&str>, ) -> Result { - execute_app(cwd, command, args, raw_subcommand, false).await + execute_local(cwd, command, args, raw_subcommand, false).await } -/// Execute an app command and preserve whether the user supplied `-C`. +/// Execute an app command (`dev`, `build`, `preview`, or `pack`). +/// +/// Without `-C`, a bare command can select another directory: `defaultPackage`, +/// the only workspace package that looks runnable, or the package picker. The +/// global CLI selects the directory before it resolves the local `vite-plus` +/// and the Node.js runtime, so the command runs as `vp -C ` would. pub async fn execute_app( cwd: AbsolutePathBuf, command: &str, @@ -27,9 +34,33 @@ pub async fn execute_app( raw_subcommand: Option<&str>, explicit_chdir: bool, ) -> Result { - let mut executor = JsExecutor::new(None) - .with_raw_subcommand(raw_subcommand) - .with_explicit_chdir(explicit_chdir); + let select_target = !explicit_chdir && vp_app_target::is_bare_app_command(args); + if !select_target { + return execute_local(cwd, command, args, raw_subcommand, explicit_chdir).await; + } + + // The note refers to a script in the directory where the user ran vp. + script_note::print(raw_subcommand.or(Some(command)), &cwd); + let target = vp_app_target::resolve_app_target(command, &cwd) + .map_err(|error| Error::Other(vt_str::format!("{error:#}")))?; + let cwd = match target { + AppTarget::CurrentDir(_) => cwd, + AppTarget::Dir(dir) => dir, + AppTarget::Exit(code) => return Ok(crate::cli::exit_status(i32::from(code))), + }; + // The local CLI must not select a target again or repeat the note. + execute_local(cwd, command, args, Some(""), true).await +} + +async fn execute_local( + cwd: AbsolutePathBuf, + command: &str, + args: &[String], + raw_subcommand: Option<&str>, + fixed_dir: bool, +) -> Result { + let mut executor = + JsExecutor::new(None).with_raw_subcommand(raw_subcommand).with_explicit_chdir(fixed_dir); let mut full_args = vec![command.to_string()]; full_args.extend(args.iter().cloned()); executor.delegate_to_local_cli(&cwd, &full_args).await diff --git a/crates/vp_global_cli/src/js_executor.rs b/crates/vp_global_cli/src/js_executor.rs index 694acdf89c..5b207b0129 100644 --- a/crates/vp_global_cli/src/js_executor.rs +++ b/crates/vp_global_cli/src/js_executor.rs @@ -35,7 +35,7 @@ pub struct JsExecutor { scripts_dir: Option, /// Subcommand as the user wrote it, forwarded to the CLI this one runs raw_subcommand: Option, - /// Whether the user selected the command directory with `-C` + /// Whether `-C` or app target selection fixed the command directory explicit_chdir: bool, /// Whether a project-local CLI miss should emit a warning before global fallback warn_on_missing_local_cli: bool, @@ -68,7 +68,8 @@ impl JsExecutor { self } - /// Preserve an explicit `-C` after the global CLI changes the child cwd. + /// Tell the delegated CLI that `-C` or app target selection fixed the + /// command directory, so that it does not select another one. pub const fn with_explicit_chdir(mut self, explicit_chdir: bool) -> Self { self.explicit_chdir = explicit_chdir; self diff --git a/crates/vp_shared/src/env_vars.rs b/crates/vp_shared/src/env_vars.rs index 80fd0dd53b..88d2d83909 100644 --- a/crates/vp_shared/src/env_vars.rs +++ b/crates/vp_shared/src/env_vars.rs @@ -193,17 +193,24 @@ pub const VP_EMIT_MILESTONES: &str = "VP_EMIT_MILESTONES"; /// before forwarding to the actual tool. pub const VP_SHIM_WRAPPER: &str = "VP_SHIM_WRAPPER"; +/// Vite Task sets this on the tasks that it spawns (`vt::MARKER_ENV_NAME`). +pub const VP_RUN: &str = "VP_RUN"; + /// The subcommand as the user wrote it, passed from the global CLI to the local /// one. /// /// A command runs under its canonical name (`vp format` runs `fmt`), which loses -/// the spelling. This carries the original alongside it. +/// the spelling. This carries the original alongside it. An empty value means +/// that the global CLI already printed the note about a script with the same +/// name. pub const VP_RAW_SUBCOMMAND: &str = "VP_RAW_SUBCOMMAND"; -/// Set (to `1`) when the global CLI delegates a command that used `-C`. +/// Set (to `1`) when `-C` or the global CLI's app target selection fixed the +/// working directory before the global CLI delegates a command. /// -/// The local CLI uses this marker to keep the explicit target after the global -/// CLI changes the child process directory and removes `-C` from its arguments. +/// The local CLI uses this marker to skip its own app target selection after +/// the global CLI changes the child process directory and removes `-C` from +/// its arguments. pub const VP_EXPLICIT_CHDIR: &str = "VP_EXPLICIT_CHDIR"; /// Path to the vp binary, passed to JS scripts so they can invoke CLI commands. diff --git a/packages/cli/binding/Cargo.toml b/packages/cli/binding/Cargo.toml index b7640a4641..71ad3b9d05 100644 --- a/packages/cli/binding/Cargo.toml +++ b/packages/cli/binding/Cargo.toml @@ -14,7 +14,6 @@ rolldown = ["dep:rolldown_binding"] [dependencies] anyhow = { workspace = true } async-trait = { workspace = true } -base64-simd = { workspace = true } clap = { workspace = true, features = ["derive"] } cow-utils = { workspace = true } rustc-hash = { workspace = true } @@ -26,14 +25,13 @@ serde = { workspace = true, features = ["derive"] } serde_json = { workspace = true } tokio = { workspace = true, features = ["fs"] } tracing = { workspace = true } -uuid = { workspace = true, features = ["v4"] } +vp_app_target = { workspace = true } vp_command = { workspace = true } vp_cli_help = { workspace = true } vp_error = { workspace = true } vp_migration = { workspace = true } vp_pm_cli = { workspace = true } vt_path = { workspace = true } -vt_select = { workspace = true } vp_shared = { workspace = true } vp_static_config = { workspace = true } vp_toolchain = { workspace = true } diff --git a/packages/cli/binding/index.d.cts b/packages/cli/binding/index.d.cts index 98f8aac40c..5eda8ec76d 100644 --- a/packages/cli/binding/index.d.cts +++ b/packages/cli/binding/index.d.cts @@ -3655,7 +3655,7 @@ export interface CliOptions { pack: (err: Error | null, arg: JsCommandContext) => Promise; doc: (err: Error | null, arg: JsCommandContext) => Promise; cwd?: string; - /** Whether the user supplied the global `-C` option. */ + /** Whether `-C` or the global CLI's app target selection fixed the working directory. */ explicitChdir?: boolean; /** * Return the `vp dev` command in `RunResult.devCommand` instead of diff --git a/packages/cli/binding/src/cli/handler.rs b/packages/cli/binding/src/cli/handler.rs index 4962c5f39a..244dba5e7c 100644 --- a/packages/cli/binding/src/cli/handler.rs +++ b/packages/cli/binding/src/cli/handler.rs @@ -111,7 +111,9 @@ impl CommandHandler for VitePlusCommandHandler { // target elicitation as direct invocations: spawn the real // binary, which elicits (defaultPackage note, listing + // exit 1) identically instead of silently running the root. - if super::app_target::needs_elicitation(&subcmd, &command.cwd) { + if subcmd.bare_app_command().is_some_and(|app_command| { + vp_app_target::needs_elicitation(app_command, &command.cwd) + }) { return Ok(HandledCommand::Verbatim); } let resolved = self.resolver.resolve(subcmd, &command.envs, &command.cwd).await?; diff --git a/packages/cli/binding/src/cli/mod.rs b/packages/cli/binding/src/cli/mod.rs index 1ae3398a75..cb38572e59 100644 --- a/packages/cli/binding/src/cli/mod.rs +++ b/packages/cli/binding/src/cli/mod.rs @@ -3,13 +3,11 @@ //! This module contains all the CLI-related code. //! It handles argument parsing, command dispatching, and orchestration of the task execution. -mod app_target; mod execution; mod handler; mod help; mod lifecycle_env; mod resolver; -mod script_note; mod types; use std::{borrow::Cow, env, ffi::OsStr, sync::Arc}; @@ -24,6 +22,8 @@ pub use types::{ SynthesizableSubcommand, ToolchainArgs, ViteConfigResolverFn, }; pub(crate) use types::{CapturedCommandOutput, EnvMap}; +use vp_app_target::AppTarget; +use vp_cli_help::script_note; use vp_error::Error; pub use vp_shared::init_tracing; use vp_shared::{PrependOptions, env_vars, prepend_tools_to_path_env}; @@ -51,26 +51,29 @@ async fn execute_direct_subcommand( options: Option, explicit_chdir: bool, ) -> Result { - // A bare app command at a workspace root resolves its target first - // (defaultPackage, package listing); the command then runs as if invoked - // in the resolved directory (rfcs/cwd-flag.md). - let (target, workspace_root_hint) = - app_target::resolve_app_target(&subcommand, cwd, explicit_chdir)?; - let retargeted = matches!(&target, app_target::AppTarget::Dir(_)); - let cwd = match &target { - app_target::AppTarget::Exit(status) => return Ok(Outcome::Exit(*status)), - app_target::AppTarget::Dir(dir) => dir, - app_target::AppTarget::CurrentDir => cwd, - }; - - // A lone `--` uses bare-command target selection. Restore the separator - // after selecting the target so Vite receives the original arguments. + // Vite receives a leading `--` unchanged. Restore it before target + // selection, so the selection sees the same arguments as the global CLI. if let SynthesizableSubcommand::Dev { args } | SynthesizableSubcommand::Build { args } = &mut subcommand { vp_shared::restore_leading_arg_separator(raw_args, args); } + // A bare app command at a workspace root resolves its target first + // (defaultPackage, package listing); the command then runs as if invoked + // in the resolved directory (rfcs/cwd-flag.md). An explicit `-C`, + // including a directory that the global CLI already selected, skips this. + let target = match subcommand.bare_app_command().filter(|_| !explicit_chdir) { + Some(command) => vp_app_target::resolve_app_target(command, cwd)?, + None => AppTarget::CurrentDir(None), + }; + let (cwd, workspace_root_hint, retargeted) = match target { + AppTarget::Exit(code) => return Ok(Outcome::Exit(ExitStatus(code))), + AppTarget::Dir(dir) => (dir, None, true), + AppTarget::CurrentDir(workspace_root) => (cwd.clone(), workspace_root, false), + }; + let cwd = &cwd; + // The resolver hands back the workspace root it already found whenever the // command runs in the unchanged cwd (never after a -C/elicitation // retarget), so it matches a fresh lookup here and saves the second walk. diff --git a/packages/cli/binding/src/cli/types.rs b/packages/cli/binding/src/cli/types.rs index 6520e625a4..b843f6a732 100644 --- a/packages/cli/binding/src/cli/types.rs +++ b/packages/cli/binding/src/cli/types.rs @@ -113,6 +113,21 @@ pub enum SynthesizableSubcommand { }, } +impl SynthesizableSubcommand { + /// The app command that may select a target directory, when its arguments + /// leave the selection to the CLI. + pub(super) fn bare_app_command(&self) -> Option<&'static str> { + let (command, args) = match self { + Self::Dev { args } => ("dev", args), + Self::Build { args } => ("build", args), + Self::Preview { args } => ("preview", args), + Self::Pack { args } => ("pack", args), + _ => return None, + }; + vp_app_target::is_bare_app_command(args).then_some(command) + } +} + #[derive(Debug, clap::Args)] pub struct ToolchainArgs { /// Tool or package names to show @@ -238,3 +253,30 @@ pub(crate) struct CapturedCommandOutput { pub(crate) fn exit_status_from(status: std::process::ExitStatus) -> ExitStatus { ExitStatus(vp_shared::exit_code_from_status(status) as u8) } + +#[cfg(test)] +mod tests { + use super::SynthesizableSubcommand as Subcommand; + + #[test] + fn only_app_commands_select_a_target() { + for (subcommand, expected) in [ + (Subcommand::Dev { args: vec![] }, Some("dev")), + (Subcommand::Build { args: vec!["--".into()] }, Some("build")), + (Subcommand::Preview { args: vec![] }, Some("preview")), + (Subcommand::Pack { args: vec![] }, Some("pack")), + (Subcommand::Build { args: vec!["--watch".into()] }, None), + (Subcommand::Lint { args: vec![] }, None), + (Subcommand::Test { args: vec![] }, None), + ] { + assert_eq!(subcommand.bare_app_command(), expected); + } + } + + /// The script note in `vp_cli_help` cannot depend on Vite Task, so it + /// keeps its own copy of the task marker name. + #[test] + fn script_note_uses_the_vite_task_marker() { + assert_eq!(vp_shared::env_vars::VP_RUN, vt::MARKER_ENV_NAME); + } +} diff --git a/packages/cli/binding/src/lib.rs b/packages/cli/binding/src/lib.rs index c09eea31b0..bdd5ee319f 100644 --- a/packages/cli/binding/src/lib.rs +++ b/packages/cli/binding/src/lib.rs @@ -84,7 +84,7 @@ pub struct CliOptions { pub pack: Arc>>, pub doc: Arc>>, pub cwd: Option, - /// Whether the user supplied the global `-C` option. + /// Whether `-C` or the global CLI's app target selection fixed the working directory. pub explicit_chdir: Option, /// Return the `vp dev` command in `RunResult.devCommand` instead of /// starting it, so that the launcher runs Vite in its own process. diff --git a/rfcs/cwd-flag.md b/rfcs/cwd-flag.md index 39be68db44..46e005be21 100644 --- a/rfcs/cwd-flag.md +++ b/rfcs/cwd-flag.md @@ -272,12 +272,11 @@ vp -C [args...] === cd && vp [args...] The child's spawn cwd is ``, so config lookup, `.env` loading, `process.cwd()` reads in configs and plugins, and relative CLI args all behave as if the user had `cd`'d. The POSIX `PWD` environment variable is refreshed too (by both entry points and for elicitation-retargeted tools), so `process.env.PWD` readers match the `cd` form. Both entry points apply `-C` by changing their own process cwd at startup, before any argument normalization, picker, or command logic runs, which is indistinguishable from having been started in ``: the global binary consumes the flag first thing in `main` (so command aliases, the no-command picker, and in-process helpers that read the process cwd are all covered), and the local `vp` bin does the same before dispatch. -The global binary also resolves the local `vite-plus` install from ``, matching `cd` exactly; through the package's own `vp` bin the executing CLI is already chosen, so there the invariant assumes a single Vite+ version per workspace (the supported monorepo model). The implicit `-C` forms (picker, auto-select, `defaultPackage`) run inside the already-chosen CLI under the same assumption: the spawned tool gets the target's cwd and `PWD`, but the executing CLI and its runtime were resolved at the invocation directory. Within one workspace the two coincide; a `defaultPackage` target carrying its own Vite+ install or runtime pin is resolved by the invoking CLI today (full re-delegation is tracked as follow-up work). +The global binary also resolves the local `vite-plus` install from ``, matching `cd` exactly; through the package's own `vp` bin the executing CLI is already chosen, so there the invariant assumes a single Vite+ version per workspace (the supported monorepo model). The implicit `-C` forms (picker, auto-select, `defaultPackage`) get the same resolution through the global binary. It selects the target before it chooses the local `vite-plus` install, the managed Node.js runtime, and the tool paths, and then runs the command as `vp -C ` would. Through the package's own `vp` bin, the selected tool gets the target's cwd and `PWD`, but it runs in the already-chosen CLI and runtime. ### Entry points and version assumption -- `-C` is parsed by both the global binary and the local bin; the picker and `defaultPackage` live in the local CLI's NAPI binding (`execute_direct_subcommand`), which every entry point executes. Bare `vp dev` at a root is primarily a global-CLI experience, but a root-level `"dev": "vp dev"` script flows through the same logic. -- Pre-1.0, both the global CLI and any local install are assumed to ship this feature; no version negotiation with older CLIs is specified. In the non-workspace shape the root has no local install, so the bundled CLI executes end to end, which is equivalent under this assumption. +- `-C` is parsed by both the global binary and the local bin. Both use `crates/vp_app_target` for the picker and `defaultPackage`. For a bare app command without `-C`, the global binary selects the target itself and delegates with `VP_EXPLICIT_CHDIR=1`, so the local CLI does not select again. The local CLI's NAPI binding (`execute_direct_subcommand`) selects the target when the package's own `vp` bin runs, for example from a root-level `"dev": "vp dev"` script. ### Picker contents @@ -353,7 +352,7 @@ No upstream Vite or tsdown changes are required. - `crates/vp_global_cli/src/main.rs` / `cli.rs`: parse the global `-C `, resolve the local install from ``, and delegate with `` as the effective cwd. Preserve an explicit-target marker for the local CLI. - `packages/cli/src/bin.ts`: parse `-C` for direct local invocations and pass the explicit-target marker to the binding. -- `packages/cli/binding/src/cli/app_target.rs` / `mod.rs`: apply the exact-bare command resolution order. Skip target selection when `-C` or a subcommand argument is present. +- `crates/vp_app_target`: apply the exact-bare command resolution order. The global CLI (`crates/vp_global_cli/src/commands/delegate.rs`) and the binding (`packages/cli/binding/src/cli/mod.rs`) call it, and skip target selection when `-C` or a subcommand argument is present. - `packages/cli/binding/src/cli/execution.rs`: spawn the child with cwd set to the target directory. - Picker: reuse `vt_select` and `vt_workspace`, both already dependencies via the `vt` crates. - `defaultPackage`: extend the `VitePlusConfigLoader` static extraction the same way `run` config is loaded, and add `defaultPackage?: string` to `packages/cli/src/define-config.ts`.