From 5b6a7912946577ca7a054282e03ca5e9433234bf Mon Sep 17 00:00:00 2001 From: BillW Gong <226689574+BillWGong@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:33:15 +0800 Subject: [PATCH] fix(cli): keep subcommand cache config for -C in task scripts A leading -C returned Verbatim from the script handler, so `vp -C check` and `vp -C lint` in a cached task never attached their tracked env vars. Keep the original command for the child, but synthesize it with the cache config the subcommand would use. --- packages/cli/binding/src/cli/handler.rs | 173 ++++++++++++++++++++--- packages/cli/binding/src/cli/resolver.rs | 118 ++++++++-------- 2 files changed, 214 insertions(+), 77 deletions(-) diff --git a/packages/cli/binding/src/cli/handler.rs b/packages/cli/binding/src/cli/handler.rs index 9f37c0a67b..872353990f 100644 --- a/packages/cli/binding/src/cli/handler.rs +++ b/packages/cli/binding/src/cli/handler.rs @@ -3,14 +3,14 @@ use std::iter; use clap::{Parser, error::ErrorKind}; use vt::{ CommandHandler, HandledCommand, ScriptCommand, - config::user::{EnabledCacheConfig, UserCacheConfig, UserRunConfig}, + config::user::{UserCacheConfig, UserRunConfig}, loader::UserConfigLoader, }; use vt_path::AbsolutePath; use vt_str::Str; use super::{ - resolver::{SubcommandResolver, check_cache_inputs, resolve_vite_config_fields}, + resolver::{SubcommandResolver, cache_config_for, resolve_vite_config_fields}, types::{CLIArgs, SynthesizableSubcommand, ViteConfigResolverFn}, }; @@ -57,14 +57,20 @@ impl CommandHandler for VitePlusCommandHandler { return Ok(HandledCommand::Verbatim); } - // A leading global `-C` runs verbatim: CLIArgs has no global flags, and - // the spawned vp/vpr binary applies the directory change (and target - // elicitation) exactly like a direct invocation. - if command.args.first().is_some_and(|arg| arg.starts_with("-C")) { - return Ok(HandledCommand::Verbatim); - } // "vpr " is shorthand for "vp run ", so prepend "run" for parsing. let is_vpr = program == "vpr"; + // A leading global `-C` keeps the child process (it applies the chdir + // and reports bad targets), but the command must still carry its + // subcommand's cache config. Verbatim skipped it, so `vp -C + // check` in a cached task never fingerprinted OXLINT_TSGOLINT_PATH. + if command.args.first().is_some_and(|arg| arg.starts_with("-C")) { + let Some(cache_config) = chdir_cache_config(command, is_vpr) else { + return Ok(HandledCommand::Verbatim); + }; + return Ok(HandledCommand::Synthesized( + command.to_synthetic_plan_request(cache_config), + )); + } let cli_args = match CLIArgs::try_parse_from( iter::once("vp") .chain(is_vpr.then_some("run")) @@ -79,20 +85,11 @@ impl CommandHandler for VitePlusCommandHandler { Err(err) => return Err(err.into()), }; match cli_args { - CLIArgs::Synthesizable(SynthesizableSubcommand::Check { .. }) => { + CLIArgs::Synthesizable(subcmd @ SynthesizableSubcommand::Check { .. }) => { // Check is a composite command (fmt + lint) — run as a subprocess in task scripts - Ok(HandledCommand::Synthesized(command.to_synthetic_plan_request( - UserCacheConfig::with_config(EnabledCacheConfig { - env: Some(Box::new([ - Str::from("OXLINT_TSGOLINT_PATH"), - Str::from(vp_shared::env_vars::VP_SKIP_STATIC_CONFIG), - ])), - untracked_env: None, - input: Some(check_cache_inputs()), - output: None, - remote: None, - }), - ))) + Ok(HandledCommand::Synthesized( + command.to_synthetic_plan_request(cache_config_for(&subcmd)), + )) } CLIArgs::Synthesizable(subcmd) => { // Bare app commands in scripts get the same workspace-root @@ -117,6 +114,41 @@ impl CommandHandler for VitePlusCommandHandler { } } +/// Index of the first argument after a leading global `-C ` / +/// `-C` / `-C=`, matching the global CLI grammar. Returns `None` for +/// a malformed flag or a missing target directory so the caller can fall back +/// to the verbatim child process, which reports the error itself. +fn leading_chdir_end(command: &ScriptCommand) -> Option { + let first = command.args.first().map(Str::as_str)?; + let inline = first.strip_prefix("-C")?; + let (dir, consumed) = if inline.is_empty() { + (command.args.get(1).map(Str::as_str)?, 2) + } else { + (inline.strip_prefix('=').unwrap_or(inline), 1) + }; + if dir.is_empty() || !command.cwd.join(dir).as_path().is_dir() { + return None; + } + Some(consumed) +} + +/// Cache config for the subcommand behind a leading `-C`. The command itself +/// stays untouched: the child still applies the chdir, and a malformed target +/// keeps the old verbatim fallback. +fn chdir_cache_config(command: &ScriptCommand, is_vpr: bool) -> Option { + let consumed = leading_chdir_end(command)?; + let cli_args = CLIArgs::try_parse_from( + iter::once("vp") + .chain(is_vpr.then_some("run")) + .chain(command.args[consumed..].iter().map(Str::as_str)), + ) + .ok()?; + match cli_args { + CLIArgs::Synthesizable(subcmd) => Some(cache_config_for(&subcmd)), + _ => None, + } +} + /// Vite Task rewrites workspace `.bin` shims. Managed package managers live /// outside the workspace, so apply Vite+'s launcher policy before the plan is /// fingerprinted. This also preserves the normal non-TTY and missing-.ps1 @@ -172,3 +204,102 @@ impl UserConfigLoader for VitePlusConfigLoader { Ok(config.run.map(serde_json::from_value).transpose()?) } } + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use vt::{CommandHandler, HandledCommand, ScriptCommand, config::user::UserCacheConfig}; + use vt_path::AbsolutePathBuf; + use vt_str::Str; + + use super::{SubcommandResolver, leading_chdir_end}; + + fn command(args: &[&str], cwd: &AbsolutePathBuf) -> ScriptCommand { + ScriptCommand { + program: Str::from("vp"), + args: args.iter().map(|arg| Str::from(*arg)).collect::>().into(), + envs: Arc::new(Default::default()), + cwd: Arc::from(cwd.clone()), + } + } + + fn cache_env(command: &ScriptCommand) -> Vec { + let UserCacheConfig::Config(config) = + super::chdir_cache_config(command, false).expect("expected cache config") + else { + panic!("expected enabled cache config"); + }; + config + .env + .expect("expected tracked env vars") + .iter() + .map(|name| name.as_str().to_owned()) + .collect() + } + + #[test] + fn finds_all_leading_chdir_forms() { + let cwd = AbsolutePathBuf::new(std::env::current_dir().unwrap()).unwrap(); + + for (args, expected) in [ + (&["-C", ".", "check", "index.js"][..], 2), + (&["-C.", "check", "index.js"][..], 1), + (&["-C=.", "check", "index.js"][..], 1), + ] { + assert_eq!(leading_chdir_end(&command(args, &cwd)), Some(expected)); + } + } + + #[test] + fn malformed_chdir_falls_back_to_verbatim() { + let cwd = AbsolutePathBuf::new(std::env::current_dir().unwrap()).unwrap(); + + for args in [&["-C"][..], &["-C", ""][..], &["-C", "definitely-missing-dir"][..]] { + assert_eq!(leading_chdir_end(&command(args, &cwd)), None); + assert!(super::chdir_cache_config(&command(args, &cwd), false).is_none()); + } + } + + #[test] + fn chdir_carries_subcommand_cache_config() { + let cwd = AbsolutePathBuf::new(std::env::current_dir().unwrap()).unwrap(); + + assert_eq!( + cache_env(&command(&["-C", ".", "check", "index.js"], &cwd)), + ["OXLINT_TSGOLINT_PATH", "VP_SKIP_STATIC_CONFIG"] + ); + assert_eq!( + cache_env(&command(&["-C", ".", "lint", "--type-aware"], &cwd)), + ["OXLINT_TSGOLINT_PATH"] + ); + } + + #[tokio::test] + async fn chdir_keeps_the_original_command() { + let cwd = AbsolutePathBuf::new(std::env::current_dir().unwrap()).unwrap(); + let resolver = SubcommandResolver::new(Arc::from(cwd.clone())); + let mut handler = super::VitePlusCommandHandler::new(resolver); + let mut command = command(&["-C", ".", "check", "index.js"], &cwd); + + let HandledCommand::Synthesized(request) = + handler.handle_command(&mut command).await.unwrap() + else { + panic!("expected check to be synthesized"); + }; + let UserCacheConfig::Config(config) = request.cache_config else { + panic!("expected check cache config"); + }; + assert!( + config + .env + .expect("check should track env vars") + .iter() + .any(|name| { name.as_str() == "OXLINT_TSGOLINT_PATH" }) + ); + assert_eq!( + request.args.iter().map(Str::as_str).collect::>(), + ["-C", ".", "check", "index.js"] + ); + } +} diff --git a/packages/cli/binding/src/cli/resolver.rs b/packages/cli/binding/src/cli/resolver.rs index f2c5c4b656..d13d3f2f0e 100644 --- a/packages/cli/binding/src/cli/resolver.rs +++ b/packages/cli/binding/src/cli/resolver.rs @@ -68,6 +68,7 @@ impl SubcommandResolver { envs: &Arc, cwd: &AbsolutePath, ) -> anyhow::Result { + let cache_config = cache_config_for(&subcommand); match subcommand { SynthesizableSubcommand::Lint { args } => { let cli_options = self.cli_options()?; @@ -86,13 +87,7 @@ impl SubcommandResolver { .into_iter() .chain(args.into_iter().map(Str::from)) .collect(), - cache_config: UserCacheConfig::with_config(EnabledCacheConfig { - env: Some(Box::new([Str::from("OXLINT_TSGOLINT_PATH")])), - untracked_env: None, - input: None, - output: None, - remote: None, - }), + cache_config, envs: merge_resolved_envs_with_version(envs, resolved.envs), }) } @@ -109,13 +104,7 @@ impl SubcommandResolver { args: iter::once(Str::from(js_path_str)) .chain(args.into_iter().map(Str::from)) .collect(), - cache_config: UserCacheConfig::with_config(EnabledCacheConfig { - env: None, - untracked_env: None, - input: None, - output: None, - remote: None, - }), + cache_config, envs: merge_resolved_envs_with_version(envs, resolved.envs), }) } @@ -133,19 +122,7 @@ impl SubcommandResolver { .chain(iter::once(Str::from("build"))) .chain(args.into_iter().map(Str::from)) .collect(), - // No synthetic cache config: vite reports its inputs/outputs/ - // envs to the runner via `@voidzero-dev/vite-task-client`. - // All fields `None` keep caching enabled with auto input and - // auto output inference (the latter drives output restoration); - // vite's `ignoreInput`/`ignoreOutput`/`getEnv`/`getEnvs` refine - // the fingerprint at runtime. - cache_config: UserCacheConfig::with_config(EnabledCacheConfig { - env: None, - untracked_env: None, - input: None, - output: None, - remote: None, - }), + cache_config, envs: merge_resolved_envs_with_version(envs, resolved.envs), }) } @@ -166,19 +143,7 @@ impl SubcommandResolver { Ok(ResolvedSubcommand { program: Arc::clone(&cli_options.node_exec_path), args: iter::once(Str::from(js_path_str)).chain(vitest_args).collect(), - cache_config: UserCacheConfig::with_config(EnabledCacheConfig { - env: None, - untracked_env: None, - input: Some(vec![ - UserInputEntry::Auto(AutoTracking { auto: true }), - exclude_glob( - "!node_modules/.vite/vitest/**/results.json", - InputBase::Package, - ), - ]), - output: None, - remote: None, - }), + cache_config, envs: merge_resolved_envs_with_version(envs, resolved.envs), }) } @@ -195,13 +160,7 @@ impl SubcommandResolver { args: iter::once(Str::from(js_path_str)) .chain(args.into_iter().map(Str::from)) .collect(), - cache_config: UserCacheConfig::with_config(EnabledCacheConfig { - env: None, - untracked_env: None, - input: Some(build_pack_cache_inputs()), - output: None, - remote: None, - }), + cache_config, envs: merge_resolved_envs(envs, resolved.envs), }) } @@ -219,7 +178,7 @@ impl SubcommandResolver { .chain(iter::once(Str::from("dev"))) .chain(args.into_iter().map(Str::from)) .collect(), - cache_config: UserCacheConfig::disabled(), + cache_config, envs: merge_resolved_envs_with_version(envs, resolved.envs), }) } @@ -237,7 +196,7 @@ impl SubcommandResolver { .chain(iter::once(Str::from("preview"))) .chain(args.into_iter().map(Str::from)) .collect(), - cache_config: UserCacheConfig::disabled(), + cache_config, envs: merge_resolved_envs_with_version(envs, resolved.envs), }) } @@ -254,13 +213,7 @@ impl SubcommandResolver { args: iter::once(Str::from(js_path_str)) .chain(args.into_iter().map(Str::from)) .collect(), - cache_config: UserCacheConfig::with_config(EnabledCacheConfig { - env: None, - untracked_env: None, - input: None, - output: None, - remote: None, - }), + cache_config, envs: merge_resolved_envs(envs, resolved.envs), }) } @@ -273,6 +226,59 @@ impl SubcommandResolver { } } +/// Cache metadata for a synthesizable subcommand. Separate from [`resolve`] so +/// callers that must preserve the original invocation (a leading `-C`) can +/// still attach the settings `resolve` would have produced. +pub(super) fn cache_config_for(subcommand: &SynthesizableSubcommand) -> UserCacheConfig { + match subcommand { + SynthesizableSubcommand::Check { .. } => UserCacheConfig::with_config(EnabledCacheConfig { + env: Some(Box::new([ + Str::from("OXLINT_TSGOLINT_PATH"), + Str::from(vp_shared::env_vars::VP_SKIP_STATIC_CONFIG), + ])), + untracked_env: None, + input: Some(check_cache_inputs()), + output: None, + remote: None, + }), + SynthesizableSubcommand::Lint { .. } => UserCacheConfig::with_config(EnabledCacheConfig { + env: Some(Box::new([Str::from("OXLINT_TSGOLINT_PATH")])), + untracked_env: None, + input: None, + output: None, + remote: None, + }), + SynthesizableSubcommand::Test { .. } => UserCacheConfig::with_config(EnabledCacheConfig { + env: None, + untracked_env: None, + input: Some(vec![ + UserInputEntry::Auto(AutoTracking { auto: true }), + exclude_glob("!node_modules/.vite/vitest/**/results.json", InputBase::Package), + ]), + output: None, + remote: None, + }), + SynthesizableSubcommand::Pack { .. } => UserCacheConfig::with_config(EnabledCacheConfig { + env: None, + untracked_env: None, + input: Some(build_pack_cache_inputs()), + output: None, + remote: None, + }), + SynthesizableSubcommand::Dev { .. } | SynthesizableSubcommand::Preview { .. } => { + UserCacheConfig::disabled() + } + // All-`None` keeps caching enabled with auto input/output inference. + // Build's vite process refines the fingerprint at runtime through + // `@voidzero-dev/vite-task-client` (`ignoreInput`/`getEnv`/...). + SynthesizableSubcommand::Fmt { .. } + | SynthesizableSubcommand::Build { .. } + | SynthesizableSubcommand::Doc { .. } => { + UserCacheConfig::with_config(EnabledCacheConfig::default()) + } + } +} + /// Resolve `fields` of the Vite config in `dir`. Static extraction answers when /// it accounts for every field, and `resolve_fn` loads the config through Vite /// otherwise or when `VP_SKIP_STATIC_CONFIG=1`. Fields not listed may be absent