mk_lib/schema/
task_root.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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
use anyhow::Context;
use hashbrown::HashMap;
use mlua::{
  Lua,
  LuaSerdeExt,
};
use serde::Deserialize;

use std::fs::File;
use std::io::{
  BufReader,
  Read as _,
};
use std::path::Path;

use super::{
  Include,
  Task,
  UseCargo,
  UseNpm,
};

const MK_COMMANDS: [&str; 5] = ["run", "list", "completion", "secrets", "help"];

macro_rules! process_tasks {
  ($root:expr, $mk_commands:expr) => {
    // Rename tasks that have the same name as mk commands
    $root.tasks = rename_tasks($root.tasks, "task", &$mk_commands, &HashMap::new());

    if let Some(npm) = &$root.use_npm {
      let npm_tasks = npm.capture()?;

      // Rename tasks that have the same name as mk commands and existing tasks
      let renamed_npm_tasks = rename_tasks(npm_tasks, "npm", &$mk_commands, &$root.tasks);

      $root.tasks.extend(renamed_npm_tasks);
    }
  };
}

/// This struct represents the root of the task schema. It contains all the tasks
/// that can be executed.
#[derive(Debug, Default, Deserialize)]
pub struct TaskRoot {
  /// The tasks that can be executed
  pub tasks: HashMap<String, Task>,

  /// This allows mk to use npm scripts as tasks
  #[serde(default)]
  pub use_npm: Option<UseNpm>,

  /// This allows mk to use cargo commands as tasks
  #[serde(default)]
  pub use_cargo: Option<UseCargo>,

  /// Includes additional files to be merged into the current file
  #[serde(default)]
  pub include: Option<Vec<Include>>,
}

impl TaskRoot {
  pub fn from_file(file: &str) -> anyhow::Result<Self> {
    let file_path = Path::new(file);
    let file_extension = file_path
      .extension()
      .and_then(|ext| ext.to_str())
      .context("Failed to get file extension")?;

    match file_extension {
      "yaml" | "yml" => load_yaml_file(file),
      "lua" => load_lua_file(file),
      "json" => load_json_file(file),
      "json5" => anyhow::bail!("JSON5 files are not supported yet"),
      "toml" => anyhow::bail!("TOML files are not supported yet"),
      "makefile" | "mk" => anyhow::bail!("Makefiles are not supported yet"),
      _ => anyhow::bail!("Unsupported file extension - {}", file_extension),
    }
  }

  pub fn from_hashmap(tasks: HashMap<String, Task>) -> Self {
    Self {
      tasks,
      use_npm: None,
      use_cargo: None,
      include: None,
    }
  }
}

fn load_yaml_file(file: &str) -> anyhow::Result<TaskRoot> {
  let file = File::open(file).with_context(|| format!("Failed to open file - {}", file))?;
  let reader = BufReader::new(file);

  // Deserialize the YAML file into a serde_yaml::Value to be able to merge
  // anchors and aliases
  let mut value: serde_yaml::Value = serde_yaml::from_reader(reader)?;
  value.apply_merge()?;

  // Deserialize the serde_yaml::Value into a TaskRoot
  let mut root: TaskRoot = serde_yaml::from_value(value)?;

  process_tasks!(root, MK_COMMANDS);

  Ok(root)
}

fn load_json_file(file: &str) -> anyhow::Result<TaskRoot> {
  let file = File::open(file).with_context(|| format!("Failed to open file - {}", file))?;
  let reader = BufReader::new(file);

  // Deserialize the YAML file into a serde_yaml::Value to be able to merge
  // anchors and aliases
  let mut value: serde_yaml::Value = serde_yaml::from_reader(reader)?;
  value.apply_merge()?;

  // Deserialize the serde_yaml::Value into a TaskRoot
  let mut root: TaskRoot = serde_yaml::from_value(value)?;

  process_tasks!(root, MK_COMMANDS);

  Ok(root)
}

fn load_lua_file(file: &str) -> anyhow::Result<TaskRoot> {
  let mut file = File::open(file).with_context(|| format!("Failed to open file - {}", file))?;
  let mut contents = String::new();
  file.read_to_string(&mut contents)?;

  let lua = Lua::new();

  let value = lua.load(&contents).eval()?;
  let mut root: TaskRoot = lua.from_value(value)?;

  process_tasks!(root, MK_COMMANDS);

  Ok(root)
}

fn rename_tasks(
  tasks: HashMap<String, Task>,
  prefix: &str,
  mk_commands: &[&str],
  existing_tasks: &HashMap<String, Task>,
) -> HashMap<String, Task> {
  let mut new_tasks = HashMap::new();
  for (task_name, task) in tasks.into_iter() {
    let new_task_name =
      if mk_commands.contains(&task_name.as_str()) || existing_tasks.contains_key(&task_name) {
        format!("{}_{}", prefix, task_name)
      } else {
        task_name
      };

    new_tasks.insert(new_task_name, task);
  }
  new_tasks
}

#[cfg(test)]
mod test {
  use super::*;
  use crate::schema::{
    CommandRunner,
    TaskDependency,
  };

