-
Notifications
You must be signed in to change notification settings - Fork 135
/
run.rs
337 lines (295 loc) · 11.8 KB
/
run.rs
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
use std::collections::hash_map::Entry;
use std::collections::HashSet;
use std::convert::identity;
use std::str::FromStr;
use std::{collections::HashMap, path::PathBuf, string::String};
use crate::config::ConfigCli;
use clap::Parser;
use dialoguer::theme::ColorfulTheme;
use itertools::Itertools;
use miette::{miette, Context, Diagnostic, IntoDiagnostic};
use rattler_conda_types::Platform;
use crate::activation::get_environment_variables;
use crate::environment::verify_prefix_location_unchanged;
use crate::project::errors::UnsupportedPlatformError;
use crate::task::{
AmbiguousTask, CanSkip, ExecutableTask, FailedToParseShellScript, InvalidWorkingDirectory,
SearchEnvironments, TaskAndEnvironment, TaskGraph, TaskName,
};
use crate::Project;
use crate::lock_file::LockFileDerivedData;
use crate::lock_file::UpdateLockFileOptions;
use crate::progress::await_in_progress;
use crate::project::manifest::EnvironmentName;
use crate::project::virtual_packages::verify_current_platform_has_required_virtual_packages;
use crate::project::Environment;
use thiserror::Error;
use tracing::Level;
/// Runs task in project.
#[derive(Parser, Debug, Default)]
#[clap(trailing_var_arg = true, arg_required_else_help = true)]
pub struct Args {
/// The task you want to run in the projects environment.
pub task: Vec<String>,
/// The path to 'pixi.toml'
#[arg(long)]
pub manifest_path: Option<PathBuf>,
#[clap(flatten)]
pub lock_file_usage: super::LockFileUsageArgs,
#[arg(long, short)]
pub environment: Option<String>,
#[clap(flatten)]
pub config: ConfigCli,
}
/// CLI entry point for `pixi run`
/// When running the sigints are ignored and child can react to them. As it pleases.
pub async fn execute(args: Args) -> miette::Result<()> {
// Load the project
let project =
Project::load_or_else_discover(args.manifest_path.as_deref())?.with_cli_config(args.config);
// Sanity check of prefix location
verify_prefix_location_unchanged(project.default_environment().dir().as_path())?;
// Extract the passed in environment name.
let explicit_environment = args
.environment
.map(|n| EnvironmentName::from_str(n.as_str()))
.transpose()?
.map(|n| {
project
.environment(&n)
.ok_or_else(|| miette::miette!("unknown environment '{n}'"))
})
.transpose()?;
// Verify that the current platform has the required virtual packages for the environment.
if let Some(ref explicit_environment) = explicit_environment {
verify_current_platform_has_required_virtual_packages(explicit_environment)
.into_diagnostic()?;
}
// Ensure that the lock-file is up-to-date.
let mut lock_file = project
.up_to_date_lock_file(UpdateLockFileOptions {
lock_file_usage: args.lock_file_usage.into(),
..UpdateLockFileOptions::default()
})
.await?;
// Split 'task' into arguments if it's a single string, supporting commands like:
// `"test 1 == 0 || echo failed"` or `"echo foo && echo bar"` or `"echo 'Hello World'"`
// This prevents shell interpretation of pixi run inputs.
// Use as-is if 'task' already contains multiple elements.
let task_args = if args.task.len() == 1 {
shlex::split(args.task[0].as_str())
.ok_or(miette!("Could not split task, assuming non valid task"))?
} else {
args.task
};
tracing::debug!("Task parsed from run command: {:?}", task_args);
// Construct a task graph from the input arguments
let search_environment = SearchEnvironments::from_opt_env(
&project,
explicit_environment.clone(),
Some(Platform::current()),
)
.with_disambiguate_fn(disambiguate_task_interactive);
let task_graph = TaskGraph::from_cmd_args(&project, &search_environment, task_args)?;
tracing::info!("Task graph: {}", task_graph);
// Traverse the task graph in topological order and execute each individual task.
let mut task_idx = 0;
let mut task_envs = HashMap::new();
for task_id in task_graph.topological_order() {
let executable_task = ExecutableTask::from_task_graph(&task_graph, task_id);
// If the task is not executable (e.g. an alias), we skip it. This ensures we don't
// instantiate a prefix for an alias.
if !executable_task.task().is_executable() {
continue;
}
// Showing which command is being run if the level and type allows it.
if tracing::enabled!(Level::WARN) && !executable_task.task().is_custom() {
if task_idx > 0 {
// Add a newline between task outputs
eprintln!();
}
eprintln!(
"{}{}{}{}{}",
console::Emoji("✨ ", ""),
console::style("Pixi task (").bold(),
executable_task
.run_environment
.name()
.fancy_display()
.bold(),
console::style("): ").bold(),
executable_task.display_command(),
);
}
// check task cache
let task_cache = match executable_task
.can_skip(&lock_file)
.await
.into_diagnostic()?
{
CanSkip::No(cache) => cache,
CanSkip::Yes => {
eprintln!("Task can be skipped (cache hit) 🚀");
task_idx += 1;
continue;
}
};
// If we don't have a command environment yet, we need to compute it. We lazily compute the
// task environment because we only need the environment if a task is actually executed.
let task_env: &_ = match task_envs.entry(executable_task.run_environment.clone()) {
Entry::Occupied(env) => env.into_mut(),
Entry::Vacant(entry) => {
let command_env =
get_task_env(&mut lock_file, &executable_task.run_environment).await?;
entry.insert(command_env)
}
};
// Execute the task itself within the command environment. If one of the tasks failed with
// a non-zero exit code, we exit this parent process with the same code.
match execute_task(&executable_task, task_env).await {
Ok(_) => {
task_idx += 1;
}
Err(TaskExecutionError::NonZeroExitCode(code)) => {
if code == 127 {
command_not_found(&project, explicit_environment);
}
std::process::exit(code);
}
Err(err) => return Err(err.into()),
}
// Update the task cache with the new hash
executable_task
.save_cache(&lock_file, task_cache)
.await
.into_diagnostic()?;
}
Ok(())
}
/// Called when a command was not found.
fn command_not_found<'p>(project: &'p Project, explicit_environment: Option<Environment<'p>>) {
let available_tasks: HashSet<TaskName> =
if let Some(explicit_environment) = explicit_environment {
explicit_environment
.tasks(Some(Platform::current()), true)
.into_iter()
.flat_map(|tasks| tasks.into_keys())
.map(ToOwned::to_owned)
.collect()
} else {
project
.environments()
.into_iter()
.filter(|env| verify_current_platform_has_required_virtual_packages(env).is_ok())
.flat_map(|env| {
env.tasks(Some(Platform::current()), true)
.into_iter()
.flat_map(|tasks| tasks.into_keys())
.map(ToOwned::to_owned)
})
.collect()
};
if !available_tasks.is_empty() {
eprintln!(
"\nAvailable tasks:\n{}",
available_tasks
.into_iter()
.sorted()
.format_with("\n", |name, f| {
f(&format_args!("\t{}", name.fancy_display().bold()))
})
);
}
}
/// Determine the environment variables to use when executing a command. The method combines the
/// activation environment with the system environment variables.
pub async fn get_task_env<'p>(
lock_file_derived_data: &mut LockFileDerivedData<'p>,
environment: &Environment<'p>,
) -> miette::Result<HashMap<String, String>> {
// Ensure there is a valid prefix
lock_file_derived_data.prefix(environment).await?;
// Get environment variables from the activation
let activation_env = await_in_progress("activating environment", |_| {
crate::activation::run_activation(environment)
})
.await
.wrap_err("failed to activate environment")?;
// Get environments from pixi
let environment_variables = get_environment_variables(environment);
// Concatenate with the system environment variables
Ok(std::env::vars()
.chain(activation_env)
.chain(environment_variables)
.collect())
}
#[derive(Debug, Error, Diagnostic)]
enum TaskExecutionError {
#[error("the script exited with a non-zero exit code {0}")]
NonZeroExitCode(i32),
#[error(transparent)]
FailedToParseShellScript(#[from] FailedToParseShellScript),
#[error(transparent)]
InvalidWorkingDirectory(#[from] InvalidWorkingDirectory),
#[error(transparent)]
UnsupportedPlatformError(#[from] UnsupportedPlatformError),
}
/// Called to execute a single command.
///
/// This function is called from [`execute`].
async fn execute_task<'p>(
task: &ExecutableTask<'p>,
command_env: &HashMap<String, String>,
) -> Result<(), TaskExecutionError> {
let Some(script) = task.as_deno_script()? else {
return Ok(());
};
let cwd = task.working_directory()?;
// Ignore CTRL+C
// Specifically so that the child is responsible for its own signal handling
// NOTE: one CTRL+C is registered it will always stay registered for the rest of the runtime of the program
// which is fine when using run in isolation, however if we start to use run in conjunction with
// some other command we might want to revaluate this.
let ctrl_c = tokio::spawn(async { while tokio::signal::ctrl_c().await.is_ok() {} });
let execute_future =
deno_task_shell::execute(script, command_env.clone(), &cwd, Default::default());
let status_code = tokio::select! {
code = execute_future => code,
// This should never exit
_ = ctrl_c => { unreachable!("Ctrl+C should not be triggered") }
};
if status_code != 0 {
return Err(TaskExecutionError::NonZeroExitCode(status_code));
}
Ok(())
}
/// Called to disambiguate between environments to run a task in.
fn disambiguate_task_interactive<'p>(
problem: &AmbiguousTask<'p>,
) -> Option<TaskAndEnvironment<'p>> {
let environment_names = problem
.environments
.iter()
.map(|(env, _)| env.name())
.collect_vec();
let theme = ColorfulTheme {
active_item_style: console::Style::new().for_stderr().magenta(),
..ColorfulTheme::default()
};
dialoguer::Select::with_theme(&theme)
.with_prompt(format!(
"The task '{}' {}can be run in multiple environments.\n\nPlease select an environment to run the task in:",
problem.task_name.fancy_display(),
if let Some(dependency) = &problem.depended_on_by {
format!("(depended on by '{}') ", dependency.0.fancy_display())
} else {
String::new()
}
))
.report(false)
.items(&environment_names)
.default(0)
.interact_opt()
.map_or(None, identity)
.map(|idx| problem.environments[idx].clone())
}