summaryrefslogtreecommitdiffstats
path: root/crates/driver/src/recipe.rs
blob: f491ff6fce0e949623e69f06ecf3686cfa7237f8 (plain)
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
use std::{borrow::Cow, collections::HashMap, ffi::OsStr, fs::File, path::Path, result};

use scoped_tls_hkt::scoped_thread_local;
use serde::{Deserialize, Deserializer};
use walkdir::WalkDir;

use common::{error::*, types::*};

use crate::task::{RecipeMeta, TaskDef};

scoped_thread_local!(static CURRENT_RECIPE: str);

fn current_recipe() -> String {
	CURRENT_RECIPE.with(|current| current.to_string())
}

pub fn deserialize_task_id<'de, D>(deserializer: D) -> result::Result<TaskID, D::Error>
where
	D: Deserializer<'de>,
{
	#[derive(Deserialize)]
	struct RecipeTaskID {
		recipe: Option<String>,
		task: String,
	}
	let RecipeTaskID { recipe, task } = RecipeTaskID::deserialize(deserializer)?;
	Ok(TaskID {
		recipe: recipe.unwrap_or_else(current_recipe),
		task,
	})
}

#[derive(Debug, Deserialize)]
struct Recipe {
	#[serde(default)]
	pub meta: RecipeMeta,
	pub tasks: HashMap<String, TaskDef>,
}

fn read_recipe(path: &Path) -> Result<Recipe> {
	let f = File::open(path).context("IO error")?;

	let recipe: Recipe = serde_yaml::from_reader(f)
		.map_err(Error::new)
		.context("YAML error")?;

	Ok(recipe)
}

const RECIPE_NAME: &str = "build";
const RECIPE_PREFIX: &str = "build.";

fn recipe_name(path: &Path) -> Option<&str> {
	if path.extension() != Some("yml".as_ref()) {
		return None;
	}

	let stem = path.file_stem()?.to_str()?;
	if stem == RECIPE_NAME {
		return Some("");
	}
	stem.strip_prefix(RECIPE_PREFIX)
}

pub fn read_recipes<P: AsRef<Path>>(path: P) -> Result<HashMap<TaskID, Vec<TaskDef>>> {
	let mut tasks = HashMap::<TaskID, Vec<TaskDef>>::new();

	for entry in WalkDir::new(path)
		.sort_by_file_name()
		.into_iter()
		.filter_map(|e| e.ok())
	{
		let path = entry.path();
		if !path.is_file() {
			continue;
		}

		let Some(recipename) = recipe_name(path) else {
			continue;
		};
		let Some(basename) = path
			.parent()
			.and_then(Path::file_name)
			.and_then(OsStr::to_str)
		else {
			continue;
		};
		let base_recipename = if recipename.is_empty() {
			Cow::Borrowed(basename)
		} else {
			Cow::Owned(format!("{basename}/{recipename}"))
		};

		let recipe = CURRENT_RECIPE.set(&base_recipename, || read_recipe(path))?;

		let mut meta = recipe.meta;
		if meta.name.is_empty() {
			meta.name = basename.to_string();
		}

		for (label, mut task) in recipe.tasks {
			let task_id = TaskID {
				recipe: base_recipename.as_ref().to_owned(),
				task: label,
			};
			task.meta = meta.clone();
			tasks.entry(task_id).or_default().push(task);
		}
	}

	Ok(tasks)
}