Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add the current working directory in tasks #380

Merged
merged 2 commits into from
Oct 6, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
test: add test to check if the cwd works for the tasks
  • Loading branch information
ruben-arts committed Oct 6, 2023
commit 1a3f61b59803ba4e2df7a3b573d1142ccae46035
34 changes: 17 additions & 17 deletions src/cli/run.rs
Original file line number Diff line number Diff line change
@@ -151,6 +151,20 @@ pub async fn create_script(task: Task, args: Vec<String>) -> miette::Result<Sequ
deno_task_shell::parser::parse(full_script.trim()).map_err(|e| miette!("{e}"))
}

/// Select a working directory based on a given path or the project.
pub fn select_cwd(path: Option<&Path>, project: &Project) -> miette::Result<PathBuf> {
Ok(match path {
Some(cwd) if cwd.is_absolute() => cwd.to_path_buf(),
Some(cwd) => {
let abs_path = project.root().join(cwd);
if !abs_path.exists() {
miette::bail!("Can't find the 'cwd': '{}'", abs_path.display());
}
abs_path
}
None => project.root().to_path_buf(),
})
}
/// Executes the given command within the specified project and with the given environment.
pub async fn execute_script(
script: SequentialList,
@@ -163,7 +177,7 @@ pub async fn execute_script(

pub async fn execute_script_with_output(
script: SequentialList,
project: &Project,
cwd: &Path,
command_env: &HashMap<String, String>,
input: Option<&[u8]>,
) -> RunOutput {
@@ -174,7 +188,7 @@ pub async fn execute_script_with_output(
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(), project.root(), Default::default());
let state = ShellState::new(command_env.clone(), cwd, Default::default());
let code = execute_with_pipes(script, state, stdin, stdout, stderr).await;
RunOutput {
exit_code: code,
@@ -196,21 +210,7 @@ pub async fn execute(args: Args) -> miette::Result<()> {

// Execute the commands in the correct order
while let Some((command, args)) = ordered_commands.pop_back() {
// Get current working directory based on the information in the task.
let cwd = match command.working_directory() {
None => project.root().to_path_buf(),
Some(cwd) => {
if cwd.is_absolute() {
cwd.to_path_buf()
} else {
let path = project.root().join(cwd);
if !path.exists() {
miette::bail!("Can't find the 'cwd': '{}'", path.display());
}
path
}
}
};
let cwd = select_cwd(command.working_directory(), &project)?;
// 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
6 changes: 6 additions & 0 deletions tests/common/builders.rs
Original file line number Diff line number Diff line change
@@ -149,6 +149,12 @@ impl TaskAddBuilder {
self
}

/// With this working directory
pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
self.args.cwd = Some(cwd);
self
}

/// Execute the CLI command
pub fn execute(self) -> miette::Result<()> {
task::execute(task::Args {
4 changes: 3 additions & 1 deletion tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -188,9 +188,11 @@ impl PixiControl {

let mut result = RunOutput::default();
while let Some((command, args)) = tasks.pop_back() {
let cwd = run::select_cwd(command.working_directory(), &project)?;
let script = create_script(command, args).await;
if let Ok(script) = script {
let output = execute_script_with_output(script, &project, &task_env, None).await;
let output =
execute_script_with_output(script, cwd.as_path(), &task_env, None).await;
result.stdout.push_str(&output.stdout);
result.stderr.push_str(&output.stderr);
result.exit_code = output.exit_code;
49 changes: 49 additions & 0 deletions tests/task_tests.rs
Original file line number Diff line number Diff line change
@@ -2,6 +2,8 @@ use crate::common::PixiControl;
use pixi::cli::run::Args;
use pixi::task::{CmdArgs, Task};
use rattler_conda_types::Platform;
use std::fs;
use std::path::PathBuf;

mod common;

@@ -142,3 +144,50 @@ pub async fn add_remove_target_specific_task() {
0
);
}

#[tokio::test]
async fn test_cwd() {
let pixi = PixiControl::new().unwrap();
pixi.init().without_channels().await.unwrap();

// Create test dir
fs::create_dir(pixi.project_path().join("test")).unwrap();

pixi.tasks()
.add("pwd-test", None)
.with_commands(["pwd"])
.with_cwd(PathBuf::from("test"))
.execute()
.unwrap();

let result = pixi
.run(Args {
task: vec!["pwd-test".to_string()],
manifest_path: None,
locked: false,
frozen: false,
})
.await
.unwrap();

assert_eq!(result.exit_code, 0);
assert!(result.stdout.contains("test"));

// Test that an unknown cwd gives an error
pixi.tasks()
.add("unknown-cwd", None)
.with_commands(["pwd"])
.with_cwd(PathBuf::from("tests"))
.execute()
.unwrap();

assert!(pixi
.run(Args {
task: vec!["unknown-cwd".to_string()],
manifest_path: None,
locked: false,
frozen: false,
})
.await
.is_err());
}
Loading