mk 0.7.12

Yet another simple task runner 🦀
Documentation
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::atomic::{
  AtomicBool,
  Ordering,
};
use std::sync::{
  Arc,
  Mutex,
};

use hashbrown::HashMap;
use indicatif::{
  MultiProgress,
  ProgressDrawTarget,
};
use serde::Serialize;

use crate::cache::CacheStore;
use crate::defaults::{
  default_ignore_errors,
  default_shell,
  default_verbose,
};
use crate::secrets::SecretConfig;

use super::{
  ActiveTasks,
  CompletedTasks,
  ContainerRuntime,
  Shell,
  TaskRoot,
};

/// Used to pass information to tasks
/// This use arc to allow for sharing of data between tasks
/// and allow parallel runs of tasks
#[derive(Clone)]
pub struct TaskContext {
  pub task_root: Arc<TaskRoot>,
  pub active_tasks: ActiveTasks,
  pub completed_tasks: CompletedTasks,
  pub multi: Arc<MultiProgress>,
  pub env_vars: HashMap<String, String>,
  pub task_outputs: Arc<Mutex<HashMap<String, String>>>,
  pub secret_config: Option<SecretConfig>,
  pub shell: Option<Arc<Shell>>,
  pub container_runtime: Option<ContainerRuntime>,
  pub ignore_errors: Option<bool>,
  pub verbose: Option<bool>,
  pub force: bool,
  pub json_events: bool,
  pub is_nested: bool,
  pub cache_store: Arc<Mutex<CacheStore>>,
  pub current_task_name: Option<String>,
  pub cancellation_requested: Arc<AtomicBool>,
}

impl TaskContext {
  pub fn empty() -> Self {
    let mp = MultiProgress::with_draw_target(ProgressDrawTarget::hidden());
    Self {
      task_root: Arc::new(TaskRoot::default()),
      active_tasks: Arc::new(Mutex::new(HashSet::new())),
      completed_tasks: Arc::new(Mutex::new(HashSet::new())),
      multi: Arc::new(mp),
      env_vars: HashMap::new(),
      task_outputs: Arc::new(Mutex::new(HashMap::new())),
      secret_config: None,
      shell: None,
      container_runtime: None,
      ignore_errors: None,
      verbose: None,
      force: false,
      json_events: false,
      is_nested: false,
      cache_store: Arc::new(Mutex::new(CacheStore::default())),
      current_task_name: None,
      cancellation_requested: Arc::new(AtomicBool::new(false)),
    }
  }

  pub fn empty_with_root(task_root: Arc<TaskRoot>) -> Self {
    let mp = MultiProgress::with_draw_target(ProgressDrawTarget::hidden());
    Self {
      task_root: task_root.clone(),
      active_tasks: Arc::new(Mutex::new(HashSet::new())),
      completed_tasks: Arc::new(Mutex::new(HashSet::new())),
      multi: Arc::new(mp),
      env_vars: HashMap::new(),
      task_outputs: Arc::new(Mutex::new(HashMap::new())),
      secret_config: None,
      shell: None,
      container_runtime: None,
      ignore_errors: None,
      verbose: None,
      force: false,
      json_events: false,
      is_nested: false,
      cache_store: Arc::new(Mutex::new(CacheStore::default())),
      current_task_name: None,
      cancellation_requested: Arc::new(AtomicBool::new(false)),
    }
  }

  pub fn new(task_root: Arc<TaskRoot>) -> Self {
    let cache_store = CacheStore::load_in_dir(&task_root.cache_base_dir()).unwrap_or_default();
    Self {
      task_root: task_root.clone(),
      active_tasks: Arc::new(Mutex::new(HashSet::new())),
      completed_tasks: Arc::new(Mutex::new(HashSet::new())),
      multi: Arc::new(MultiProgress::new()),
      env_vars: HashMap::new(),
      task_outputs: Arc::new(Mutex::new(HashMap::new())),
      secret_config: None,
      shell: None,
      container_runtime: task_root.container_runtime.clone(),
      ignore_errors: None,
      verbose: None,
      force: false,
      json_events: false,
      is_nested: false,
      cache_store: Arc::new(Mutex::new(cache_store)),
      current_task_name: None,
      cancellation_requested: Arc::new(AtomicBool::new(false)),
    }
  }

