Skip to main content

conjure_oxide/
rule_trace_aggregates.rs

1//! Writes the final in-memory rule counts to the CLI aggregate trace file.
2use std::collections::BTreeMap;
3use std::fmt::Write as _;
4use std::fs;
5use std::path::Path;
6
7use anyhow::Context as _;
8
9/// Write a snapshot of the counts, ordered by descending count and then rule name.
10pub fn write_rule_trace_aggregates(
11    path: &Path,
12    counts: &BTreeMap<String, u64>,
13) -> anyhow::Result<()> {
14    let mut rows: Vec<_> = counts.iter().collect();
15    rows.sort_by(|(rule_name_a, count_a), (rule_name_b, count_b)| {
16        count_b
17            .cmp(count_a)
18            .then_with(|| rule_name_a.cmp(rule_name_b))
19    });
20
21    let mut contents = format!(
22        "total_rule_applications: {}\n",
23        counts.values().sum::<u64>()
24    );
25
26    for (rule_name, count) in rows {
27        writeln!(contents, "{count:6} {rule_name}")?;
28    }
29
30    fs::write(path, contents)
31        .with_context(|| format!("Unable to write aggregate trace file {}", path.display()))
32}