Skip to content

Commit

Permalink
feat(whiskers): add read_file function (#217)
Browse files Browse the repository at this point in the history
Co-authored-by: backwardspy <backwardspy@pigeon.life>
  • Loading branch information
uncenter and backwardspy authored May 27, 2024
1 parent e2e7f22 commit c00881a
Show file tree
Hide file tree
Showing 8 changed files with 94 additions and 4 deletions.
1 change: 1 addition & 0 deletions whiskers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,7 @@ These types are designed to closely match the [palette.json](https://github.com/
| `css_rgba` | Convert a color to an RGBA CSS string | `css_rgba(color=red)` => `rgba(210, 15, 57, 1.00)` |
| `css_hsl` | Convert a color to an HSL CSS string | `css_hsl(color=red)` => `hsl(347, 87%, 44%)` |
| `css_hsla` | Convert a color to an HSLA CSS string | `css_hsla(color=red)` => `hsla(347, 87%, 44%, 1.00)` |
| `read_file` | Read and include the contents of a file, path is relative to the template file | `read_file(path="abc.txt")` => `abc` |

### Filters

Expand Down
22 changes: 21 additions & 1 deletion whiskers/src/functions.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
use std::collections::{BTreeMap, HashMap};
use std::{
collections::{BTreeMap, HashMap},
fs,
path::PathBuf,
};

use crate::models::Color;

Expand Down Expand Up @@ -67,3 +71,19 @@ pub fn css_hsla(args: &HashMap<String, tera::Value>) -> Result<tera::Value, tera
let color: css_colors::HSLA = (&color).into();
Ok(tera::to_value(color.to_string())?)
}

pub fn read_file_handler(
template_directory: PathBuf,
) -> impl Fn(&HashMap<String, tera::Value>) -> Result<tera::Value, tera::Error> {
move |args| -> Result<tera::Value, tera::Error> {
let path: String = tera::from_value(
args.get("path")
.ok_or_else(|| tera::Error::msg("path is required"))?
.clone(),
)?;
let path = template_directory.join(path);
let contents = fs::read_to_string(&path)
.map_err(|_| format!("Failed to open file {}", path.display()))?;
Ok(tera::to_value(contents)?)
}
}
15 changes: 14 additions & 1 deletion whiskers/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ fn main() -> anyhow::Result<()> {
.expect("args.template is guaranteed by clap to be set");
let template_from_stdin = matches!(template.source, clap_stdin::Source::Stdin);
let template_name = template_name(template);
let template_directory =
template_directory(template).context("Template file does not exist")?;

let mut decoder = DecodeReaderBytes::new(
template
Expand Down Expand Up @@ -149,7 +151,7 @@ fn main() -> anyhow::Result<()> {
}

// build the Tera engine
let mut tera = templating::make_engine();
let mut tera = templating::make_engine(&template_directory);
tera.add_raw_template(&template_name, &doc.body)
.context("Template is invalid")?;

Expand Down Expand Up @@ -258,6 +260,17 @@ fn template_name(template: &clap_stdin::FileOrStdin) -> String {
}
}

fn template_directory(template: &clap_stdin::FileOrStdin) -> anyhow::Result<PathBuf> {
match &template.source {
clap_stdin::Source::Stdin => Ok(std::env::current_dir()?),
clap_stdin::Source::Arg(arg) => Ok(Path::new(&arg)
.canonicalize()?
.parent()
.expect("file path must have a parent")
.to_owned()),
}
}

fn template_is_compatible(template_opts: &TemplateOptions) -> bool {
let whiskers_version = semver::Version::parse(env!("CARGO_PKG_VERSION"))
.expect("CARGO_PKG_VERSION is always valid");
Expand Down
15 changes: 14 additions & 1 deletion whiskers/src/templating.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::path::Path;

use indexmap::IndexMap;

use crate::{filters, functions};
Expand Down Expand Up @@ -42,7 +44,7 @@ macro_rules! filter_example {
};
}

pub fn make_engine() -> tera::Tera {
pub fn make_engine(template_directory: &Path) -> tera::Tera {
let mut tera = tera::Tera::default();
tera.register_filter("add", filters::add);
tera.register_filter("sub", filters::sub);
Expand All @@ -60,6 +62,10 @@ pub fn make_engine() -> tera::Tera {
tera.register_function("css_rgba", functions::css_rgba);
tera.register_function("css_hsl", functions::css_hsl);
tera.register_function("css_hsla", functions::css_hsla);
tera.register_function(
"read_file",
functions::read_file_handler(template_directory.to_owned()),
);
tera
}

Expand Down Expand Up @@ -103,6 +109,13 @@ pub fn all_functions() -> Vec<Function> {
description: "Convert a color to an HSLA CSS string".to_string(),
examples: vec![function_example!(css_hsla(color=red) => "hsla(347, 87%, 44%, 1.00)")],
},
Function {
name: "read_file".to_string(),
description:
"Read and include the contents of a file, path is relative to the template file"
.to_string(),
examples: vec![function_example!(read_file(path="abc.txt") => "abc")],
},
]
}

Expand Down
14 changes: 13 additions & 1 deletion whiskers/tests/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,18 @@ mod happy_path {
));
}

/// Test that the CLI can render a template which uses read_file
#[test]
fn test_read_file() {
let mut cmd = Command::cargo_bin("whiskers").expect("binary exists");
let assert = cmd
.args(["tests/fixtures/read_file/read_file.tera", "-f", "latte"])
.assert();
assert
.success()
.stdout(include_str!("fixtures/read_file/read_file.md"));
}

/// Test that the CLI can render a UTF-8 template file
#[test]
fn test_utf8() {
Expand Down Expand Up @@ -89,7 +101,7 @@ mod sad_path {
cmd.arg("test/file/doesnt/exist");
cmd.assert()
.failure()
.stderr(predicate::str::contains("Failed to open template file"));
.stderr(predicate::str::contains("Template file does not exist"));
}

#[test]
Expand Down
1 change: 1 addition & 0 deletions whiskers/tests/fixtures/read_file/abc.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Aute tempor minim eiusmod.
23 changes: 23 additions & 0 deletions whiskers/tests/fixtures/read_file/read_file.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
Aute tempor minim eiusmod.

MIT License

Copyright (c) 2021 Catppuccin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
7 changes: 7 additions & 0 deletions whiskers/tests/fixtures/read_file/read_file.tera
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
whiskers:
version: 2.0.0
---

{{- read_file(path="abc.txt") }}
{{ read_file(path="../../../LICENSE") -}}

0 comments on commit c00881a

Please sign in to comment.