  pub fn new_with_options(task_root: Arc<TaskRoot>, force: bool, json_events: bool) -> Self {
    let cache_store = CacheStore::load_in_dir(&task_root.cache_base_dir()).unwrap_or_default();
    let multi = if json_events {
      Arc::new(MultiProgress::with_draw_target(ProgressDrawTarget::hidden()))
    } else {
      Arc::new(MultiProgress::new())
    };
    Self {
      task_root: task_root.clone(),
      active_tasks: Arc::new(Mutex::new(HashSet::new())),
      completed_tasks: Arc::new(Mutex::new(HashSet::new())),
      multi,
      env_vars: HashMap::new(),
      task_outputs: Arc::new(Mutex::new(HashMap::new())),
      secret_config: None,
      shell: None,
      container_runtime: task_root.container_runtime.clone(),
      ignore_errors: None,
      verbose: None,
      force,
      json_events,
      is_nested: false,
      cache_store: Arc::new(Mutex::new(cache_store)),
      current_task_name: None,
      cancellation_requested: Arc::new(AtomicBool::new(false)),
    }
  }

  pub fn from_context(context: &TaskContext) -> Self {
    Self {
      task_root: context.task_root.clone(),
      active_tasks: context.active_tasks.clone(),
      completed_tasks: context.completed_tasks.clone(),
      multi: context.multi.clone(),
      env_vars: context.env_vars.clone(),
      task_outputs: Arc::new(Mutex::new(HashMap::new())),
      secret_config: context.secret_config.clone(),
      shell: context.shell.clone(),
      container_runtime: context.container_runtime.clone(),
      ignore_errors: context.ignore_errors,
      verbose: context.verbose,
      force: context.force,
      json_events: context.json_events,
      is_nested: true,
      cache_store: context.cache_store.clone(),
      current_task_name: context.current_task_name.clone(),
      cancellation_requested: context.cancellation_requested.clone(),
    }
  }

  pub fn from_context_with_args(context: &TaskContext, ignore_errors: bool, verbose: bool) -> Self {
    Self {
      task_root: context.task_root.clone(),
      active_tasks: context.active_tasks.clone(),
      completed_tasks: context.completed_tasks.clone(),
      multi: context.multi.clone(),
      env_vars: context.env_vars.clone(),
      task_outputs: Arc::new(Mutex::new(HashMap::new())),
      secret_config: context.secret_config.clone(),
      shell: context.shell.clone(),
      container_runtime: context.container_runtime.clone(),
      ignore_errors: Some(ignore_errors),
      verbose: Some(verbose),
      force: context.force,
      json_events: context.json_events,
      is_nested: true,
      cache_store: context.cache_store.clone(),
      current_task_name: context.current_task_name.clone(),
      cancellation_requested: context.cancellation_requested.clone(),
    }
  }

  pub fn extend_env_vars<I>(&mut self, iter: I)
  where
    I: IntoIterator<Item = (String, String)>,
  {
    self.env_vars.extend(iter);
  }

  pub fn set_shell(&mut self, shell: &Shell) {
    let shell = Arc::new(Shell::from_shell(shell));
    self.shell = Some(shell);
  }

  pub fn set_secret_config(&mut self, secret_config: SecretConfig) {
    self.secret_config = Some(secret_config);
  }

  pub fn set_container_runtime(&mut self, runtime: &ContainerRuntime) {
    self.container_runtime = Some(runtime.clone());
  }

  pub fn set_ignore_errors(&mut self, ignore_errors: bool) {
    self.ignore_errors = Some(ignore_errors);
  }

  pub fn set_verbose(&mut self, verbose: bool) {
    self.verbose = Some(verbose);
  }

  pub fn insert_task_output(&self, name: impl Into<String>, value: impl Into<String>) -> anyhow::Result<()> {
    let name = name.into();
    let mut outputs = self
      .task_outputs
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock task outputs - {}", e))?;
    if outputs.contains_key(&name) {
      anyhow::bail!("Task output already exists - {}", name);
    }
    outputs.insert(name, value.into());
    Ok(())
  }

  pub fn get_task_output(&self, name: &str) -> anyhow::Result<Option<String>> {
    let outputs = self
      .task_outputs
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock task outputs - {}", e))?;
    Ok(outputs.get(name).cloned())
  }

