-
Notifications
You must be signed in to change notification settings - Fork 453
Expand file tree
/
Copy pathexecutable_task.rs
More file actions
730 lines (660 loc) · 24.2 KB
/
executable_task.rs
File metadata and controls
730 lines (660 loc) · 24.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
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
use std::{
borrow::Cow,
collections::HashMap,
ffi::OsString,
fmt::{Display, Formatter},
path::PathBuf,
};
use deno_task_shell::{
ShellPipeWriter, ShellState, execute_with_pipes, parser::SequentialList, pipe,
};
use fs_err::tokio as tokio_fs;
use itertools::Itertools;
use miette::{Context, Diagnostic};
use pixi_consts::consts;
use pixi_core::{
Workspace,
activation::CurrentEnvVarBehavior,
workspace::get_activated_environment_variables,
workspace::{Environment, HasWorkspaceRef},
};
use pixi_manifest::{
Task, TaskName,
task::{ArgValues, TaskRenderContext, TemplateStringError},
};
use pixi_progress::await_in_progress;
use rattler_lock::LockFile;
use thiserror::Error;
use tokio::task::JoinHandle;
use crate::task_graph::{TaskGraph, TaskId};
use crate::task_hash::{InputHashesError, NameHash, TaskCache, TaskHash};
/// Runs task in project.
#[derive(Default, Debug)]
pub struct RunOutput {
pub exit_code: i32,
pub stdout: String,
pub stderr: String,
}
#[derive(Debug, Error, Diagnostic)]
#[error("The task failed to parse")]
pub enum FailedToParseShellScript {
#[error("failed to parse shell script. Task: '{task}'")]
ParseError {
#[source]
source: anyhow::Error,
task: String,
},
#[error(transparent)]
#[diagnostic(transparent)]
ArgumentReplacement(#[from] TemplateStringError),
}
#[derive(Debug, Error, Diagnostic)]
#[error("invalid working directory '{path}'")]
pub struct InvalidWorkingDirectory {
pub path: String,
}
#[derive(Debug, Error, Diagnostic)]
pub enum TaskExecutionError {
#[error(transparent)]
InvalidWorkingDirectory(#[from] InvalidWorkingDirectory),
#[error(transparent)]
FailedToParseShellScript(#[from] FailedToParseShellScript),
}
#[derive(Debug, Error, Diagnostic)]
pub enum CacheUpdateError {
#[error(transparent)]
Io(#[from] std::io::Error),
#[error(transparent)]
TaskHashError(#[from] InputHashesError),
#[error("failed to serialize cache")]
Serialization(#[from] serde_json::Error),
}
pub enum CanSkip {
Yes,
No(Option<TaskHash>),
}
/// A task that contains enough information to be able to execute it. The
/// lifetime [`'p`] refers to the lifetime of the project that contains the
/// tasks.
#[derive(Clone, Debug)]
pub struct ExecutableTask<'p> {
pub workspace: &'p Workspace,
pub name: Option<TaskName>,
pub task: Cow<'p, Task>,
pub run_environment: Environment<'p>,
pub args: ArgValues,
pub init_cwd: Option<PathBuf>,
}
impl<'p> ExecutableTask<'p> {
/// Constructs a new executable task from a task graph node.
pub fn from_task_graph(
task_graph: &TaskGraph<'p>,
task_id: TaskId,
init_cwd: Option<PathBuf>,
) -> Self {
let node = &task_graph[task_id];
Self {
workspace: task_graph.project(),
name: node.name.clone(),
task: node.task.clone(),
run_environment: node.run_environment.clone(),
args: node.args.clone().unwrap_or_default(),
init_cwd,
}
}
/// Returns the name of the task or `None` if this is an anonymous task.
pub fn name(&self) -> Option<&str> {
self.name.as_ref().map(|name| name.as_str())
}
/// Returns the task description from the project.
pub fn task(&self) -> &Task {
self.task.as_ref()
}
/// Returns the project in which this task is defined.
pub fn project(&self) -> &'p Workspace {
self.workspace
}
pub fn args(&self) -> &ArgValues {
&self.args
}
/// Creates a properly populated `TaskRenderContext` for this task.
///
/// This includes the platform, environment name, manifest path, and arguments.
pub fn render_context(&self) -> pixi_manifest::task::TaskRenderContext<'_> {
pixi_manifest::task::TaskRenderContext {
platform: self.run_environment.best_platform(),
environment_name: self.run_environment.name(),
manifest_path: Some(&self.workspace.workspace.provenance.path),
args: Some(&self.args),
init_cwd: self.init_cwd.as_deref(),
}
}
/// Returns the task as script
fn as_script(&self) -> Result<Option<String>, FailedToParseShellScript> {
// Convert the task into an executable string
let context = self.render_context();
let task = self
.task
.as_single_command(&context)
.map_err(FailedToParseShellScript::ArgumentReplacement)?;
if let Some(task) = task {
// Get the export specific environment variables
let export = get_export_specific_task_env(self.task.as_ref(), &context)
.map_err(FailedToParseShellScript::ArgumentReplacement)?;
// Append the command line arguments verbatim
let extra = self.args.extra_args();
let cli_args = if extra.is_empty() {
String::new()
} else {
format!(
" {}",
extra
.iter()
.format_with(" ", |arg, f| f(&format_args!("'{arg}'")))
)
};
// Skip the export if it's empty, to avoid newlines
let full_script = if export.is_empty() {
format!("{task}{cli_args}")
} else {
format!("{export}\n{task}{cli_args}")
};
Ok(Some(full_script))
} else {
Ok(None)
}
}
/// Returns a [`SequentialList`] which can be executed by deno task shell.
/// Returns `None` if the command is not executable like in the case of
/// an alias.
pub fn as_deno_script(&self) -> Result<Option<SequentialList>, FailedToParseShellScript> {
let full_script = self.as_script()?;
if let Some(full_script) = full_script {
tracing::debug!("Parsing shell script: {}", full_script);
// Parse the shell command
deno_task_shell::parser::parse(full_script.trim())
.map_err(|e| FailedToParseShellScript::ParseError {
source: e,
task: full_script.to_string(),
})
.map(Some)
} else {
Ok(None)
}
}
/// Returns the working directory for this task.
pub fn working_directory(&self) -> Result<PathBuf, InvalidWorkingDirectory> {
Ok(match self.task.working_directory() {
Some(cwd) if cwd.is_absolute() => cwd.to_path_buf(),
Some(cwd) => {
let abs_path = self.workspace.root().join(cwd);
if !abs_path.is_dir() {
return Err(InvalidWorkingDirectory {
path: cwd.to_string_lossy().to_string(),
});
}
abs_path
}
None => self.workspace.root().to_path_buf(),
})
}
/// Returns the full command that should be executed for this task. This
/// includes any additional arguments that should be passed to the
/// command.
///
/// This function returns `None` if the task does not define a command to
/// execute. This is the case for alias only commands.
pub fn full_command(&self) -> Result<Option<String>, TemplateStringError> {
let context = self.render_context();
let original_cmd = self
.task
.as_single_command(&context)?
.map(|c| c.into_owned());
if let Some(mut cmd) = original_cmd {
let extra = self.args.extra_args();
if !extra.is_empty() {
cmd.push(' ');
cmd.push_str(&extra.join(" "));
}
Ok(Some(cmd))
} else {
Ok(None)
}
}
/// Returns an object that implements [`Display`] which outputs the command
/// of the wrapped task.
pub fn display_command(&self) -> impl Display + '_ {
ExecutableTaskConsoleDisplay { task: self }
}
/// Executes the task and capture its output.
pub async fn execute_with_pipes(
&self,
command_env: &HashMap<OsString, OsString>,
input: Option<&[u8]>,
) -> Result<RunOutput, TaskExecutionError> {
let Some(script) = self.as_deno_script()? else {
return Ok(RunOutput {
exit_code: 0,
stdout: String::new(),
stderr: String::new(),
});
};
let cwd = self.working_directory()?;
let (stdin, mut stdin_writer) = pipe();
if let Some(stdin) = input {
stdin_writer
.write_all(stdin)
.expect("should be able to write to stdin");
}
drop(stdin_writer); // prevent a deadlock by dropping the writer
let (stdout, stdout_handle) = get_output_writer_and_handle();
let (stderr, stderr_handle) = get_output_writer_and_handle();
let state = ShellState::new(
command_env.clone(),
cwd,
Default::default(),
Default::default(),
);
let code = execute_with_pipes(script, state, stdin, stdout, stderr).await;
Ok(RunOutput {
exit_code: code,
stdout: stdout_handle.await.expect("should be able to get stdout"),
stderr: stderr_handle.await.expect("should be able to get stderr"),
})
}
/// Compute the post-run task hash by updating inputs and outputs.
/// This does not emit any warnings; it only reflects the current filesystem state.
pub async fn compute_post_run_hash(
&self,
lock_file: &LockFile,
previous_hash: Option<TaskHash>,
) -> Result<Option<TaskHash>, InputHashesError> {
// Start from provided hash if available, otherwise from current task state.
// If neither is available, create a minimal hash so we can report warnings
// and make a consistent caching decision.
let mut hash = if let Some(hash) = previous_hash {
hash
} else if let Some(hash) = TaskHash::from_task(self, lock_file).await? {
hash
} else {
TaskHash {
command: self.full_command().ok().flatten(),
inputs: None,
outputs: None,
environment: pixi_core::environment::EnvironmentHash::from_environment(
&self.run_environment,
&std::collections::HashMap::new(),
lock_file,
),
}
};
// Update inputs/outputs based on the current filesystem
hash.update_output(self).await?;
hash.update_input(self).await?;
Ok(Some(hash))
}
/// Emit warnings for missing input/output globs given a computed hash.
pub fn warn_on_missing_globs(&self, post_hash: &TaskHash) {
let (rendered_inputs, rendered_outputs) = match self.task().as_execute() {
Ok(exe) => {
let context = self.render_context();
let ins = exe
.inputs
.as_ref()
.map(|p| p.render(&context).unwrap_or_default());
let outs = exe
.outputs
.as_ref()
.map(|p| p.render(&context).unwrap_or_default());
(ins, outs)
}
Err(_) => (None, None),
};
// Outputs warning
if rendered_outputs.is_some()
&& post_hash.outputs.is_none()
&& let Some(globs) = rendered_outputs.as_ref()
{
tracing::warn!(
"No files matched the output globs for task '{}'",
self.name().unwrap_or_default()
);
let formatted = globs.iter().map(|g| format!("`{}`", g.inner())).join(", ");
tracing::warn!("Output globs: {}", formatted);
}
// Inputs warning
if rendered_inputs.is_some()
&& post_hash.inputs.is_none()
&& let Some(globs) = rendered_inputs.as_ref()
{
tracing::warn!(
"No files matched the input globs for task '{}'",
self.name().unwrap_or_default()
);
let formatted = globs.iter().map(|g| format!("`{}`", g.inner())).join(", ");
tracing::warn!("Input globs: {}", formatted);
}
}
/// We store the hashes of the inputs and the outputs of the task in a file
/// in the cache. The current name is something like
/// `run_environment-task_name.json`.
pub(crate) fn cache_name(&self, args_cache: Option<NameHash>) -> String {
format!(
"{}-{}-{}.json",
self.run_environment.name(),
self.name().unwrap_or("default"),
args_cache
.map(|hash| hash.to_string())
.unwrap_or("".to_string())
)
}
/// Checks if the task can be skipped. If the task can be skipped, it
/// returns `CanSkip::Yes`. If the task cannot be skipped, it returns
/// `CanSkip::No` and includes the hash of the task that caused the task
/// to not be skipped - we can use this later to update the cache file
/// quickly.
pub async fn can_skip(&self, lock_file: &LockFile) -> Result<CanSkip, std::io::Error> {
tracing::info!("Checking if task can be skipped");
let args_hash = TaskHash::task_args_hash(self).unwrap_or_default();
let cache_name = self.cache_name(args_hash);
let cache_file = self.project().task_cache_folder().join(cache_name);
if cache_file.exists() {
let cache = tokio_fs::read_to_string(&cache_file).await?;
let cache: TaskCache = serde_json::from_str(&cache)?;
let hash = TaskHash::from_task(self, lock_file).await;
if let Ok(Some(hash)) = hash {
if hash.computation_hash() != cache.hash {
return Ok(CanSkip::No(Some(hash)));
} else {
return Ok(CanSkip::Yes);
}
}
}
Ok(CanSkip::No(None))
}
/// Saves the cache of the task using the provided post-run hash.
/// If the task has no inputs or outputs (hash is None), it will not save the cache.
pub async fn save_cache(
&self,
post_run_hash: Option<TaskHash>,
) -> Result<(), CacheUpdateError> {
let execute = if let Ok(task) = self.task().as_execute() {
task
} else {
// Don't save cache for non-execute tasks
return Ok(());
};
let task_cache_folder = self.project().task_cache_folder();
let args_cache = TaskHash::task_args_hash(self)?;
let cache_file = task_cache_folder.join(self.cache_name(args_cache));
// Use the post-run hash provided by the caller
let new_hash = match post_run_hash {
Some(hash) => hash,
None => return Ok(()),
};
// If any configured globs (inputs or outputs) did not match, do not create a cache entry
let outputs_unmatched = execute.outputs.is_some() && new_hash.outputs.is_none();
let inputs_unmatched = execute.inputs.is_some() && new_hash.inputs.is_none();
if outputs_unmatched || inputs_unmatched {
return Ok(());
}
tokio::fs::create_dir_all(&task_cache_folder).await?;
let cache = TaskCache {
hash: new_hash.computation_hash(),
};
let cache = serde_json::to_string(&cache)?;
Ok(tokio::fs::write(&cache_file, cache).await?)
}
}
/// A helper object that implements [`Display`] to display (with ascii color)
/// the command of the task.
struct ExecutableTaskConsoleDisplay<'p, 't> {
task: &'t ExecutableTask<'p>,
}
impl Display for ExecutableTaskConsoleDisplay<'_, '_> {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let context = self.task.render_context();
match self.task.task.as_single_command(&context) {
Ok(command) => {
write!(
f,
"{}",
consts::TASK_STYLE
.apply_to(command.as_deref().unwrap_or("<alias>"))
.bold()
)?;
let extra = self.task.args.extra_args();
if !extra.is_empty() {
write!(
f,
" {}",
consts::TASK_STYLE.apply_to(extra.iter().format(" "))
)?;
}
Ok(())
}
Err(err) => {
write!(
f,
"{}",
consts::TASK_ERROR_STYLE.apply_to(err.get_source()).bold()
)
}
}
}
}
/// Helper function to create a pipe that we can get the output from.
fn get_output_writer_and_handle() -> (ShellPipeWriter, JoinHandle<String>) {
let (reader, writer) = pipe();
let handle = reader.pipe_to_string_handle();
(writer, handle)
}
/// Task specific environment variables.
///
/// These are rendered as `export KEY=VALUE` statements and prepended to the
/// task script. At runtime they are interpreted by `deno_task_shell`, not by an
/// external OS shell, so `$VAR`-style expansion follows deno-task-shell’s
/// semantics.
fn get_export_specific_task_env(
task: &Task,
context: &TaskRenderContext,
) -> Result<String, TemplateStringError> {
// Append the environment variables if they don’t exist
let mut export = String::new();
if let Some(env) = task.env() {
for (key, value) in env {
let rendered = value.render(context)?;
// Escape double quotes so the export statement remains valid shell.
let escaped = rendered.replace('"', "\\\"");
tracing::debug!("Setting environment variable: {}=\"{}\"", key, escaped);
export.push_str(&format!("export \"{key}={escaped}\";\n"));
}
}
Ok(export)
}
/// 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(
environment: &Environment<'_>,
clean_env: bool,
lock_file: Option<&LockFile>,
force_activate: bool,
experimental_cache: bool,
) -> miette::Result<HashMap<String, String>> {
// Get environment variables from the activation
let env_var_behavior = if clean_env {
CurrentEnvVarBehavior::Clean
} else {
CurrentEnvVarBehavior::Include
};
let mut activation_env = await_in_progress("activating environment", |_| {
get_activated_environment_variables(
environment.workspace().env_vars(),
environment,
env_var_behavior,
lock_file,
force_activate,
experimental_cache,
)
})
.await
.wrap_err("failed to activate environment")?
.clone();
// Add the current working directory to the environment
if let Ok(init_cwd) = std::env::current_dir() {
activation_env.insert(
"INIT_CWD".to_string(),
init_cwd.to_string_lossy().to_string(),
);
} else {
tracing::warn!("Failed to get the current working directory for INIT_CWD.");
}
// Concatenate with the system environment variables
Ok(activation_env)
}
#[cfg(test)]
mod tests {
use super::*;
use pixi_manifest::task::{ArgValues, TypedArg};
use std::path::Path;
const PROJECT_BOILERPLATE: &str = r#"
[project]
name = "foo"
version = "0.1.0"
channels = []
# Required to run tests
platforms = ["linux-64", "osx-64", "win-64", "osx-arm64", "linux-ppc64le", "linux-aarch64"]
"#;
#[test]
fn test_export_specific_task_env() {
let file_contents = r#"
[tasks]
test = {cmd = "test", cwd = "tests", env = {FOO = "bar", BAR = "$FOO"}}
"#;
let workspace = Workspace::from_str(
Path::new("pixi.toml"),
&format!("{PROJECT_BOILERPLATE}\n{file_contents}"),
)
.unwrap();
let task = workspace
.default_environment()
.task(&TaskName::from("test"), None)
.unwrap();
let context = TaskRenderContext::default();
let export = get_export_specific_task_env(task, &context).unwrap();
assert_eq!(export, "export \"FOO=bar\";\nexport \"BAR=$FOO\";\n");
}
#[test]
fn test_export_specific_task_env_with_template() {
let file_contents = r#"
[tasks]
test = {cmd = "test", env = {BACKEND = "{{ backend }}"}, args = [{arg = "backend", default = "Numba"}]}
"#;
let workspace = Workspace::from_str(
Path::new("pixi.toml"),
&format!("{PROJECT_BOILERPLATE}\n{file_contents}"),
)
.unwrap();
let task = workspace
.default_environment()
.task(&TaskName::from("test"), None)
.unwrap();
// Test with explicit arg value
let args = ArgValues::TypedArgs {
args: vec![TypedArg {
name: "backend".into(),
value: "CuPy".into(),
}],
extra: vec![],
};
let context = TaskRenderContext {
args: Some(&args),
..Default::default()
};
let export = get_export_specific_task_env(task, &context).unwrap();
assert_eq!(export, "export \"BACKEND=CuPy\";\n");
// Test with default context (no args renders the default)
let default_args = ArgValues::TypedArgs {
args: vec![TypedArg {
name: "backend".into(),
value: "Numba".into(),
}],
extra: vec![],
};
let context = TaskRenderContext {
args: Some(&default_args),
..Default::default()
};
let export = get_export_specific_task_env(task, &context).unwrap();
assert_eq!(export, "export \"BACKEND=Numba\";\n");
}
#[test]
fn test_export_env_escapes_double_quotes() {
let file_contents = r#"
[tasks]
test = {cmd = "test", env = {JSON = '{"key": "value"}'}}
"#;
let workspace = Workspace::from_str(
Path::new("pixi.toml"),
&format!("{PROJECT_BOILERPLATE}\n{file_contents}"),
)
.unwrap();
let task = workspace
.default_environment()
.task(&TaskName::from("test"), None)
.unwrap();
let context = TaskRenderContext::default();
let export = get_export_specific_task_env(task, &context).unwrap();
assert_eq!(export, "export \"JSON={\\\"key\\\": \\\"value\\\"}\";\n");
}
#[test]
fn test_as_script() {
let file_contents = r#"
[tasks]
test = {cmd = "test", cwd = "tests", env = {FOO = "bar"}}
"#;
let workspace = Workspace::from_str(
Path::new("pixi.toml"),
&format!("{PROJECT_BOILERPLATE}\n{file_contents}"),
)
.unwrap();
let task = workspace
.default_environment()
.task(&TaskName::from("test"), None)
.unwrap();
let executable_task = ExecutableTask {
workspace: &workspace,
name: Some("test".into()),
task: Cow::Borrowed(task),
run_environment: workspace.default_environment(),
args: ArgValues::default(),
init_cwd: None,
};
let script = executable_task.as_script().unwrap().unwrap();
assert_eq!(script, "export \"FOO=bar\";\n\ntest");
}
#[tokio::test]
async fn test_get_task_env() {
let file_contents = r#"
[tasks]
test = {cmd = "test", cwd = "tests", env = {FOO = "bar"}}
"#;
let workspace = Workspace::from_str(
Path::new("pixi.toml"),
&format!("{PROJECT_BOILERPLATE}\n{file_contents}"),
)
.unwrap();
let environment = workspace.default_environment();
let env = get_task_env(&environment, false, None, false, false)
.await
.unwrap();
assert_eq!(
env.get("INIT_CWD").unwrap(),
&std::env::current_dir()
.unwrap()
.to_string_lossy()
.to_string()
);
}
}