Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions docs/templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,14 @@ Tera offers more filters. Read more on [tera documentation](https://keats.github

#### Hash

- `str | hash([len]) -> String` – Generates a SHA256 hash for the input string.
- `str | hash([algorithm], [len]) -> String` – Generates a hash for the input string.
- `algorithm: "sha256" | "blake3"`: hash algorithm to use (default: `"sha256"`)
- `len: usize`: truncates the hash string to the given size
- `path | hash_file([len]) -> String` – Returns the SHA256 hash of the file
- Examples:
- <span v-pre>`{{ "foo" | hash }}`</span> – SHA256 hash (default)
- <span v-pre>`{{ "foo" | hash(algorithm="blake3") }}`</span> – BLAKE3 hash
- <span v-pre>`{{ "foo" | hash(len=8) }}`</span> – SHA256 hash truncated to 8 characters
- `path | hash_file([len]) -> String` – Returns the BLAKE3 hash of the file
at the given path.
- `len: usize`: truncates the hash string to the given size

Expand Down
20 changes: 19 additions & 1 deletion src/tera.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,18 @@ static TERA: Lazy<Tera> = Lazy::new(|| {
"hash",
move |input: &Value, args: &HashMap<String, Value>| match input {
Value::String(s) => {
let mut hash = hash::hash_blake3_to_str(s);
// Get the algorithm, default to sha256
let algorithm = args
.get("algorithm")
.and_then(Value::as_str)
.unwrap_or("sha256");

let mut hash = match algorithm {
"sha256" => hash::hash_sha256_to_str(s),
"blake3" => hash::hash_blake3_to_str(s),
_ => return Err(format!("unknown hash algorithm: {algorithm}").into()),
};

if let Some(len) = args.get("len").and_then(Value::as_u64) {
hash = hash.chars().take(len as usize).collect();
}
Expand Down Expand Up @@ -642,7 +653,14 @@ mod tests {
#[tokio::test]
async fn test_hash() {
let _config = Config::get().await.unwrap();
// SHA256 of "foo" is 2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae
let s = render("{{ \"foo\" | hash(len=8) }}");
assert_eq!(s, "2c26b46b");
// Test explicit sha256
let s = render("{{ \"foo\" | hash(algorithm=\"sha256\", len=8) }}");
assert_eq!(s, "2c26b46b");
// Test blake3 - BLAKE3 of "foo" starts with 04e0bb39
let s = render("{{ \"foo\" | hash(algorithm=\"blake3\", len=8) }}");
assert_eq!(s, "04e0bb39");
}

Expand Down
Loading