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    /// Whether the glob names paths inside the submodule at `link` explicitly: its literal
27    /// prefix, the segments before the first one holding `*`, `?`, `[` or `{`, is `link` or lies
28    /// below it. `**/AGENTS.md` or `apps/**` match inside a submodule without naming it.
29    pub fn names_inside(&self, link: &str) -> bool {
30        crate::paths::is_under(&literal_prefix(&self.glob), link)
31    }
32}
33
34/// The segments of `glob` before the first one with a wildcard, joined by `/`.
35fn literal_prefix(glob: &str) -> String {
36    let segs: Vec<&str> =
37        glob.trim_end_matches('/').split('/').take_while(|s| !s.contains(['*', '?', '[', '{'])).collect();
38    segs.join("/")
39}
40
41/// The submodule among `links` that `path` lies inside, if any.
42pub fn gitlink_of<'a>(links: &'a [String], path: &str) -> Option<&'a str> {
43    links.iter().map(String::as_str).find(|l| crate::paths::is_below(path, l))
44}
45
46/// The budgets that judge `path`: those whose glob matches it, except that inside a submodule
47/// only those naming it explicitly count, as the parent repository does not own its files.
48pub fn applicable(list: &[Budget], links: &[String], path: &str) -> Vec<Budget> {
49    let link = gitlink_of(links, path);
50    list.iter().filter(|b| b.matches(path) && link.is_none_or(|l| b.names_inside(l))).cloned().collect()
51}
52
53/// What a file measures and the limits that apply to it, in the order they were read.
54#[derive(Debug, Clone, Serialize)]
55pub struct Measure {
56    pub path: String,
57    pub bytes: u64,
58    pub lines: u64,
59    pub limits: Vec<Applied>,
60    /// Whether any limit is exceeded.
61    pub over: bool,
62}
63
64/// One limit as applied to a file: the glob, its source, the maxima, and which were exceeded.
65#[derive(Debug, Clone, Serialize)]
66pub struct Applied {
67    pub glob: String,
68    pub source: String,
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub max_bytes: Option<u64>,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub max_lines: Option<u64>,
73    pub over_bytes: bool,
74    pub over_lines: bool,
75}
76
77/// The array form of a budget table: `[[x]] path = "…"` (or `paths = […]`), `bytes`, `lines`.
78#[derive(Deserialize)]
79#[serde(deny_unknown_fields)]
80struct Entry {
81    path: Option<String>,
82    #[serde(default)]
83    paths: Vec<String>,
84    bytes: Option<u64>,
85    lines: Option<u64>,
86}
87
88/// Every budget, spec.toml's first, then those of `[budgets] from`. Any source that cannot be
89/// read, a table of the wrong shape, a bad glob or an entry with neither limit is an error.
90pub fn load(cfg: &Config) -> Result<Vec<Budget>> {
91    let sec = &cfg.raw.budgets;
92    let mut out = vec![];
93    for (glob, limit) in &sec.paths {
94        out.push(budget(glob, "spec.toml", *limit)?);
95    }
96    if let Some(from) = &sec.from {
97        let v = super::source::read(&cfg.spec_home, from).context("[budgets] from")?;
98        out.extend(parse(&v, from).with_context(|| format!("[budgets] from = \"{from}\""))?);
99    }
100    Ok(out)
101}
102
103fn budget(glob: &str, source: &str, limit: BudgetLimit) -> Result<Budget> {
104    if limit.bytes.is_none() && limit.lines.is_none() {
105        bail!("{source}: the budget for '{glob}' sets neither bytes nor lines");
106    }
107    let m = matcher(glob).ok_or_else(|| anyhow!("{source}: '{glob}' is not a valid glob"))?;
108    Ok(Budget { glob: glob.to_string(), source: source.to_string(), limit, m })
109}
110
111/// A table of glob → `{ bytes, lines }`, or an array of `{ path | paths, bytes, lines }`.
112fn parse(v: &Value, source: &str) -> Result<Vec<Budget>> {
113    let mut out = vec![];
114    match v {
115        Value::Object(map) => {
116            for (glob, l) in map {
117                let limit: BudgetLimit = serde_json::from_value(l.clone())
118                    .with_context(|| format!("'{glob}' is not {{ bytes = <n>, lines = <n> }}"))?;
119                out.push(budget(glob, source, limit)?);
120            }
121        }
122        Value::Array(list) => {
123            for (i, e) in list.iter().enumerate() {
124                let e: Entry = serde_json::from_value(e.clone())
125                    .with_context(|| format!("entry {} is not {{ path, bytes, lines }}", i + 1))?;
126                let globs: Vec<String> = e.path.into_iter().chain(e.paths).collect();
127                if globs.is_empty() {
128                    bail!("entry {} names no path", i + 1);
129                }
130                for g in globs {
131                    out.push(budget(&g, source, BudgetLimit { bytes: e.bytes, lines: e.lines })?);
132                }
133            }
134        }
135        _ => bail!("the budgets are neither a table nor an array"),
136    }
137    Ok(out)
138}
139
140/// `path` with content `text` measured against every budget whose glob matches it; None when
141/// none does.
142pub fn measure(budgets: &[Budget], path: &str, text: &[u8]) -> Option<Measure> {
143    let applied: Vec<&Budget> = budgets.iter().filter(|b| b.matches(path)).collect();
144    if applied.is_empty() {
145        return None;
146    }
147    let bytes = text.len() as u64;
148    let lines = text.split(|b| *b == b'\n').count() as u64 - u64::from(text.ends_with(b"\n") || text.is_empty());
149    let limits: Vec<Applied> = applied
150        .iter()
151        .map(|b| Applied {
152            glob: b.glob.clone(),
153            source: b.source.clone(),
154            max_bytes: b.limit.bytes,
155            max_lines: b.limit.lines,
156            over_bytes: b.limit.bytes.is_some_and(|m| bytes > m),
157            over_lines: b.limit.lines.is_some_and(|m| lines > m),
158        })
159        .collect();
160    let over = limits.iter().any(|a| a.over_bytes || a.over_lines);
161    Some(Measure { path: path.to_string(), bytes, lines, limits, over })
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    fn b(glob: &str, bytes: Option<u64>, lines: Option<u64>) -> Budget {
169        budget(glob, "spec.toml", BudgetLimit { bytes, lines }).unwrap()
170    }
171
172    #[test]
173    fn measures_bytes_and_lines_against_each_matching_budget() {
174        let budgets = [b("AGENTS.md", Some(10), None), b("**/*.md", None, Some(2)), b("src", Some(1), None)];
175        let m = measure(&budgets, "AGENTS.md", b"one\ntwo\nthree\n").unwrap();
176        assert_eq!((m.bytes, m.lines, m.limits.len(), m.over), (14, 3, 2, true));
177        assert!(m.limits[0].over_bytes && m.limits[1].over_lines);
178        let m = measure(&budgets, "a.md", b"x\ny").unwrap();
179        assert_eq!((m.lines, m.over), (2, false));
180        assert!(measure(&budgets, "b.txt", b"").is_none());
181    }
182
183    #[test]
184    fn only_a_literal_prefix_reaching_a_gitlink_names_paths_inside_it() {
185        let link = "vendor/lib";
186        let named = |g: &str| b(g, Some(1), None).names_inside(link);
187        assert!(named("vendor/lib/AGENTS.md") && named("vendor/lib/**/*.md") && named("vendor/lib"));
188        assert!(!named("**/AGENTS.md") && !named("vendor/**/AGENTS.md") && !named("AGENTS.md"));
189        assert!(!named("vendor") && !named("vendor/library/*.md") && !named("*.md"));
190        let links = vec![link.to_string()];
191        let list = [b("**/AGENTS.md", Some(1), None), b("vendor/lib/AGENTS.md", None, Some(1))];
192        let globs = |p: &str| applicable(&list, &links, p).into_iter().map(|b| b.glob).collect::<Vec<_>>();
193        assert_eq!(globs("vendor/lib/AGENTS.md"), ["vendor/lib/AGENTS.md"]);
194        assert_eq!(globs("vendor/lib/x/AGENTS.md"), Vec::<String>::new());
195        assert_eq!(globs("AGENTS.md"), ["**/AGENTS.md"]);
196        assert_eq!(gitlink_of(&links, "vendor/lib"), None);
197    }
198
199    #[test]
200    fn parses_both_table_shapes_and_refuses_empty_entries() {
201        let t = serde_json::json!({"a.md": {"bytes": 5}});
202        assert_eq!(parse(&t, "x").unwrap()[0].glob, "a.md");
203        let a = serde_json::json!([{"paths": ["a.md", "b.md"], "lines": 3}]);
204        assert_eq!(parse(&a, "x").unwrap().len(), 2);
205        assert!(parse(&serde_json::json!({"a.md": {}}), "x").is_err());
206        assert!(parse(&serde_json::json!({"a.md": {"byte": 1}}), "x").is_err());
207        assert!(parse(&serde_json::json!([{"bytes": 1}]), "x").is_err());
208        assert!(parse(&serde_json::json!(3), "x").is_err());
209    }
210}