From b3c437722d8e69dbe7cf864b0b4f8ad67f3f828c Mon Sep 17 00:00:00 2001 From: Flawid DSouza Date: Sat, 9 Nov 2024 15:37:00 +0530 Subject: [PATCH] implement when like ansible --- src/main.rs | 24 ++++++++++++++++++++++++ test-ymls/when-condition.yml | 11 +++++++++++ test-ymls/when-condition.yml.out | 12 ++++++++++++ tests/integration_test.rs | 5 +++++ 4 files changed, 52 insertions(+) create mode 100644 test-ymls/when-condition.yml create mode 100644 test-ymls/when-condition.yml.out diff --git a/src/main.rs b/src/main.rs index 4cd6853..88ceb6c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,6 +46,7 @@ struct Task { debug: Option, vars: Option>, chdir: Option, + when: Option, } #[derive(Debug, Deserialize)] @@ -429,6 +430,24 @@ fn process_commands( Ok(()) } +fn should_run_task( + condition: &Option, + register_map: &IndexMap, + vars_map: &IndexMap, +) -> bool { + if let Some(cond) = condition { + let template_str = format!("{{% if {} %}}true{{% else %}}false{{% endif %}}", cond); + let rendered_cond = replace_placeholders(&template_str, register_map, vars_map); + if rendered_cond == "false" { + false + } else { + true + } + } else { + true + } +} + fn main() -> Result<(), Box> { let matches = ClapCommand::new("deploy-helper") .version("1.0.3") @@ -521,6 +540,11 @@ fn main() -> Result<(), Box> { }; for task in &dep.tasks { + if !should_run_task(&task.when, ®ister_map, &vars_map) { + println!("{}", format!("Skipping task: {}\n", task.name).yellow()); + continue; + } + println!("{}", format!("Executing task: {}", task.name).cyan()); let task_chdir = task.chdir.as_deref().or(dep.chdir.as_deref()); // Use task-level chdir if present, otherwise use top-level chdir diff --git a/test-ymls/when-condition.yml b/test-ymls/when-condition.yml new file mode 100644 index 0000000..653e54b --- /dev/null +++ b/test-ymls/when-condition.yml @@ -0,0 +1,11 @@ +- name: Test when condition + hosts: local + tasks: + - name: should run when condition is true + shell: echo "Condition is true" + when: condition == "true" + - name: should not run when condition is false + shell: echo "Condition is false" + when: condition == "false" + - name: always run + shell: echo "Always run" diff --git a/test-ymls/when-condition.yml.out b/test-ymls/when-condition.yml.out new file mode 100644 index 0000000..6975618 --- /dev/null +++ b/test-ymls/when-condition.yml.out @@ -0,0 +1,12 @@ +Starting deployment: Test when condition + +Executing task: should run when condition is true +> echo "Condition is true" +Condition is true + +Skipping task: should not run when condition is false + +Executing task: always run +> echo "Always run" +Always run + diff --git a/tests/integration_test.rs b/tests/integration_test.rs index ba57a43..a6003a6 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -126,3 +126,8 @@ fn extra_vars() { "@test-ymls/extra-vars.vars.yml", ); } + +#[test] +fn when_condition() { + run_test("test-ymls/when-condition.yml", false, "condition=true"); +}