-
Notifications
You must be signed in to change notification settings - Fork 223
Expand file tree
/
Copy pathresolver.rs
More file actions
365 lines (339 loc) · 16.2 KB
/
Copy pathresolver.rs
File metadata and controls
365 lines (339 loc) · 16.2 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
use std::{env, ffi::OsStr, iter, sync::Arc};
use rustc_hash::FxHashMap;
use vite_path::AbsolutePath;
use vite_str::Str;
use vite_task::config::user::{
AutoInput, EnabledCacheConfig, GlobWithBase, InputBase, UserCacheConfig, UserInputEntry,
};
use super::{
help::should_prepend_vitest_run,
types::{CliOptions, ResolvedSubcommand, ResolvedUniversalViteConfig, SynthesizableSubcommand},
};
/// 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
}
fn cli_options(&self) -> anyhow::Result<&CliOptions> {
self.cli_options
.as_ref()
.ok_or_else(|| anyhow::anyhow!("CLI options not available (running without NAPI?)"))
}
pub(crate) async fn resolve_universal_vite_config(
&self,
) -> anyhow::Result<ResolvedUniversalViteConfig> {
let cli_options = self.cli_options()?;
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.
pub(super) async fn resolve(
&self,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
) -> anyhow::Result<ResolvedSubcommand> {
let command_name = subcommand.command_name();
let mut resolved = self.resolve_inner(subcommand, resolved_vite_config, envs).await?;
// Inject VP_COMMAND so that defineConfig's plugin factory knows which command is running,
// even when the subcommand is synthesized inside `vp run`.
let envs = Arc::make_mut(&mut resolved.envs);
envs.insert(Arc::from(OsStr::new("VP_COMMAND")), Arc::from(OsStr::new(command_name)));
Ok(resolved)
}
async fn resolve_inner(
&self,
subcommand: SynthesizableSubcommand,
resolved_vite_config: Option<&ResolvedUniversalViteConfig>,
envs: &Arc<FxHashMap<Arc<OsStr>, Arc<OsStr>>>,
) -> anyhow::Result<ResolvedSubcommand> {
match subcommand {
SynthesizableSubcommand::Lint { mut args } => {
let cli_options = self.cli_options()?;
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,
output: None,
}),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Fmt { mut args } => {
let cli_options = self.cli_options()?;
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(_), Some(config_file)) =
(&resolved_vite_config.fmt, &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(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,
}),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Build { args } => {
let cli_options = self.cli_options()?;
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(),
// 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,
}),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Test { args } => {
let cli_options = self.cli_options()?;
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,
),
]),
output: None,
}),
envs: merge_resolved_envs_with_version(envs, resolved.envs),
})
}
SynthesizableSubcommand::Pack { args } => {
let cli_options = self.cli_options()?;
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()),
output: None,
}),
envs: merge_resolved_envs(envs, resolved.envs),
})
}
SynthesizableSubcommand::Dev { args } => {
let cli_options = self.cli_options()?;
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()?;
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()?;
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,
output: 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"
);
}
}
}
}
/// 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),
]
}
/// Cache input entries for the check command.
/// The vp check subprocess is a full vp CLI process (not resolved to a binary like
/// build/lint/fmt), so it accesses additional directories that must be excluded:
/// - `.vite-temp`: config compilation cache, read+written during vp CLI startup
/// - `.vite/task-cache`: task runner state files that change after each run
pub(super) fn check_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("!node_modules/.vite/task-cache/**", InputBase::Workspace),
exclude_glob("!node_modules/.vite/task-cache/**", 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
}