Skip to main content

micromegas_analytics/
log_msg_template.rs

1use micromegas_transit::value::{Object, Value};
2
3/// Renders a log message from the template the instrumented process deferred: `fmt_str` with
4/// each `{name}` or `{name:?}` replaced by the string property `name`.
5///
6/// A missing property, or a placeholder outside that grammar, is copied through unchanged, so a
7/// corrupt or hand-built block stays readable instead of failing.
8pub fn render_msg_template(fmt_str: &str, properties: &Object) -> String {
9    let mut out = String::with_capacity(fmt_str.len());
10    let mut rest = fmt_str;
11    while let Some(pos) = rest.find(['{', '}']) {
12        out.push_str(&rest[..pos]);
13        let tail = &rest[pos..];
14        if tail.starts_with("{{") || tail.starts_with("}}") {
15            out.push_str(&tail[..1]);
16            rest = &tail[2..];
17            continue;
18        }
19        if tail.starts_with('{')
20            && let Some(end) = tail.find('}')
21        {
22            let placeholder = &tail[..=end];
23            let inner = &tail[1..end];
24            // `{n:}` is `{n}` in Rust's format grammar and reaches here verbatim.
25            let name = inner
26                .strip_suffix(":?")
27                .or_else(|| inner.strip_suffix(':'))
28                .unwrap_or(inner);
29            match properties.members.iter().find(|(k, _)| *k == name) {
30                Some((_, Value::String(value))) => out.push_str(value),
31                _ => out.push_str(placeholder),
32            }
33            rest = &tail[end + 1..];
34            continue;
35        }
36        out.push_str(&tail[..1]);
37        rest = &tail[1..];
38    }
39    out.push_str(rest);
40    out
41}