  #[test]
  fn test_task_root_1() -> anyhow::Result<()> {
    let yaml = "
      tasks:
        task1:
          commands:
            - command: echo \"Hello, World 1!\"
              ignore_errors: false
              verbose: false
          depends_on:
            - name: task2
          description: 'This is a task'
          labels: {}
          environment:
            FOO: bar
          env_file:
            - test.env
        task2:
          commands:
            - command: echo \"Hello, World 2!\"
              ignore_errors: false
              verbose: false
          depends_on:
            - name: task1
          description: 'This is a task'
          labels: {}
          environment: {}
        task3:
          commands:
            - command: echo \"Hello, World 3!\"
              ignore_errors: false
              verbose: false
    ";

    let task_root = serde_yaml::from_str::<TaskRoot>(yaml)?;

    assert_eq!(task_root.tasks.len(), 3);

    if let Task::Task(task) = &task_root.tasks["task1"] {
      if let CommandRunner::LocalRun(local_run) = &task.commands[0] {
        assert_eq!(local_run.command, "echo \"Hello, World 1!\"");
        assert_eq!(local_run.work_dir, None);
        assert_eq!(local_run.shell, "sh");
        assert_eq!(local_run.ignore_errors, Some(false));
        assert_eq!(local_run.verbose, Some(false));
      } else {
        panic!("Expected CommandRunner::LocalRun");
      }

      if let TaskDependency::TaskDependency(args) = &task.depends_on[0] {
        assert_eq!(args.name, "task2");
      } else {
        panic!("Expected TaskDependency::TaskDependency");
      }
      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);
    } else {
      panic!("Expected Task::Task");
    }

    if let Task::Task(task) = &task_root.tasks["task2"] {
      if let CommandRunner::LocalRun(local_run) = &task.commands[0] {
        assert_eq!(local_run.command, "echo \"Hello, World 2!\"");
        assert_eq!(local_run.work_dir, None);
        assert_eq!(local_run.shell, "sh");
        assert_eq!(local_run.ignore_errors, Some(false));
        assert_eq!(local_run.verbose, Some(false));
      } else {
        panic!("Expected CommandRunner::LocalRun");
      }

      if let TaskDependency::TaskDependency(args) = &task.depends_on[0] {
        assert_eq!(args.name, "task1");
      } else {
        panic!("Expected TaskDependency::TaskDependency");
      }
      assert_eq!(task.labels.len(), 0);
      assert_eq!(task.description, "This is a task");
      assert_eq!(task.environment.len(), 0);
      assert_eq!(task.env_file.len(), 0);
    } else {
      panic!("Expected Task::Task");
    }

    if let Task::Task(task) = &task_root.tasks["task3"] {
      if let CommandRunner::LocalRun(local_run) = &task.commands[0] {
        assert_eq!(local_run.command, "echo \"Hello, World 3!\"");
        assert_eq!(local_run.work_dir, None);
        assert_eq!(local_run.shell, "sh");
        assert_eq!(local_run.ignore_errors, Some(false));
        assert_eq!(local_run.verbose, Some(false));
      } else {
        panic!("Expected CommandRunner::LocalRun");
      }

      assert_eq!(task.depends_on.len(), 0);
      assert_eq!(task.labels.len(), 0);
      assert_eq!(task.description.len(), 0);
      assert_eq!(task.environment.len(), 0);
      assert_eq!(task.env_file.len(), 0);
    } else {
      panic!("Expected Task::Task");
    }

    Ok(())
  }

  #[test]
  fn test_task_root_2() -> anyhow::Result<()> {
    let yaml = "
      tasks:
        task1:
          commands:
            - command: echo \"Hello, World 1!\"
        task2:
          commands:
            - echo \"Hello, World 2!\"
        task3: echo \"Hello, World 3!\"
    ";

    let task_root = serde_yaml::from_str::<TaskRoot>(yaml)?;

    assert_eq!(task_root.tasks.len(), 3);

    if let Task::Task(task) = &task_root.tasks["task1"] {
      if let CommandRunner::LocalRun(local_run) = &task.commands[0] {
        assert_eq!(local_run.command, "echo \"Hello, World 1!\"");
        assert_eq!(local_run.work_dir, None);
        assert_eq!(local_run.shell, "sh");
        assert_eq!(local_run.ignore_errors, None);
        assert_eq!(local_run.verbose, None);
      } else {
        panic!("Expected CommandRunner::LocalRun");
      }

      assert_eq!(task.labels.len(), 0);
      assert_eq!(task.description, "");
      assert_eq!(task.environment.len(), 0);
      assert_eq!(task.env_file.len(), 0);
    } else {
      panic!("Expected Task::Task");
    }

    if let Task::Task(task) = &task_root.tasks["task2"] {
      if let CommandRunner::CommandRun(command) = &task.commands[0] {
        assert_eq!(command, "echo \"Hello, World 2!\"");
      } else {
        panic!("Expected CommandRunner::CommandRun");
      }

      assert_eq!(task.labels.len(), 0);
      assert_eq!(task.description, "");
      assert_eq!(task.environment.len(), 0);
      assert_eq!(task.env_file.len(), 0);
    } else {
      panic!("Expected Task::Task");
    }

    if let Task::String(command) = &task_root.tasks["task3"] {
      assert_eq!(command, "echo \"Hello, World 3!\"");
    } else {
      panic!("Expected Task::String");
    }

    Ok(())
  }

  #[test]
  fn test_task_root_3() -> anyhow::Result<()> {
    let yaml = "
      tasks:
        task1: echo \"Hello, World 1!\"
        task2: echo \"Hello, World 2!\"
        task3: echo \"Hello, World 3!\"
    ";

    let task_root = serde_yaml::from_str::<TaskRoot>(yaml)?;

    assert_eq!(task_root.tasks.len(), 3);

    if let Task::String(command) = &task_root.tasks["task1"] {
      assert_eq!(command, "echo \"Hello, World 1!\"");
    } else {
      panic!("Expected Task::String");
    }

    if let Task::String(command) = &task_root.tasks["task2"] {
      assert_eq!(command, "echo \"Hello, World 2!\"");
    } else {
      panic!("Expected Task::String");
    }

    if let Task::String(command) = &task_root.tasks["task3"] {
      assert_eq!(command, "echo \"Hello, World 3!\"");
    } else {
      panic!("Expected Task::String");
    }

    Ok(())
  }
}