diff options
| author | P-Andersson <pierre.andersson01@gmail.com> | 2023-04-01 14:33:42 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-04-01 14:33:42 +0200 |
| commit | 387bcc3879dbcfac17b215acd9a6b29fe400a016 (patch) | |
| tree | f40fb672d8f67bf55a68626c4c4f6f9ab247516c /library/src/compute | |
| parent | 9e69a7b161191992f336c09ec711a1e1c9768633 (diff) | |
add support for loading data from yaml files (#447)
Diffstat (limited to 'library/src/compute')
| -rw-r--r-- | library/src/compute/data.rs | 90 |
1 files changed, 90 insertions, 0 deletions
diff --git a/library/src/compute/data.rs b/library/src/compute/data.rs index 0c17972d..c2dc632b 100644 --- a/library/src/compute/data.rs +++ b/library/src/compute/data.rs @@ -207,6 +207,96 @@ fn format_json_error(error: serde_json::Error) -> String { format!("failed to parse json file: syntax error in line {}", error.line()) } +/// Read structured data from a YAML file. +/// +/// The file must contain a valid YAML object or array. YAML mappings will be +/// converted into Typst dictionaries, and YAML sequences will be converted into +/// Typst arrays. Strings and booleans will be converted into the Typst +/// equivalents, null-values (`null`, `~` or empty ``) will be converted into +/// `{none}`, and numbers will be converted to floats or integers depending on +/// whether they are whole numbers. +/// +/// Note that mapping keys that are not a string cause the entry to be +/// discarded. +/// +/// Custom YAML tags are ignored, though the loaded value will still be +/// present. +/// +/// The function returns a dictionary or value or an array, depending on +/// the YAML file. +/// +/// The YAML files in the example contain objects with authors as keys, +/// each with a sequence of their own submapping with the keys +/// "title" and "published" +/// +/// ## Example +/// ```example +/// #let bookshelf(contents) = { +/// for author, works in contents { +/// author +/// for work in works [ +/// - #work.title (#work.published) +/// ] +/// } +/// } +/// +/// #bookshelf(yaml("scifi-authors.yaml")) +/// ``` +/// +/// Display: YAML +/// Category: data-loading +/// Returns: array or value or dictionary +#[func] +pub fn yaml( + /// Path to a YAML file. + path: Spanned<EcoString>, +) -> Value { + let Spanned { v: path, span } = path; + let path = vm.locate(&path).at(span)?; + let data = vm.world().file(&path).at(span)?; + let value: serde_yaml::Value = + serde_yaml::from_slice(&data).map_err(format_yaml_error).at(span)?; + convert_yaml(value) +} + +/// Convert a YAML value to a Typst value. +fn convert_yaml(value: serde_yaml::Value) -> Value { + match value { + serde_yaml::Value::Null => Value::None, + serde_yaml::Value::Bool(v) => Value::Bool(v), + serde_yaml::Value::Number(v) => match v.as_i64() { + Some(int) => Value::Int(int), + None => Value::Float(v.as_f64().unwrap_or(f64::NAN)), + }, + serde_yaml::Value::String(v) => Value::Str(v.into()), + serde_yaml::Value::Sequence(v) => { + Value::Array(v.into_iter().map(convert_yaml).collect()) + } + serde_yaml::Value::Mapping(v) => Value::Dict( + v.into_iter() + .map(|(key, value)| (convert_yaml_key(key), convert_yaml(value))) + .filter_map(|(key, value)| key.map(|key|(key, value))) + .collect(), + ) + } +} + +/// Converts an arbitary YAML mapping key into a Typst Dict Key. +/// Currently it only does so for strings, everything else +/// returns None +fn convert_yaml_key(key: serde_yaml::Value) -> Option<Str> { + match key { + serde_yaml::Value::String(v) => Some(Str::from(v)), + _ => None, + } +} + +/// Format the user-facing YAML error message. +#[track_caller] +fn format_yaml_error(error: serde_yaml::Error) -> String { + format!("failed to parse yaml file: {}", error.to_string().trim()) +} + /// Read structured data from an XML file. /// /// The XML file is parsed into an array of dictionaries and strings. XML nodes |
