Skip to content

Commit

Permalink
implement when like ansible
Browse files Browse the repository at this point in the history
  • Loading branch information
flawiddsouza committed Nov 9, 2024
1 parent eb53a27 commit b3c4377
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ struct Task {
debug: Option<Debug>,
vars: Option<IndexMap<String, String>>,
chdir: Option<String>,
when: Option<String>,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -429,6 +430,24 @@ fn process_commands(
Ok(())
}

fn should_run_task(
condition: &Option<String>,
register_map: &IndexMap<String, Register>,
vars_map: &IndexMap<String, Value>,
) -> 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<dyn std::error::Error>> {
let matches = ClapCommand::new("deploy-helper")
.version("1.0.3")
Expand Down Expand Up @@ -521,6 +540,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
};

for task in &dep.tasks {
if !should_run_task(&task.when, &register_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
Expand Down
11 changes: 11 additions & 0 deletions test-ymls/when-condition.yml
Original file line number Diff line number Diff line change
@@ -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"
12 changes: 12 additions & 0 deletions test-ymls/when-condition.yml.out
Original file line number Diff line number Diff line change
@@ -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

5 changes: 5 additions & 0 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
}

0 comments on commit b3c4377

Please sign in to comment.