-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathlib.rs
More file actions
163 lines (153 loc) · 5.83 KB
/
lib.rs
File metadata and controls
163 lines (153 loc) · 5.83 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
use std::{
env::{self, join_paths},
ffi::OsStr,
iter,
sync::Arc,
};
use clap::Parser;
use vite_path::AbsolutePath;
use vite_str::Str;
use vite_task::{
Command, EnabledCacheConfig, HandledCommand, ScriptCommand, SessionConfig, TaskErrorHints,
UserCacheConfig, get_path_env, plan_request::SyntheticPlanRequest,
};
#[derive(Debug, Default)]
pub struct CommandHandler(());
/// Find an executable in `node_modules/.bin` directories up the tree.
///
/// # Errors
///
/// Returns an error if the executable cannot be found in any searched path.
pub fn find_executable(
path_env: Option<&Arc<OsStr>>,
cwd: &AbsolutePath,
executable: &str,
) -> anyhow::Result<Arc<OsStr>> {
#[expect(
clippy::disallowed_types,
reason = "PathBuf required by env::split_paths and which::which_in APIs"
)]
let mut paths: Vec<std::path::PathBuf> =
path_env.map_or_else(Vec::new, |path_env| env::split_paths(path_env).collect());
let mut current_cwd_parent = cwd;
loop {
let node_modules_bin = current_cwd_parent.join("node_modules").join(".bin");
paths.push(node_modules_bin.as_path().to_path_buf());
if let Some(parent) = current_cwd_parent.parent() {
current_cwd_parent = parent;
} else {
break;
}
}
let executable_path = which::which_in(executable, Some(join_paths(paths)?), cwd)?;
Ok(executable_path.into_os_string().into())
}
/// Internal argument parser for `vt`/`vp` commands that appear inside task scripts.
///
/// [`CommandHandler`] uses this to parse the command line when it intercepts a `vt` or `vp`
/// invocation during script execution. It extends [`Command`] with a `tool` subcommand that
/// forwards to the `vtt` test-utility binary — a subcommand that only makes sense within
/// script execution and is therefore not exposed on the top-level `vt` CLI entry point.
#[derive(Debug, Parser)]
#[command(name = "vt", version)]
enum Args {
/// Forward arguments to the `vtt` test-utility binary.
///
/// Resolves `vtt` via `node_modules/.bin` lookup (same as any other script executable),
/// then synthesizes a cached invocation with the given arguments. The `--` separator,
/// if present, is stripped before forwarding.
Tool {
#[clap(trailing_var_arg = true, allow_hyphen_values = true)]
args: Vec<Str>,
},
/// Any other `vt` subcommand, delegated to the standard [`Command`] parser.
#[command(flatten)]
Task(Command),
}
#[async_trait::async_trait(?Send)]
impl vite_task::CommandHandler for CommandHandler {
async fn handle_command(
&mut self,
command: &mut ScriptCommand,
) -> anyhow::Result<HandledCommand> {
match command.program.as_str() {
"vt" | "vp" => {}
// `vpr <args>` is shorthand for `vt run <args>`
"vpr" => {
command.program = Str::from("vt");
command.args =
iter::once(Str::from("run")).chain(command.args.iter().cloned()).collect();
}
_ => return Ok(HandledCommand::Verbatim),
}
let args = Args::try_parse_from(
std::iter::once(command.program.as_str()).chain(command.args.iter().map(Str::as_str)),
)?;
match args {
Args::Tool { args } => {
let program = find_executable(get_path_env(&command.envs), &command.cwd, "vtt")?;
Ok(HandledCommand::Synthesized(SyntheticPlanRequest {
program,
args: args.into_iter().filter(|a| a.as_str() != "--").collect(),
cache_config: UserCacheConfig::with_config(EnabledCacheConfig {
env: None,
untracked_env: None,
input: None,
}),
envs: Arc::clone(&command.envs),
}))
}
Args::Task(parsed) => Ok(HandledCommand::ViteTaskCommand(parsed)),
}
}
fn task_error_hints(&self) -> TaskErrorHints {
TaskErrorHints {
task_list_hint: Str::from("Run `vt run` to browse available tasks."),
task_source_hint: Str::from(
"Check `vite-task.json` and `package.json` scripts where tasks are defined.",
),
}
}
}
/// A `UserConfigLoader` implementation that only loads `vite-task.json`.
///
/// This is mainly for examples and testing as it does not require Node.js environment.
#[derive(Default, Debug)]
pub struct JsonUserConfigLoader(());
#[async_trait::async_trait(?Send)]
impl vite_task::loader::UserConfigLoader for JsonUserConfigLoader {
async fn load_user_config_file(
&self,
package_path: &AbsolutePath,
) -> anyhow::Result<Option<vite_task::config::UserRunConfig>> {
let config_path = package_path.join("vite-task.json");
let config_content = match tokio::fs::read_to_string(&config_path).await {
Ok(content) => content,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Ok(None);
}
Err(err) => return Err(err.into()),
};
let json_value = jsonc_parser::parse_to_serde_value(
&config_content,
&jsonc_parser::ParseOptions::default(),
)?
.unwrap_or_default();
let user_config: vite_task::config::UserRunConfig = serde_json::from_value(json_value)?;
Ok(Some(user_config))
}
}
#[derive(Default)]
pub struct OwnedSessionConfig {
command_handler: CommandHandler,
user_config_loader: JsonUserConfigLoader,
}
impl OwnedSessionConfig {
pub fn as_config(&mut self) -> SessionConfig<'_> {
SessionConfig {
command_handler: &mut self.command_handler,
user_config_loader: &mut self.user_config_loader,
program_name: Str::from("vt"),
}
}
}