Skip to content

Commit

Permalink
feat(whiskers): allow overrides of any matrix iterable
Browse files Browse the repository at this point in the history
  • Loading branch information
backwardspy committed Apr 2, 2024
1 parent a6be59f commit 74e6de8
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 4 deletions.
1 change: 0 additions & 1 deletion whiskers/examples/multi-output/output-a.txt

This file was deleted.

1 change: 0 additions & 1 deletion whiskers/examples/multi-output/output-b.txt

This file was deleted.

10 changes: 10 additions & 0 deletions whiskers/examples/multi-output/single-accent/example.tera
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
# use `--overrides '{"accent": "red"}'` for example
whiskers:
version: "2.0.0"
matrix:
- flavor
- accent
filename: 'output-{{flavor.identifier}}-{{accent}}.txt'
---
{{flavor.name}} accent {{accent}}
36 changes: 34 additions & 2 deletions whiskers/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
collections::HashMap,
collections::{hash_map::Entry, HashMap},
env,
io::Write as _,
path::{Path, PathBuf},
Expand Down Expand Up @@ -87,7 +87,7 @@ fn main() -> anyhow::Result<()> {
.context("Template contents could not be read")?,
)
.context("Frontmatter is invalid")?;
let template_opts =
let mut template_opts =
TemplateOptions::from_frontmatter(&doc.frontmatter, args.flavor.map(Into::into))
.context("Could not get template options from frontmatter")?;

Expand All @@ -108,6 +108,11 @@ fn main() -> anyhow::Result<()> {
tera::to_value(value)
.with_context(|| format!("Value of {key} override is invalid"))?,
);

// overrides also work on matrix iterables
if let Some(ref mut matrix) = template_opts.matrix {
override_matrix(matrix, value, key)?;
}
}
}
let mut ctx = tera::Context::new();
Expand Down Expand Up @@ -169,6 +174,33 @@ fn main() -> anyhow::Result<()> {
Ok(())
}

fn override_matrix(
matrix: &mut Matrix,
value: &tera::Value,
key: &str,
) -> Result<(), anyhow::Error> {
let Entry::Occupied(e) = matrix.entry(key.to_string()) else {
return Ok(());
};

// if the override is a list, we can just replace the iterable.
if let Some(value_list) = value.as_array() {
let value_list = value_list
.iter()
.map(|v| v.as_str().map(ToString::to_string))
.collect::<Option<Vec<_>>>()
.context("Override value is not a list of strings")?;
*e.into_mut() = value_list;
}
// if the override is a string, we instead replace the iterable with a
// single-element list containing the string.
else if let Some(value_string) = value.as_str() {
*e.into_mut() = vec![value_string.to_string()];
}

Ok(())
}

#[allow(clippy::too_many_lines)]
fn list_functions(format: OutputFormat) {
match format {
Expand Down

0 comments on commit 74e6de8

Please sign in to comment.