  pub fn has_task_output(&self, name: &str) -> anyhow::Result<bool> {
    let outputs = self
      .task_outputs
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock task outputs - {}", e))?;
    Ok(outputs.contains_key(name))
  }

  pub fn shell(&self) -> Arc<Shell> {
    self.shell.clone().unwrap_or_else(|| Arc::new(default_shell()))
  }

  pub fn ignore_errors(&self) -> bool {
    self.ignore_errors.unwrap_or(default_ignore_errors())
  }

  pub fn verbose(&self) -> bool {
    self.verbose.unwrap_or(default_verbose())
  }

  pub fn is_task_active(&self, task_name: &str) -> anyhow::Result<bool> {
    let active = self
      .active_tasks
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock active tasks - {}", e))?;
    Ok(active.contains(task_name))
  }

  pub fn is_task_completed(&self, task_name: &str) -> anyhow::Result<bool> {
    let completed = self
      .completed_tasks
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock completed tasks - {}", e))?;
    Ok(completed.contains(task_name))
  }

  pub fn mark_task_active(&self, task_name: &str) -> anyhow::Result<()> {
    let mut active = self
      .active_tasks
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock active tasks - {}", e))?;
    active.insert(task_name.to_string());
    Ok(())
  }

  pub fn unmark_task_active(&self, task_name: &str) -> anyhow::Result<()> {
    let mut active = self
      .active_tasks
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock active tasks - {}", e))?;
    active.remove(task_name);
    Ok(())
  }

  pub fn mark_task_complete(&self, task_name: &str) -> anyhow::Result<()> {
    let mut completed = self
      .completed_tasks
      .lock()
      .map_err(|e| anyhow::anyhow!("Failed to lock completed tasks - {}", e))?;
    completed.insert(task_name.to_string());
    Ok(())
  }

  pub fn emit_event<T: Serialize>(&self, value: &T) -> anyhow::Result<()> {
    if self.json_events {
      println!("{}", serde_json::to_string(value)?);
    }
    Ok(())
  }

  pub fn set_current_task_name(&mut self, task_name: &str) {
    self.current_task_name = Some(task_name.to_string());
  }

  pub fn request_cancellation(&self) {
    self.cancellation_requested.store(true, Ordering::SeqCst);
  }

  pub fn cancellation_requested(&self) -> bool {
    self.cancellation_requested.load(Ordering::SeqCst)
  }

  pub fn clear_cancellation(&self) {
    self.cancellation_requested.store(false, Ordering::SeqCst);
  }

  pub fn resolve_from_config(&self, value: &str) -> PathBuf {
    self.task_root.resolve_from_config(value)
  }
}

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

  #[test]
  fn test_task_context_1() -> anyhow::Result<()> {
    {
      let context = TaskContext::empty();
      let expected = if cfg!(windows) { "cmd" } else { "sh" };
      assert_eq!(context.shell().cmd(), expected.to_string());
      assert!(!context.ignore_errors());
      assert!(context.verbose());
    }

    Ok(())
  }

  #[test]
  fn test_task_context_2() -> anyhow::Result<()> {
    {
      let mut context = TaskContext::empty();
      context.set_shell(&Shell::String("bash".to_string()));
      assert_eq!(context.shell().cmd(), "bash".to_string());
    }

    Ok(())
  }

  #[test]
  fn test_task_context_3() -> anyhow::Result<()> {
    {
      let mut context = TaskContext::empty();
      context.extend_env_vars(vec![("key".to_string(), "value".to_string())]);
      assert_eq!(context.env_vars.get("key"), Some(&"value".to_string()));
    }

    Ok(())
  }

  #[test]
  fn test_task_context_4() -> anyhow::Result<()> {
    {
      let mut context = TaskContext::empty();
      context.set_ignore_errors(true);
      assert!(context.ignore_errors());
    }

    Ok(())
  }

  #[test]
  fn test_task_context_5() -> anyhow::Result<()> {
    {
      let mut context = TaskContext::empty();
      context.set_verbose(true);
      assert!(context.verbose());
    }

    Ok(())
  }

  #[test]
  fn test_task_context_outputs_are_stored() -> anyhow::Result<()> {
    let context = TaskContext::empty();
    context.insert_task_output("tag", "v1.0.0")?;
    assert_eq!(context.get_task_output("tag")?, Some("v1.0.0".to_string()));
    assert!(context.has_task_output("tag")?);
    Ok(())
  }
}