Skip to main content

mk_lib/schema/
mod.rs

1mod command;
2mod include;
3mod plan;
4mod precondition;
5mod shell;
6mod task;
7mod task_context;
8mod task_dependency;
9mod task_root;
10mod use_cargo;
11mod use_npm;
12mod validation;
13
14use std::collections::HashSet;
15use std::fmt;
16use std::process::Stdio;
17use std::sync::{
18  Arc,
19  Mutex,
20};
21
22use once_cell::sync::Lazy;
23use regex::Regex;
24
25pub type ActiveTasks = Arc<Mutex<HashSet<String>>>;
26pub type CompletedTasks = Arc<Mutex<HashSet<String>>>;
27
28#[derive(Debug)]
29pub struct ExecutionInterrupted;
30
31impl fmt::Display for ExecutionInterrupted {
32  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33    write!(f, "Execution interrupted")
34  }
35}
36
37impl std::error::Error for ExecutionInterrupted {}
38
39pub use command::*;
40pub use include::*;
41pub use plan::*;
42pub use precondition::*;
43pub use shell::*;
44pub use task::*;
45pub use task_context::*;
46pub use task_dependency::*;
47pub use task_root::*;
48pub use use_cargo::*;
49pub use use_npm::*;
50pub use validation::*;
51
52use crate::secrets::load_secret_value;
53
54static TEMPLATE_COMMAND_RE: Lazy<Regex> =
55  Lazy::new(|| Regex::new(r"^\$\{\{.+\}\}$").expect("valid template regex"));
56static TEMPLATE_EXPR_RE: Lazy<Regex> =
57  Lazy::new(|| Regex::new(r"\$\{\{\s*(.+?)\s*\}\}").expect("valid template expression regex"));
58
59pub fn is_shell_command(value: &str) -> anyhow::Result<bool> {
60  let re = Regex::new(r"^\$\(.+\)$")?;
61  Ok(re.is_match(value))
62}
63
64pub fn is_template_command(value: &str) -> anyhow::Result<bool> {
65  Ok(TEMPLATE_COMMAND_RE.is_match(value))
66}
67
68pub fn resolve_template_command_value(value: &str, context: &TaskContext) -> anyhow::Result<String> {
69  let value = value.trim_start_matches("${{").trim_end_matches("}}").trim();
70  resolve_template_expression(value, context)
71}
72
73pub fn resolve_template_expression(value: &str, context: &TaskContext) -> anyhow::Result<String> {
74  if value.starts_with("env.") {
75    let value = value.trim_start_matches("env.");
76    let value = context
77      .env_vars
78      .get(value)
79      .ok_or_else(|| anyhow::anyhow!("Failed to find environment variable"))?;
80    Ok(value.to_string())
81  } else if value.starts_with("secrets.") {
82    let path = value.trim_start_matches("secrets.");
83    load_secret_value(
84      path,
85      &context.task_root.config_base_dir(),
86      context.secret_vault_location.as_deref(),
87      context.secret_keys_location.as_deref(),
88      context.secret_key_name.as_deref(),
89      context.secret_gpg_key_id.as_deref(),
90    )
91  } else if value.starts_with("outputs.") {
92    let name = value.trim_start_matches("outputs.");
93    context
94      .get_task_output(name)?
95      .ok_or_else(|| anyhow::anyhow!("Failed to find task output - {}", name))
96  } else {
97    Ok(value.to_string())
98  }
99}
100
101pub fn interpolate_template_string(value: &str, context: &TaskContext) -> anyhow::Result<String> {
102  let mut result = String::with_capacity(value.len());
103  let mut last_end = 0usize;
104  for captures in TEMPLATE_EXPR_RE.captures_iter(value) {
105    let Some(full_match) = captures.get(0) else {
106      continue;
107    };
108    let Some(expr) = captures.get(1) else {
109      continue;
110    };
111    result.push_str(&value[last_end..full_match.start()]);
112    result.push_str(&resolve_template_expression(expr.as_str().trim(), context)?);
113    last_end = full_match.end();
114  }
115  result.push_str(&value[last_end..]);
116  Ok(result)
117}
118
119pub fn extract_output_references(value: &str) -> Vec<String> {
120  TEMPLATE_EXPR_RE
121    .captures_iter(value)
122    .filter_map(|captures| captures.get(1))
123    .map(|expr| expr.as_str().trim())
124    .filter_map(|expr| expr.strip_prefix("outputs."))
125    .map(str::to_string)
126    .collect()
127}
128
129pub fn contains_output_reference(value: &str) -> bool {
130  !extract_output_references(value).is_empty()
131}
132
133pub fn get_output_handler(verbose: bool) -> Stdio {
134  if verbose {
135    Stdio::piped()
136  } else {
137    Stdio::null()
138  }
139}
140
141#[cfg(test)]
142mod test {
143  use std::sync::Arc;
144
145  use super::*;
146
147  #[test]
148  fn test_interpolate_template_string_resolves_outputs() -> anyhow::Result<()> {
149    let root = Arc::new(TaskRoot::default());
150    let context = TaskContext::empty_with_root(root);
151    context.insert_task_output("version", "v1.2.3")?;
152    assert_eq!(
153      interpolate_template_string("tag=${{ outputs.version }}", &context)?,
154      "tag=v1.2.3"
155    );
156    Ok(())
157  }
158
159  #[test]
160  fn test_extract_output_references_finds_all_output_templates() {
161    assert_eq!(
162      extract_output_references("${{ outputs.first }}-${{ outputs.second }}"),
163      vec!["first".to_string(), "second".to_string()]
164    );
165  }
166}