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

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

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

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

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(Clone, Debug, Deserialize, Default)]
pub struct RecipeMeta {
	pub name: Option<String>,
	pub version: Option<String>,
}

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

#[derive(Debug, Deserialize)]
struct Subrecipe {
	pub tasks: HashMap<String, TaskDef>,
}

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

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

	Ok(value)
}

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)
}

fn handle_recipe_tasks(
	tasks: &mut HashMap<TaskID, Vec<TaskDef>>,
	recipe_tasks: HashMap<String, TaskDef>,
	meta: &TaskMeta,
) {
	for (label, mut task) in recipe_tasks {
		let task_id = TaskID {
			recipe: meta.recipe.clone(),
			task: label,
		};
		task.meta = meta.clone();
		tasks.entry(task_id).or_default().push(task);
	}
}

fn read_recipe_tasks(
	path: &Path,
	basename: &str,
	tasks: &mut HashMap<TaskID, Vec<TaskDef>>,
) -> Result<RecipeMeta> {
	let recipe_def = CURRENT_RECIPE.set(basename, || read_yaml::<Recipe>(path))?;

	let name = recipe_def
		.meta
		.name
		.as_deref()
		.unwrap_or(basename)
		.to_string();

	let meta = TaskMeta {
		basename: basename.to_string(),
		recipename: "".to_string(),
		recipe: basename.to_string(),
		name,
		version: recipe_def.meta.version.clone(),
	};

	handle_recipe_tasks(tasks, recipe_def.tasks, &meta);

	Ok(recipe_def.meta)
}

fn read_subrecipe_tasks(
	path: &Path,
	basename: &str,
	recipename: &str,
	recipe_meta: &RecipeMeta,
	tasks: &mut HashMap<TaskID, Vec<TaskDef>>,
) -> Result<()> {
	let recipe = format!("{basename}/{recipename}");
	let recipe_def = CURRENT_RECIPE.set(&recipe, || read_yaml::<Subrecipe>(path))?;

	let name = recipe_meta.name.as_deref().unwrap_or(basename).to_string();

	let meta = TaskMeta {
		basename: basename.to_string(),
		recipename: recipename.to_string(),
		recipe: recipe.clone(),
		name,
		version: recipe_meta.version.clone(),
	};

	handle_recipe_tasks(tasks, recipe_def.tasks, &meta);

	Ok(())
}

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

	for entry in WalkDir::new(path)
		.sort_by(|a, b| {
			// Files are sorted first by stem, then by extension, so that
			// recipe.yml will always be read before recipe.NAME.yml
			let stem_cmp = a.path().file_stem().cmp(&b.path().file_stem());
			let ext_cmp = a.path().extension().cmp(&b.path().extension());
			stem_cmp.then(ext_cmp)
		})
		.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;
		};

		if recipename.is_empty() {
			recipe_metas.insert(
				basename.to_string(),
				read_recipe_tasks(path, basename, &mut tasks)?,
			);
		} else {
			let Some(recipe_meta) = recipe_metas.get(basename) else {
				continue;
			};
			read_subrecipe_tasks(path, basename, recipename, recipe_meta, &mut tasks)?;
		}
	}

	Ok(tasks)
}