rustysan-sword 0.1.1

Blade-inspired HTML templates for Rust
Documentation
//! `@dump`: a bounded, allowlisted view of one template value, for development only.
//!
//! Nothing here runs unless the `dump` feature is compiled in, the host enabled it, and the
//! environment is a development one. The directive's argument is not even evaluated otherwise.
use minijinja::{Value, value::ValueKind};

/// Deepest nesting shown.
const MAX_DEPTH: usize = 6;
/// Most entries shown per list or map.
const MAX_ENTRIES: usize = 50;
/// Longest string shown, in characters.
const MAX_STRING: usize = 200;
/// Longest output, in bytes.
const MAX_OUTPUT: usize = 8 * 1024;

/// Environments in which dumping may run, however it was enabled.
pub(crate) fn development(environment: &str) -> bool {
    matches!(environment, "local" | "testing")
}

/// Render `value`. Map fields are shown only when named in `allowed`; every other field is
/// counted, never named or shown, so a dump cannot reveal a secret nobody listed.
pub(crate) fn render(value: &Value, allowed: &[String]) -> String {
    let mut out = String::new();
    write(&mut out, value, allowed, 0);
    if out.len() > MAX_OUTPUT {
        let mut end = MAX_OUTPUT;
        while !out.is_char_boundary(end) {
            end -= 1;
        }
        out.truncate(end);
        out.push_str("\n… output truncated");
    }
    out
}

fn indent(out: &mut String, depth: usize) {
    for _ in 0..depth {
        out.push_str("  ");
    }
}

fn write(out: &mut String, value: &Value, allowed: &[String], depth: usize) {
    if out.len() > MAX_OUTPUT {
        return;
    }
    match value.kind() {
        ValueKind::Undefined => out.push_str("undefined"),
        ValueKind::None => out.push_str("null"),
        ValueKind::Bool => out.push_str(if value.is_true() { "true" } else { "false" }),
        ValueKind::Number => out.push_str(&value.to_string()),
        ValueKind::String => {
            let text = value.as_str().unwrap_or_default();
            out.push('"');
            out.extend(text.chars().take(MAX_STRING));
            if text.chars().count() > MAX_STRING {
                out.push('…');
            }
            out.push('"');
        }
        ValueKind::Seq | ValueKind::Iterable => {
            let items: Vec<Value> = value.try_iter().map(Iterator::collect).unwrap_or_default();
            if items.is_empty() {
                out.push_str("[]");
            } else if depth >= MAX_DEPTH {
                out.push_str(&format!("[… {} items]", items.len()));
            } else {
                out.push_str("[\n");
                for item in items.iter().take(MAX_ENTRIES) {
                    indent(out, depth + 1);
                    write(out, item, allowed, depth + 1);
                    out.push_str(",\n");
                }
                if items.len() > MAX_ENTRIES {
                    indent(out, depth + 1);
                    out.push_str(&format!("… {} more\n", items.len() - MAX_ENTRIES));
                }
                indent(out, depth);
                out.push(']');
            }
        }
        ValueKind::Map => {
            let keys: Vec<Value> = value.try_iter().map(Iterator::collect).unwrap_or_default();
            if depth >= MAX_DEPTH {
                out.push_str(&format!("{{… {} fields}}", keys.len()));
                return;
            }
            let mut shown = Vec::new();
            let mut hidden = 0usize;
            for key in &keys {
                let name = key.as_str().map(str::to_owned);
                match name {
                    Some(name) if allowed.contains(&name) => {
                        shown.push((name, value.get_item(key).unwrap_or(Value::UNDEFINED)));
                    }
                    _ => hidden += 1,
                }
            }
            out.push_str("{\n");
            for (name, field) in shown.iter().take(MAX_ENTRIES) {
                indent(out, depth + 1);
                out.push_str(name);
                out.push_str(": ");
                write(out, field, allowed, depth + 1);
                out.push_str(",\n");
            }
            if hidden > 0 {
                indent(out, depth + 1);
                out.push_str(&format!("… {hidden} fields not listed\n"));
            }
            indent(out, depth);
            out.push('}');
        }
        _ => out.push_str("<value>"),
    }
}