-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathcli.rs
More file actions
1769 lines (1588 loc) · 65.9 KB
/
cli.rs
File metadata and controls
1769 lines (1588 loc) · 65.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! CLI types and logic for vite-plus using the new Session API from vite-task.
//!
//! This module contains all the CLI-related code.
//! It handles argument parsing, command dispatching, and orchestration of the task execution.
use std::{
borrow::Cow, env, ffi::OsStr, future::Future, io::IsTerminal, iter, pin::Pin, process::Stdio,
sync::Arc, time::Instant,
};
use clap::{
Parser, Subcommand,
error::{ContextKind, ContextValue, ErrorKind},
};
use cow_utils::CowUtils;
use owo_colors::OwoColorize;
use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use vite_error::Error;
use vite_path::{AbsolutePath, AbsolutePathBuf};
use vite_shared::{PrependOptions, output, prepend_to_path_env};
use vite_str::Str;
use vite_task::{
Command, CommandHandler, ExitStatus, HandledCommand, ScriptCommand, Session, SessionConfig,
config::{
UserRunConfig,
user::{
AutoInput, EnabledCacheConfig, GlobWithBase, InputBase, UserCacheConfig, UserInputEntry,
},
},
loader::UserConfigLoader,
plan_request::SyntheticPlanRequest,
};
/// Resolved configuration from vite.config.ts
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResolvedUniversalViteConfig {
#[serde(rename = "configFile")]
pub config_file: Option<String>,
pub lint: Option<serde_json::Value>,
pub fmt: Option<serde_json::Value>,
pub run: Option<serde_json::Value>,
}
/// Result type for resolved commands from JavaScript
#[derive(Debug, Clone)]
pub struct ResolveCommandResult {
pub bin_path: Arc<OsStr>,
pub envs: Vec<(String, String)>,
}
/// Built-in subcommands that resolve to a concrete tool (oxlint, vitest, vite, etc.)
#[derive(Debug, Clone, Subcommand)]
pub enum SynthesizableSubcommand {
/// Lint code
#[command(disable_help_flag = true)]
Lint {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Format code
#[command(disable_help_flag = true)]
Fmt {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Build for production
#[command(disable_help_flag = true)]
Build {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Run tests
#[command(disable_help_flag = true)]
Test {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Build library
#[command(disable_help_flag = true)]
Pack {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Run the development server
#[command(disable_help_flag = true)]
Dev {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Preview production build
#[command(disable_help_flag = true)]
Preview {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Build documentation
#[command(disable_help_flag = true, hide = true)]
Doc {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Install command.
#[command(disable_help_flag = true, alias = "i")]
Install {
#[clap(allow_hyphen_values = true, trailing_var_arg = true)]
args: Vec<String>,
},
/// Run format, lint, and type checks
Check {
/// Auto-fix format and lint issues
#[arg(long)]
fix: bool,
/// Skip format check
#[arg(long = "no-fmt")]
no_fmt: bool,
/// Skip lint check
#[arg(long = "no-lint")]
no_lint: bool,
/// File paths to check (passed through to fmt and lint)
#[arg(trailing_var_arg = true)]
paths: Vec<String>,
},
}
/// Top-level CLI argument parser for vite-plus.
#[derive(Debug, Parser)]
#[command(name = "vp", disable_help_subcommand = true)]
enum CLIArgs {
/// vite-task commands (run, cache)
#[command(flatten)]
ViteTask(Command),
/// Built-in subcommands (lint, build, test, etc.)
#[command(flatten)]
Synthesizable(SynthesizableSubcommand),
/// Execute a command from local node_modules/.bin
Exec(crate::exec::ExecArgs),
}
/// Type alias for boxed async resolver function
/// NOTE: Uses anyhow::Error to avoid NAPI type inference issues
pub type BoxedResolverFn =
Box<dyn Fn() -> Pin<Box<dyn Future<Output = anyhow::Result<ResolveCommandResult>> + 'static>>>;
/// Type alias for vite config resolver function (takes package path, returns JSON string)
/// Uses Arc for cloning and Send + Sync for use in UserConfigLoader
pub type ViteConfigResolverFn = Arc<
dyn Fn(String) -> Pin<Box<dyn Future<Output = anyhow::Result<String>> + Send + 'static>>
+ Send
+ Sync,
>;
/// CLI options containing JavaScript resolver functions (using boxed futures for simplicity)
pub struct CliOptions {
pub lint: BoxedResolverFn,
pub fmt: BoxedResolverFn,
pub vite: BoxedResolverFn,
pub test: BoxedResolverFn,
pub pack: BoxedResolverFn,
pub doc: BoxedResolverFn,
pub resolve_universal_vite_config: ViteConfigResolverFn,
}
/// A resolved subcommand ready for execution.
struct ResolvedSubcommand {
program: Arc<OsStr>,
args: Arc<[Str]>,
cache_config: UserCacheConfig,
envs: Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
}
impl ResolvedSubcommand {
fn into_synthetic_plan_request(self) -> SyntheticPlanRequest {
SyntheticPlanRequest {
program: self.program,
args: self.args,
cache_config: self.cache_config,
envs: self.envs,
}
}
}
/// Resolves synthesizable subcommands to concrete programs and arguments.
/// Used by both direct CLI execution and CommandHandler.
pub struct SubcommandResolver {
cli_options: Option<CliOptions>,
workspace_path: Arc<AbsolutePath>,
}
impl std::fmt::Debug for SubcommandResolver {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SubcommandResolver")
.field("has_cli_options", &self.cli_options.is_some())
.field("workspace_path", &self.workspace_path)
.finish()
}
}
impl SubcommandResolver {
pub fn new(workspace_path: Arc<AbsolutePath>) -> Self {
Self { cli_options: None, workspace_path }
}
pub fn with_cli_options(mut self, cli_options: CliOptions) -> Self {
self.cli_options = Some(cli_options);
self
}
async fn resolve_universal_vite_config(&self) -> anyhow::Result<ResolvedUniversalViteConfig> {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for vite config resolution"))?;
let workspace_path_str = self
.workspace_path
.as_path()
.to_str()
.ok_or_else(|| anyhow::anyhow!("workspace path is not valid UTF-8"))?;
let vite_config_json =
(cli_options.resolve_universal_vite_config)(workspace_path_str.to_string()).await?;
Ok(serde_json::from_str(&vite_config_json).inspect_err(|_| {
tracing::error!("Failed to parse vite config: {vite_config_json}");
})?)
}
/// Resolve a synthesizable subcommand to a concrete program, args, cache config, and envs.
async fn resolve(
&self,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &Arc<AbsolutePath>,
) -> anyhow::Result<ResolvedSubcommand> {
match subcommand {
SynthesizableSubcommand::Lint { mut args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for lint command"))?;
let resolved = (cli_options.lint)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("lint JS path is not valid UTF-8"))?;
let owned_resolved_vite_config;
let resolved_vite_config = if let Some(config) = resolved_vite_config {
config
} else {
owned_resolved_vite_config = self.resolve_universal_vite_config().await?;
&owned_resolved_vite_config
};
if let (Some(_), Some(config_file)) =
(&resolved_vite_config.lint, &resolved_vite_config.config_file)
{
args.insert(0, "-c".to_string());
args.insert(1, config_file.clone());
}
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
args: iter::once(Str::from("--disable-warning=MODULE_TYPELESS_PACKAGE_JSON"))
.chain(iter::once(Str::from(js_path_str)))
.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,
}),
envs: merge_resolved_envs(envs, resolved.envs),
})
}
SynthesizableSubcommand::Fmt { mut args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for fmt command"))?;
let resolved = (cli_options.fmt)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("fmt JS path is not valid UTF-8"))?;
let owned_resolved_vite_config;
let resolved_vite_config = if let Some(config) = resolved_vite_config {
config
} else {
owned_resolved_vite_config = self.resolve_universal_vite_config().await?;
&owned_resolved_vite_config
};
if let (Some(fmt_config), Some(config_file)) =
(&resolved_vite_config.fmt, &resolved_vite_config.config_file)
{
args.insert(0, "-c".to_string());
args.insert(1, config_file.clone());
// Avoid "Expected at least one target file" error when
// ignorePatterns filters out all input files (e.g., `vp staged`
// passes only package-lock.json which is then excluded).
if fmt_config
.get("ignorePatterns")
.and_then(|v| v.as_array())
.is_some_and(|arr| !arr.is_empty())
&& !has_flag_before_terminator(&args, "--no-error-on-unmatched-pattern")
{
args.push("--no-error-on-unmatched-pattern".to_string());
}
}
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
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,
}),
envs: merge_resolved_envs(envs, resolved.envs),
})
}
SynthesizableSubcommand::Build { args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for build command"))?;
let resolved = (cli_options.vite)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("vite JS path is not valid UTF-8"))?;
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
args: iter::once(Str::from(js_path_str))
.chain(iter::once(Str::from("build")))
.chain(args.into_iter().map(Str::from))
.collect(),
cache_config: UserCacheConfig::with_config(EnabledCacheConfig {
env: Some(Box::new([Str::from("VITE_*")])),
untracked_env: None,
input: Some(build_pack_cache_inputs()),
}),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Test { args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for test command"))?;
let resolved = (cli_options.test)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("test JS path is not valid UTF-8"))?;
let prepend_run = should_prepend_vitest_run(&args);
let vitest_args: Vec<Str> = if prepend_run {
iter::once(Str::from("run")).chain(args.into_iter().map(Str::from)).collect()
} else {
args.into_iter().map(Str::from).collect()
};
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
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(AutoInput { auto: true }),
exclude_glob("!node_modules/.vite-temp/**", InputBase::Package),
exclude_glob(
"!node_modules/.vite/vitest/**/results.json",
InputBase::Package,
),
]),
}),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Pack { args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for pack command"))?;
let resolved = (cli_options.pack)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("pack JS path is not valid UTF-8"))?;
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
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()),
}),
envs: merge_resolved_envs(envs, resolved.envs),
})
}
SynthesizableSubcommand::Dev { args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for dev command"))?;
let resolved = (cli_options.vite)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("vite JS path is not valid UTF-8"))?;
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
args: iter::once(Str::from(js_path_str))
.chain(iter::once(Str::from("dev")))
.chain(args.into_iter().map(Str::from))
.collect(),
cache_config: UserCacheConfig::disabled(),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Preview { args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for preview command"))?;
let resolved = (cli_options.vite)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("vite JS path is not valid UTF-8"))?;
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
args: iter::once(Str::from(js_path_str))
.chain(iter::once(Str::from("preview")))
.chain(args.into_iter().map(Str::from))
.collect(),
cache_config: UserCacheConfig::disabled(),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Doc { args } => {
let cli_options = self
.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options required for doc command"))?;
let resolved = (cli_options.doc)().await?;
let js_path = resolved.bin_path;
let js_path_str = js_path
.to_str()
.ok_or_else(|| anyhow::anyhow!("doc JS path is not valid UTF-8"))?;
Ok(ResolvedSubcommand {
program: Arc::from(OsStr::new("node")),
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,
}),
envs: merge_resolved_envs(envs, resolved.envs),
})
}
SynthesizableSubcommand::Check { .. } => {
anyhow::bail!(
"Check is a composite command and cannot be resolved to a single subcommand"
);
}
SynthesizableSubcommand::Install { args } => {
let package_manager =
vite_install::PackageManager::builder(cwd).build_with_default().await?;
let resolve_command = package_manager.resolve_install_command(&args);
let merged_envs = {
let mut env_map = FxHashMap::clone(envs);
for (k, v) in resolve_command.envs {
env_map.insert(Arc::from(OsStr::new(&k)), Arc::from(OsStr::new(&v)));
}
Arc::new(env_map)
};
Ok(ResolvedSubcommand {
program: Arc::<OsStr>::from(
OsStr::new(&resolve_command.bin_path).to_os_string(),
),
args: resolve_command.args.into_iter().map(Str::from).collect(),
cache_config: UserCacheConfig::with_config(EnabledCacheConfig {
env: None,
untracked_env: None,
input: None,
}),
envs: merged_envs,
})
}
}
}
}
/// Merge resolved environment variables from JS resolver into existing envs.
/// Does not override existing entries.
/// Create a negative glob entry to exclude a pattern from cache fingerprinting.
fn exclude_glob(pattern: &str, base: InputBase) -> UserInputEntry {
UserInputEntry::GlobWithBase(GlobWithBase { pattern: Str::from(pattern), base })
}
/// Common cache input entries for build/pack commands.
/// Excludes .vite-temp config files and dist output files that are both read and written.
/// TODO: The hardcoded `!dist/**` exclusion is a temporary workaround. It will be replaced
/// by a runner-aware approach that automatically excludes task output directories.
fn build_pack_cache_inputs() -> Vec<UserInputEntry> {
vec![
UserInputEntry::Auto(AutoInput { auto: true }),
exclude_glob("!node_modules/.vite-temp/**", InputBase::Workspace),
exclude_glob("!node_modules/.vite-temp/**", InputBase::Package),
exclude_glob("!dist/**", InputBase::Package),
]
}
fn merge_resolved_envs(
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
resolved_envs: Vec<(String, String)>,
) -> Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>> {
let mut envs = FxHashMap::clone(envs);
for (k, v) in resolved_envs {
envs.entry(Arc::from(OsStr::new(&k))).or_insert_with(|| Arc::from(OsStr::new(&v)));
}
Arc::new(envs)
}
/// Merge resolved envs and inject VP_VERSION for rolldown-vite branding.
fn merge_resolved_envs_with_version(
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
resolved_envs: Vec<(String, String)>,
) -> Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>> {
let mut merged = merge_resolved_envs(envs, resolved_envs);
let map = Arc::make_mut(&mut merged);
map.entry(Arc::from(OsStr::new("VP_VERSION")))
.or_insert_with(|| Arc::from(OsStr::new(env!("CARGO_PKG_VERSION"))));
merged
}
/// CommandHandler implementation for vite-plus.
/// Handles `vp` commands in task scripts.
pub struct VitePlusCommandHandler {
resolver: SubcommandResolver,
}
impl std::fmt::Debug for VitePlusCommandHandler {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VitePlusCommandHandler").finish()
}
}
impl VitePlusCommandHandler {
pub fn new(resolver: SubcommandResolver) -> Self {
Self { resolver }
}
}
#[async_trait::async_trait(?Send)]
impl CommandHandler for VitePlusCommandHandler {
async fn handle_command(
&mut self,
command: &mut ScriptCommand,
) -> anyhow::Result<HandledCommand> {
// Intercept "vp" and "vpr" commands in task scripts so that `vp test`, `vp build`,
// `vpr build`, etc. are synthesized in-session rather than spawning a new CLI process.
let program = command.program.as_str();
if program != "vp" && program != "vpr" {
return Ok(HandledCommand::Verbatim);
}
// "vpr <args>" is shorthand for "vp run <args>", so prepend "run" for parsing.
let is_vpr = program == "vpr";
let cli_args = match CLIArgs::try_parse_from(
iter::once("vp")
.chain(is_vpr.then_some("run"))
.chain(command.args.iter().map(Str::as_str)),
) {
Ok(args) => args,
Err(err) if err.kind() == ErrorKind::InvalidSubcommand => {
return Ok(HandledCommand::Synthesized(
command.to_synthetic_plan_request(UserCacheConfig::disabled()),
));
}
Err(err) => return Err(err.into()),
};
match cli_args {
CLIArgs::Synthesizable(SynthesizableSubcommand::Check { .. }) => {
// Check is a composite command — run as a subprocess in task scripts
Ok(HandledCommand::Synthesized(
command.to_synthetic_plan_request(UserCacheConfig::disabled()),
))
}
CLIArgs::Synthesizable(subcmd) => {
let resolved =
self.resolver.resolve(subcmd, None, &command.envs, &command.cwd).await?;
Ok(HandledCommand::Synthesized(resolved.into_synthetic_plan_request()))
}
CLIArgs::ViteTask(cmd) => Ok(HandledCommand::ViteTaskCommand(cmd)),
CLIArgs::Exec(_) => {
// exec in task scripts should run as a subprocess
Ok(HandledCommand::Synthesized(
command.to_synthetic_plan_request(UserCacheConfig::disabled()),
))
}
}
}
}
/// User config loader that resolves vite.config.ts via JavaScript callback
pub struct VitePlusConfigLoader {
resolve_fn: ViteConfigResolverFn,
}
impl VitePlusConfigLoader {
pub fn new(resolve_fn: ViteConfigResolverFn) -> Self {
Self { resolve_fn }
}
}
impl std::fmt::Debug for VitePlusConfigLoader {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VitePlusConfigLoader").finish()
}
}
#[async_trait::async_trait(?Send)]
impl UserConfigLoader for VitePlusConfigLoader {
async fn load_user_config_file(
&self,
package_path: &AbsolutePath,
) -> anyhow::Result<Option<UserRunConfig>> {
// Try static config extraction first (no JS runtime needed)
let static_fields = vite_static_config::resolve_static_config(package_path);
match static_fields.get("run") {
Some(vite_static_config::FieldValue::Json(run_value)) => {
tracing::debug!(
"Using statically extracted run config for {}",
package_path.as_path().display()
);
let run_config: UserRunConfig = serde_json::from_value(run_value)?;
return Ok(Some(run_config));
}
Some(vite_static_config::FieldValue::NonStatic) => {
// `run` field exists (or may exist via a spread) — fall back to NAPI
tracing::debug!(
"run config is not statically analyzable for {}, falling back to NAPI",
package_path.as_path().display()
);
}
None => {
// Config was analyzed successfully and `run` field is definitively absent
return Ok(None);
}
}
// Fall back to NAPI-based config resolution
let package_path_str = package_path
.as_path()
.to_str()
.ok_or_else(|| anyhow::anyhow!("package path is not valid UTF-8"))?;
let config_json = (self.resolve_fn)(package_path_str.to_string()).await?;
let resolved: ResolvedUniversalViteConfig = serde_json::from_str(&config_json)
.inspect_err(|_| {
tracing::error!("Failed to parse vite config: {config_json}");
})?;
let run_config = match resolved.run {
Some(run) => serde_json::from_value(run)?,
None => UserRunConfig::default(),
};
Ok(Some(run_config))
}
}
/// Resolve a subcommand into a prepared `tokio::process::Command`.
async fn resolve_and_build_command(
resolver: &SubcommandResolver,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePathBuf,
cwd_arc: &Arc<AbsolutePath>,
) -> Result<tokio::process::Command, Error> {
let resolved = resolver
.resolve(subcommand, resolved_vite_config, envs, cwd_arc)
.await
.map_err(|e| Error::Anyhow(e))?;
// Resolve the program path using `which` to handle Windows .cmd/.bat files (PATHEXT)
let program_path = {
let paths = resolved.envs.iter().find_map(|(k, v)| {
let is_path = if cfg!(windows) {
k.as_ref().eq_ignore_ascii_case("PATH")
} else {
k.as_ref() == "PATH"
};
if is_path { Some(v.as_ref().to_os_string()) } else { None }
});
vite_command::resolve_bin(
resolved.program.as_ref().to_str().unwrap_or_default(),
paths.as_deref(),
cwd,
)?
};
let mut cmd = vite_command::build_command(&program_path, cwd);
cmd.args(resolved.args.iter().map(|s| s.as_str()))
.env_clear()
.envs(resolved.envs.iter().map(|(k, v)| (k.as_ref(), v.as_ref())));
Ok(cmd)
}
/// Resolve a single subcommand and execute it, returning its exit status.
async fn resolve_and_execute(
resolver: &SubcommandResolver,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePathBuf,
cwd_arc: &Arc<AbsolutePath>,
) -> Result<ExitStatus, Error> {
let mut cmd =
resolve_and_build_command(resolver, subcommand, resolved_vite_config, envs, cwd, cwd_arc)
.await?;
let mut child = cmd.spawn().map_err(|e| Error::Anyhow(e.into()))?;
let status = child.wait().await.map_err(|e| Error::Anyhow(e.into()))?;
Ok(ExitStatus(status.code().unwrap_or(1) as u8))
}
/// Like `resolve_and_execute`, but captures stdout, applies a text filter,
/// and writes the result to real stdout. Stderr remains inherited.
async fn resolve_and_execute_with_stdout_filter(
resolver: &SubcommandResolver,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePathBuf,
cwd_arc: &Arc<AbsolutePath>,
filter: impl Fn(&str) -> Cow<'_, str>,
) -> Result<ExitStatus, Error> {
let mut cmd =
resolve_and_build_command(resolver, subcommand, resolved_vite_config, envs, cwd, cwd_arc)
.await?;
cmd.stdout(Stdio::piped());
let child = cmd.spawn().map_err(|e| Error::Anyhow(e.into()))?;
let output = child.wait_with_output().await.map_err(|e| Error::Anyhow(e.into()))?;
use std::io::Write;
let stdout = String::from_utf8_lossy(&output.stdout);
let filtered = filter(&stdout);
let _ = std::io::stdout().lock().write_all(filtered.as_bytes());
Ok(ExitStatus(output.status.code().unwrap_or(1) as u8))
}
/// Like `resolve_and_execute`, but captures stderr, applies a text filter,
/// and writes the result to real stderr. Stdout remains inherited (streaming).
async fn resolve_and_execute_with_stderr_filter(
resolver: &SubcommandResolver,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePathBuf,
cwd_arc: &Arc<AbsolutePath>,
filter: impl Fn(&str) -> Cow<'_, str>,
) -> Result<ExitStatus, Error> {
let mut cmd =
resolve_and_build_command(resolver, subcommand, resolved_vite_config, envs, cwd, cwd_arc)
.await?;
cmd.stderr(Stdio::piped());
let child = cmd.spawn().map_err(|e| Error::Anyhow(e.into()))?;
let output = child.wait_with_output().await.map_err(|e| Error::Anyhow(e.into()))?;
use std::io::Write;
let stderr = String::from_utf8_lossy(&output.stderr);
let filtered = filter(&stderr);
let _ = std::io::stderr().lock().write_all(filtered.as_bytes());
Ok(ExitStatus(output.status.code().unwrap_or(1) as u8))
}
struct CapturedCommandOutput {
status: ExitStatus,
stdout: String,
stderr: String,
}
async fn resolve_and_capture_output(
resolver: &SubcommandResolver,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
cwd: &AbsolutePathBuf,
cwd_arc: &Arc<AbsolutePath>,
force_color_if_terminal: bool,
) -> Result<CapturedCommandOutput, Error> {
let mut cmd =
resolve_and_build_command(resolver, subcommand, resolved_vite_config, envs, cwd, cwd_arc)
.await?;
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
if force_color_if_terminal && std::io::stdout().is_terminal() {
cmd.env("FORCE_COLOR", "1");
}
let child = cmd.spawn().map_err(|e| Error::Anyhow(e.into()))?;
let output = child.wait_with_output().await.map_err(|e| Error::Anyhow(e.into()))?;
Ok(CapturedCommandOutput {
status: ExitStatus(output.status.code().unwrap_or(1) as u8),
stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
})
}
#[derive(Debug, Clone)]
struct CheckSummary {
duration: String,
files: usize,
threads: usize,
}
#[derive(Debug)]
struct FmtSuccess {
summary: CheckSummary,
}
#[derive(Debug)]
struct FmtFailure {
summary: CheckSummary,
issue_files: Vec<String>,
issue_count: usize,
}
#[derive(Debug)]
struct LintSuccess {
summary: CheckSummary,
}
#[derive(Debug)]
struct LintFailure {
summary: CheckSummary,
warnings: usize,
errors: usize,
diagnostics: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum LintMessageKind {
LintOnly,
LintAndTypeCheck,
}
impl LintMessageKind {
fn from_lint_config(lint_config: Option<&serde_json::Value>) -> Self {
let type_check_enabled = lint_config
.and_then(|config| config.get("options"))
.and_then(|options| options.get("typeCheck"))
.and_then(serde_json::Value::as_bool)
.unwrap_or(false);
if type_check_enabled { Self::LintAndTypeCheck } else { Self::LintOnly }
}
fn success_label(self) -> &'static str {
match self {
Self::LintOnly => "Found no warnings or lint errors",
Self::LintAndTypeCheck => "Found no warnings, lint errors, or type errors",
}
}
fn warning_heading(self) -> &'static str {
match self {
Self::LintOnly => "Lint warnings found",
Self::LintAndTypeCheck => "Lint or type warnings found",
}
}
fn issue_heading(self) -> &'static str {
match self {
Self::LintOnly => "Lint issues found",
Self::LintAndTypeCheck => "Lint or type issues found",
}
}
}
fn parse_check_summary(line: &str) -> Option<CheckSummary> {
let rest = line.strip_prefix("Finished in ")?;
let (duration, rest) = rest.split_once(" on ")?;
let files = rest.split_once(" file")?.0.parse().ok()?;
let (_, threads_part) = rest.rsplit_once(" using ")?;
let threads = threads_part.split_once(" thread")?.0.parse().ok()?;
Some(CheckSummary { duration: duration.to_string(), files, threads })
}
fn parse_issue_count(line: &str, prefix: &str) -> Option<usize> {
let rest = line.strip_prefix(prefix)?;
rest.split_once(" file")?.0.parse().ok()
}
fn parse_warning_error_counts(line: &str) -> Option<(usize, usize)> {
let rest = line.strip_prefix("Found ")?;
let (warnings, rest) = rest.split_once(" warning")?;
let (_, rest) = rest.split_once(" and ")?;
let errors = rest.split_once(" error")?.0;
Some((warnings.parse().ok()?, errors.parse().ok()?))
}
fn format_elapsed(elapsed: std::time::Duration) -> String {
if elapsed.as_millis() < 1000 {
format!("{}ms", elapsed.as_millis())
} else {
format!("{:.1}s", elapsed.as_secs_f64())
}
}
fn format_count(count: usize, singular: &str, plural: &str) -> String {
if count == 1 { format!("1 {singular}") } else { format!("{count} {plural}") }
}
fn print_stdout_block(block: &str) {
let trimmed = block.trim_matches('\n');
if trimmed.is_empty() {
return;
}
use std::io::Write;
let mut stdout = std::io::stdout().lock();
let _ = stdout.write_all(trimmed.as_bytes());
let _ = stdout.write_all(b"\n");
}
fn print_summary_line(message: &str) {
output::raw("");
if std::io::stdout().is_terminal() && message.contains('`') {
let mut formatted = String::with_capacity(message.len());
let mut segments = message.split('`');
if let Some(first) = segments.next() {
formatted.push_str(first);
}
let mut is_accent = true;
for segment in segments {
if is_accent {
formatted.push_str(&format!("{}", format!("`{segment}`").bright_blue()));
} else {
formatted.push_str(segment);
}
is_accent = !is_accent;
}
output::raw(&formatted);
} else {
output::raw(message);
}
}
fn print_error_block(error_msg: &str, combined_output: &str, summary_msg: &str) {
output::error(error_msg);
if !combined_output.trim().is_empty() {
print_stdout_block(combined_output);
}
print_summary_line(summary_msg);
}
fn print_pass_line(message: &str, detail: Option<&str>) {
if let Some(detail) = detail {
output::raw(&format!("{} {message} {}", "pass:".bright_blue().bold(), detail.dimmed()));
} else {
output::pass(message);
}
}
fn analyze_fmt_check_output(output: &str) -> Option<Result<FmtSuccess, FmtFailure>> {
let trimmed = output.trim();
if trimmed.is_empty() {
return None;
}
let lines: Vec<&str> = trimmed.lines().collect();
let finish_line = lines.iter().rev().find(|line| line.starts_with("Finished in "))?;
let summary = parse_check_summary(finish_line)?;
if lines.iter().any(|line| *line == "All matched files use the correct format.") {