Skip to main content

specfold_core/check/limits/
budgets.rs

1//! `[budgets]`: size limits per path glob, written in spec.toml or read from another file, and
2//! what one file measures against them (rule B1).
3
4use crate::config::Config;
5use crate::config::types::BudgetLimit;
6use crate::workspace::owners::{PathMatch, matcher};
7use anyhow::{Context, Result, anyhow, bail};
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11/// One glob's limits and where they were read.
12#[derive(Debug, Clone)]
13pub struct Budget {
14    pub glob: String,
15    /// `spec.toml`, or the `<file>#<key>` of `[budgets] from`.
16    pub source: String,
17    pub limit: BudgetLimit,
18    m: PathMatch,
19}
20
21impl Budget {
22    pub fn matches(&self, path: &str) -> bool {
23        self.m.is_match(path)
24    }
25}
26
27/// What a file measures and the limits that apply to it, in the order they were read.
28#[derive(Debug, Clone, Serialize)]
29pub struct Measure {
30    pub path: String,
31    pub bytes: u64,
32    pub lines: u64,
33    pub limits: Vec<Applied>,
34    /// Whether any limit is exceeded.
35    pub over: bool,
36}
37
38/// One limit as applied to a file: the glob, its source, the maxima, and which were exceeded.
39#[derive(Debug, Clone, Serialize)]
40pub struct Applied {
41    pub glob: String,
42    pub source: String,
43    #[serde(skip_serializing_if = "Option::is_none")]
44    pub max_bytes: Option<u64>,
45    #[serde(skip_serializing_if = "Option::is_none")]
46    pub max_lines: Option<u64>,
47    pub over_bytes: bool,
48    pub over_lines: bool,
49}
50
51/// The array form of a budget table: `[[x]] path = "…"` (or `paths = […]`), `bytes`, `lines`.
52#[derive(Deserialize)]
53#[serde(deny_unknown_fields)]
54struct Entry {
55    path: Option<String>,
56    #[serde(default)]
57    paths: Vec<String>,
58    bytes: Option<u64>,
59    lines: Option<u64>,
60}
61
62/// Every budget, spec.toml's first, then those of `[budgets] from`. Any source that cannot be
63/// read, a table of the wrong shape, a bad glob or an entry with neither limit is an error.
64pub fn load(cfg: &Config) -> Result<Vec<Budget>> {
65    let sec = &cfg.raw.budgets;
66    let mut out = vec![];
67    for (glob, limit) in &sec.paths {
68        out.push(budget(glob, "spec.toml", *limit)?);
69    }
70    if let Some(from) = &sec.from {
71        let v = super::source::read(&cfg.spec_home, from).context("[budgets] from")?;
72        out.extend(parse(&v, from).with_context(|| format!("[budgets] from = \"{from}\""))?);
73    }
74    Ok(out)
75}
76
77fn budget(glob: &str, source: &str, limit: BudgetLimit) -> Result<Budget> {
78    if limit.bytes.is_none() && limit.lines.is_none() {
79        bail!("{source}: the budget for '{glob}' sets neither bytes nor lines");
80    }
81    let m = matcher(glob).ok_or_else(|| anyhow!("{source}: '{glob}' is not a valid glob"))?;
82    Ok(Budget { glob: glob.to_string(), source: source.to_string(), limit, m })
83}
84
85/// A table of glob → `{ bytes, lines }`, or an array of `{ path | paths, bytes, lines }`.
86fn parse(v: &Value, source: &str) -> Result<Vec<Budget>> {
87    let mut out = vec![];
88    match v {
89        Value::Object(map) => {
90            for (glob, l) in map {
91                let limit: BudgetLimit = serde_json::from_value(l.clone())
92                    .with_context(|| format!("'{glob}' is not {{ bytes = <n>, lines = <n> }}"))?;
93                out.push(budget(glob, source, limit)?);
94            }
95        }
96        Value::Array(list) => {
97            for (i, e) in list.iter().enumerate() {
98                let e: Entry = serde_json::from_value(e.clone())
99                    .with_context(|| format!("entry {} is not {{ path, bytes, lines }}", i + 1))?;
100                let globs: Vec<String> = e.path.into_iter().chain(e.paths).collect();
101                if globs.is_empty() {
102                    bail!("entry {} names no path", i + 1);
103                }
104                for g in globs {
105                    out.push(budget(&g, source, BudgetLimit { bytes: e.bytes, lines: e.lines })?);
106                }
107            }
108        }
109        _ => bail!("the budgets are neither a table nor an array"),
110    }
111    Ok(out)
112}
113
114/// `path` with content `text` measured against every budget whose glob matches it; None when
115/// none does.
116pub fn measure(budgets: &[Budget], path: &str, text: &[u8]) -> Option<Measure> {
117    let applied: Vec<&Budget> = budgets.iter().filter(|b| b.matches(path)).collect();
118    if applied.is_empty() {
119        return None;
120    }
121    let bytes = text.len() as u64;
122    let lines = text.split(|b| *b == b'\n').count() as u64 - u64::from(text.ends_with(b"\n") || text.is_empty());
123    let limits: Vec<Applied> = applied
124        .iter()
125        .map(|b| Applied {
126            glob: b.glob.clone(),
127            source: b.source.clone(),
128            max_bytes: b.limit.bytes,
129            max_lines: b.limit.lines,
130            over_bytes: b.limit.bytes.is_some_and(|m| bytes > m),
131            over_lines: b.limit.lines.is_some_and(|m| lines > m),
132        })
133        .collect();
134    let over = limits.iter().any(|a| a.over_bytes || a.over_lines);
135    Some(Measure { path: path.to_string(), bytes, lines, limits, over })
136}
137
138#[cfg(test)]
139mod tests {
140    use super::*;
141
142    fn b(glob: &str, bytes: Option<u64>, lines: Option<u64>) -> Budget {
143        budget(glob, "spec.toml", BudgetLimit { bytes, lines }).unwrap()
144    }
145
146    #[test]
147    fn measures_bytes_and_lines_against_each_matching_budget() {
148        let budgets = [b("AGENTS.md", Some(10), None), b("**/*.md", None, Some(2)), b("src", Some(1), None)];
149        let m = measure(&budgets, "AGENTS.md", b"one\ntwo\nthree\n").unwrap();
150        assert_eq!((m.bytes, m.lines, m.limits.len(), m.over), (14, 3, 2, true));
151        assert!(m.limits[0].over_bytes && m.limits[1].over_lines);
152        let m = measure(&budgets, "a.md", b"x\ny").unwrap();
153        assert_eq!((m.lines, m.over), (2, false));
154        assert!(measure(&budgets, "b.txt", b"").is_none());
155    }
156
157    #[test]
158    fn parses_both_table_shapes_and_refuses_empty_entries() {
159        let t = serde_json::json!({"a.md": {"bytes": 5}});
160        assert_eq!(parse(&t, "x").unwrap()[0].glob, "a.md");
161        let a = serde_json::json!([{"paths": ["a.md", "b.md"], "lines": 3}]);
162        assert_eq!(parse(&a, "x").unwrap().len(), 2);
163        assert!(parse(&serde_json::json!({"a.md": {}}), "x").is_err());
164        assert!(parse(&serde_json::json!({"a.md": {"byte": 1}}), "x").is_err());
165        assert!(parse(&serde_json::json!([{"bytes": 1}]), "x").is_err());
166        assert!(parse(&serde_json::json!(3), "x").is_err());
167    }
168}