1
//! Writes the final in-memory rule counts to the CLI aggregate trace file.
2
use std::collections::BTreeMap;
3
use std::fmt::Write as _;
4
use std::fs;
5
use std::path::Path;
6

            
7
use anyhow::Context as _;
8

            
9
/// Write a snapshot of the counts, ordered by descending count and then rule name.
10
36
pub fn write_rule_trace_aggregates(
11
36
    path: &Path,
12
36
    counts: &BTreeMap<String, u64>,
13
36
) -> anyhow::Result<()> {
14
36
    let mut rows: Vec<_> = counts.iter().collect();
15
1308
    rows.sort_by(|(rule_name_a, count_a), (rule_name_b, count_b)| {
16
1308
        count_b
17
1308
            .cmp(count_a)
18
112
            .then_with(|| rule_name_a.cmp(rule_name_b))
19
1308
    });
20

            
21
36
    let mut contents = format!(
22
        "total_rule_applications: {}\n",
23
36
        counts.values().sum::<u64>()
24
    );
25

            
26
36
    for (rule_name, count) in rows {
27
392
        writeln!(contents, "{count:6} {rule_name}")?;
28
    }
29

            
30
36
    fs::write(path, contents)
31
        .with_context(|| format!("Unable to write aggregate trace file {}", path.display()))
32
36
}