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
//! # cm_run_task
//!
//! Enables to run cargo-make tasks from within duckscript.
//!

#[cfg(test)]
#[path = "cm_plugin_run_custom_task_test.rs"]
mod cm_plugin_run_custom_task_test;

use crate::runner;
use crate::types::{FlowInfo, FlowState, RunTaskOptions, Step, Task};
use duckscript::types::command::{Command, CommandResult};
use serde_json;
use std::cell::RefCell;
use std::rc::Rc;

#[derive(Clone)]
pub(crate) struct CommandImpl {
    flow_info: FlowInfo,
    flow_state: Rc<RefCell<FlowState>>,
    step: Step,
}

impl Command for CommandImpl {
    fn name(&self) -> String {
        "cm_plugin_run_custom_task".to_string()
    }

    fn clone_and_box(&self) -> Box<dyn Command> {
        Box::new((*self).clone())
    }

    fn run(&self, arguments: Vec<String>) -> CommandResult {
        if arguments.is_empty() {
            CommandResult::Error("No task data provided.".to_string())
        } else {
            let task: Task = match serde_json::from_str(&arguments[0]) {
                Ok(value) => value,
                Err(error) => return CommandResult::Error(error.to_string()),
            };

            let custom_step = Step {
                name: self.step.name.clone(),
                config: task,
            };

            let options = RunTaskOptions {
                plugins_enabled: false,
            };

            runner::run_task_with_options(
                &self.flow_info,
                self.flow_state.clone(),
                &custom_step,
                &options,
            );

            CommandResult::Continue(Some("true".to_string()))
        }
    }
}

pub(crate) fn create(
    flow_info: &FlowInfo,
    flow_state: Rc<RefCell<FlowState>>,
    step: &Step,
) -> Box<dyn Command> {
    Box::new(CommandImpl {
        flow_info: flow_info.clone(),
        flow_state,
        step: step.clone(),
    })
}