1mod address;
5mod bindings;
6pub(crate) mod capture;
7pub(crate) mod codec;
8pub(crate) mod collection;
9mod composition;
10pub(crate) mod declaration;
11mod definitions;
12mod document;
13pub(crate) mod figure;
14mod keys;
15pub(crate) mod plot_input;
16mod readers;
17pub(crate) mod resolve;
18mod run;
19pub(crate) mod schema;
20mod source;
21pub(crate) mod style;
22mod template;
23mod text;
24pub(crate) mod theme;
25
26use std::path::{Path, PathBuf};
27
28pub use crate::data::BindingSelector;
29pub use bindings::{
30 BindingArguments, BindingColumnType, BindingField, BindingInput, BindingObject, Bindings,
31};
32pub use composition::RecipeDocument;
33pub use declaration::{BindingRequirement, BindingValueType};
34pub use figure::RecipeFigure;
35pub use run::{OutputDeclaration, RunAction, RunOptions, RunResult};
36pub use source::{BindingSource, BindingSourceInput};
37pub use style::StyleSource;
38
39use toml_edit::{DocumentMut, InlineTable, Item, Table, Value};
40
41use crate::{
42 operation::{self, OperationOptions},
43 Result, Theme,
44};
45
46use codec::{invalid, Codec};
47
48pub const RECIPE_VERSION: &str = "0.3.0";
51
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54pub enum PlotRecipeScope {
55 #[default]
57 Full,
58 Style,
60}
61
62#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
64pub enum CanvasRecipeScope {
65 #[default]
67 Full,
68 Style,
70 Layout,
72}
73
74#[derive(Debug, Clone)]
79pub struct Recipe {
80 document: DocumentMut,
81 base: PathBuf,
82 bindings: Vec<BindingInfo>,
83 warnings: Vec<RecipeWarning>,
84}
85
86#[derive(Debug, Clone)]
88pub struct BindingInfo {
89 name: String,
90 source: Option<BindingSource>,
91 requirements: Vec<BindingRequirement>,
92}
93impl BindingInfo {
94 pub fn name(&self) -> &str {
96 &self.name
97 }
98 pub fn source(&self) -> Option<&BindingSource> {
100 self.source.as_ref()
101 }
102 pub fn requirements(&self) -> &[BindingRequirement] {
104 &self.requirements
105 }
106}
107
108#[derive(Debug, Clone)]
110pub struct RecipeWarning {
111 field: String,
112 binding: String,
113 reason: String,
114}
115impl RecipeWarning {
116 pub(crate) fn new(field: &str, binding: &str, reason: &str) -> Self {
117 Self {
118 field: field.to_owned(),
119 binding: binding.to_owned(),
120 reason: reason.to_owned(),
121 }
122 }
123 pub fn field(&self) -> &str {
125 &self.field
126 }
127 pub fn binding(&self) -> &str {
129 &self.binding
130 }
131 pub fn reason(&self) -> &str {
133 &self.reason
134 }
135}
136
137impl Recipe {
138 fn from_theme(theme: &Theme) -> Self {
139 let mut document = DocumentMut::new();
140 document["recipe_version"] = toml_edit::value(RECIPE_VERSION);
141 let toml_edit::Value::InlineTable(value) = theme.encode() else {
142 unreachable!("complete theme table")
143 };
144 document["theme"] = Item::Table(section(value));
145 Self {
146 document,
147 base: PathBuf::new(),
148 bindings: Vec::new(),
149 warnings: Vec::new(),
150 }
151 }
152
153 pub fn read(path: impl AsRef<Path>) -> Result<Self> {
155 Self::read_with_operation(path, &OperationOptions::default())
156 }
157
158 pub fn read_with_operation(path: impl AsRef<Path>, options: &OperationOptions) -> Result<Self> {
160 operation::run(options, || Self::read_document(path.as_ref()))
161 }
162
163 pub(crate) fn read_document(path: &Path) -> Result<Self> {
164 let source = operation::external(|| std::fs::read_to_string(path))?;
165 operation::checkpoint()?;
166 let document = source
167 .parse::<DocumentMut>()
168 .map_err(|error| invalid(format!("recipe {}: {error}", path.display())))?;
169 let (bindings, warnings) = Self::inventory(&document)
170 .map_err(|error| error.with_prefix(&format!("recipe {}", path.display())))?;
171 let absolute = std::path::absolute(path)?;
172 let base = absolute
173 .parent()
174 .ok_or_else(|| invalid("recipe path has no directory"))?
175 .to_owned();
176 Ok(Self {
177 document,
178 base,
179 bindings,
180 warnings,
181 })
182 }
183
184 pub fn theme(&self) -> Result<Theme> {
187 let value = self
188 .document
189 .get("theme")
190 .ok_or_else(|| invalid("recipe has no independent theme"))?;
191 Theme::decode(value, None).map_err(|error| error.with_prefix("theme"))
192 }
193
194 pub fn write(&self, path: impl AsRef<Path>) -> Result<()> {
196 self.write_with_operation(path, &OperationOptions::default())
197 }
198
199 pub fn write_with_operation(
201 &self,
202 path: impl AsRef<Path>,
203 options: &OperationOptions,
204 ) -> Result<()> {
205 operation::run(options, || self.write_document(path.as_ref()))
206 }
207
208 pub(crate) fn write_document(&self, path: &Path) -> Result<()> {
209 let document = self.document_for_path(path)?;
210 let source = document.to_string();
211 operation::checkpoint()?;
212 crate::orchestrator::write_atomic(path, source.as_bytes())
213 }
214}
215
216fn section(value: InlineTable) -> Table {
219 let mut table = Table::new();
220 for (key, value) in value {
221 let item = match value {
222 Value::InlineTable(value) if !atomic_table(&value) => Item::Table(section(value)),
223 value => Item::Value(value),
224 };
225 table.insert(&key, item);
226 }
227 table
228}
229
230fn atomic_table(value: &InlineTable) -> bool {
231 value.contains_key("rgb")
232 || value.contains_key("numerator")
233 || ["em", "px", "short_side"]
234 .iter()
235 .any(|name| value.contains_key(name))
236}
237
238impl Theme {
239 pub fn get_recipe(&self) -> Result<Recipe> {
241 self.get_recipe_with_operation(&OperationOptions::default())
242 }
243
244 pub fn get_recipe_with_operation(&self, options: &OperationOptions) -> Result<Recipe> {
246 operation::run(options, || {
247 let recipe = Recipe::from_theme(self);
248 operation::checkpoint()?;
249 Ok(recipe)
250 })
251 }
252
253 pub fn recipe(&self, path: impl AsRef<Path>) -> Result<Recipe> {
255 self.recipe_with_operation(path, &OperationOptions::default())
256 }
257
258 pub fn recipe_with_operation(
260 &self,
261 path: impl AsRef<Path>,
262 options: &OperationOptions,
263 ) -> Result<Recipe> {
264 operation::run(options, || {
265 let recipe = Recipe::from_theme(self);
266 recipe.write_document(path.as_ref())?;
267 Ok(recipe)
268 })
269 }
270}