mk_lib/schema/
task.rs

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
use anyhow::Context;
use indicatif::{
  HumanDuration,
  MultiProgress,
  ProgressBar,
  ProgressStyle,
};
use rand::Rng as _;
use serde::{
  Deserialize,
  Serialize,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::{
  Duration,
  Instant,
};
use std::{
  fs,
  thread,
};

use super::{
  CommandRunner,
  ExecutionStack,
  Precondition,
  TaskDependency,
  TaskRoot,
};

pub struct TaskContext {
  pub task_root: Arc<TaskRoot>,
  pub execution_stack: ExecutionStack,
  pub multi: Arc<MultiProgress>,
  pub env_vars: HashMap<String, String>,
  pub ignore_errors: bool,
  pub verbose: bool,
  pub is_nested: bool,
}

impl TaskContext {
  pub fn new(task_root: Arc<TaskRoot>, execution_stack: ExecutionStack) -> Self {
    Self {
      task_root: task_root.clone(),
      execution_stack,
      multi: Arc::new(MultiProgress::new()),
      env_vars: HashMap::new(),
      ignore_errors: false,
      verbose: false,
      is_nested: false,
    }
  }

  pub fn from_context(context: &TaskContext) -> Self {
    Self {
      task_root: context.task_root.clone(),
      execution_stack: context.execution_stack.clone(),
      multi: context.multi.clone(),
      env_vars: context.env_vars.clone(),
      ignore_errors: context.ignore_errors,
      verbose: context.verbose,
      is_nested: true,
    }
  }

  pub fn from_context_with_args(context: &TaskContext, ignore_errors: bool, verbose: bool) -> Self {
    Self {
      task_root: context.task_root.clone(),
      execution_stack: context.execution_stack.clone(),
      multi: context.multi.clone(),
      env_vars: context.env_vars.clone(),
      ignore_errors,
      verbose,
      is_nested: true,
    }
  }
}

/// This struct represents a task that can be executed. A task can contain multiple
/// commands that are executed sequentially. A task can also have preconditions that
/// must be met before the task can be executed.
#[derive(Debug, Default, Serialize, Deserialize, PartialEq)]
pub struct Task {
  pub commands: Vec<CommandRunner>,

  #[serde(default)]
  pub preconditions: Vec<Precondition>,

  #[serde(default)]
  pub depends_on: Vec<TaskDependency>,

  #[serde(default)]
  pub labels: HashMap<String, String>,

  #[serde(default)]
  pub description: String,

  #[serde(default)]
  pub environment: HashMap<String, String>,

  #[serde(default)]
  pub env_file: Vec<String>,
}

impl Task {
  pub fn run(&self, context: &mut TaskContext) -> anyhow::Result<()> {
    let started = Instant::now();

    let mut current_env = context.env_vars.clone();

    // Load environment variables from the task environment and env files field
    let defined_env = self.environment.clone();
    let additional_env = self.load_env_file()?;

    current_env.extend(defined_env);
    current_env.extend(additional_env);

    context.env_vars = current_env;

    let mut rng = rand::thread_rng();
    // Spinners can be found here:
    // https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json
    let pb_style =
      ProgressStyle::with_template("{spinner:.green} [{prefix:.bold.dim}] {wide_msg:.cyan/blue} ")?
        .tick_chars("⣾⣽⣻⢿⡿⣟⣯⣷");

    let depends_on_pb = context.multi.add(ProgressBar::new(self.depends_on.len() as u64));

    if !self.depends_on.is_empty() {
      depends_on_pb.set_style(pb_style.clone());
      depends_on_pb.set_message("Running task dependencies...");
      for (i, dependency) in self.depends_on.iter().enumerate() {
        thread::sleep(Duration::from_millis(rng.gen_range(40..300)));
        depends_on_pb.set_prefix(format!("{}/{}", i + 1, self.depends_on.len()));
        dependency.run(context)?;
        depends_on_pb.inc(1);
      }
      let message = format!("Dependencies completed in {}.", HumanDuration(started.elapsed()));

      if context.is_nested {
        depends_on_pb.finish_and_clear();
      } else {
        depends_on_pb.finish_with_message(message);
      }
    }

    let precondition_pb = context
      .multi
      .add(ProgressBar::new(self.preconditions.len() as u64));

    if !self.preconditions.is_empty() {
      precondition_pb.set_style(pb_style.clone());
      precondition_pb.set_message("Running task precondition...");
      for (i, precondition) in self.preconditions.iter().enumerate() {
        thread::sleep(Duration::from_millis(rng.gen_range(40..300)));
        precondition_pb.set_prefix(format!("{}/{}", i + 1, self.preconditions.len()));
        precondition.execute(context)?;
        precondition_pb.inc(1);
      }
      let message = format!("Preconditions completed in {}.", HumanDuration(started.elapsed()));

      if context.is_nested {
        precondition_pb.finish_and_clear();
      } else {
        precondition_pb.finish_with_message(message);
      }
    }

    let command_pb = context.multi.add(ProgressBar::new(self.commands.len() as u64));
    command_pb.set_style(pb_style);
    command_pb.set_message("Running task command...");
    for (i, command) in self.commands.iter().enumerate() {
      thread::sleep(Duration::from_millis(rng.gen_range(100..400)));
      command_pb.set_prefix(format!("{}/{}", i + 1, self.commands.len()));
      command.execute(context)?;
      command_pb.inc(1);
    }
    let message = format!("Commands completed in {}.", HumanDuration(started.elapsed()));

    if context.is_nested {
      command_pb.finish_and_clear();
    } else {
      command_pb.finish_with_message(message);
    }

    Ok(())
  }

  fn load_env_file(&self) -> anyhow::Result<HashMap<String, String>> {
    let mut local_env: HashMap<String, String> = HashMap::new();
    for env_file in &self.env_file {
      let contents =
        fs::read_to_string(env_file).with_context(|| format!("Failed to read env file: {}", env_file))?;

      for line in contents.lines() {
        if let Some((key, value)) = line.split_once('=') {
          local_env.insert(key.trim().to_string(), value.trim().to_string());
        }
      }
    }

    Ok(local_env)
  }
}

mod test {
  #[allow(unused_imports)]
  use super::*;

  #[test]
  fn test_task() {
    {
      let yaml = "
        commands:
          - command: echo \"Hello, World!\"
            ignore_errors: false
            verbose: false
        depends_on:
          - name: task1
        description: 'This is a task'
        labels: {}
        environment:
          FOO: bar
        env_file:
          - test.env
      ";

      let task = serde_yaml::from_str::<Task>(yaml).unwrap();

      if let CommandRunner::LocalRun {
        command,
        work_dir,
        shell,
        ignore_errors,
        verbose,
      } = &task.commands[0]
      {
        assert_eq!(command, "echo \"Hello, World!\"");
        assert_eq!(work_dir, &None);
        assert_eq!(shell, "sh");
        assert_eq!(ignore_errors, &false);
        assert_eq!(verbose, &false);
      }

      assert_eq!(task.depends_on[0].name, "task1");
      assert_eq!(task.labels.len(), 0);
      assert_eq!(task.description, "This is a task");
      assert_eq!(task.environment.len(), 1);
      assert_eq!(task.env_file.len(), 1);
    }
  }
}