sherd 0.6.0

two-axis federation of SPEC.md and source over a dir DAG, for small-context local models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
//! A RATCHET: measure, compare to a recorded floor, refuse the wrong way.
//!
//! Promoted because the rule was stated three times -- twice in `hk.pkl` as
//! awk and once in `src/land` as Rust -- and the Rust copy diverged from the
//! gate on its flags, its file set AND its denominator at once, reporting
//! 10.8 where the gate computed 14.6 (`.:B25`). Three readings of one rule is
//! `.:B13`, pointed at the gate itself.
//!
//! What the gate reads is stated ONCE here. `src/land` calls it; `hk.pkl`
//! will (`T1`).

use std::path::Path;
use std::process::Command;

mod llvm_json;
pub(crate) mod swift;
pub(crate) mod swift_fn;
pub use swift::{
    Toolchain, excluded_files, llvm_cov_lines, llvm_cov_lines_except,
    swift_bin, swift_coverage, toolchain_of,
};
pub use swift_fn::{
    Exclusion, SwiftMeasure, excluded_cap, excluded_verdict, exclusions,
    measure_export, record_excluded, swift_measure,
};

/// The gate's own clippy invocation. A different build is a different number
/// (`V4`).
pub const GATE_ARGS: [&str; 5] = [
    "clippy",
    "--workspace",
    "--all-targets",
    "--all-features",
    "--message-format=short",
];

/// The directories the gate measures. ONE list, so the numerator and the
/// denominator cannot drift apart (`§C`).
pub const MEASURED: [&str; 2] = ["src", "dev"];

/// Ceiling for the CODE half of one `.rs` file (`V8`).
pub const CEILING_FILE: u64 = 4_000;

/// Ceiling for the TEST half of one `.rs` file (`V8`).
pub const CEILING_TEST: u64 = 2_000;

/// Does `hk` count this line? `^(src|dev)/.*: warning`.
#[must_use]
pub fn gate_counts(line: &str) -> bool {
    MEASURED.iter().any(|d| line.starts_with(&format!("{d}/")))
        && line.contains(": warning")
}

/// Did the build fail? Then there is nothing to count (`V3`).
#[must_use]
pub fn build_failed(line: &str) -> bool {
    line.starts_with("error[") || line.starts_with("error:")
}

/// Tenths as the number a reader sees: `170` is `17.0`.
#[must_use]
pub fn per_kloc(tenths: usize) -> String {
    format!("{}.{}", tenths / 10, tenths % 10)
}

/// Lines of Rust the gate divides by.
///
/// One walker (`§C`): `src/fed` owns the traversal and this asks it, rather
/// than becoming the fourth reading of "the `.rs` files in this tree".
#[must_use]
pub fn measured_lines(root: &Path) -> usize {
    MEASURED
        .iter()
        .flat_map(|d| crate::fed::rust_files(&root.join(d)))
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .map(|t| t.lines().count())
        .sum()
}

/// Everything one clippy run tells the ratchet.
///
/// One struct because the two gated ratios share a run and a denominator:
/// computing them separately invites exactly the drift `B6` records.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Measured {
    /// Warnings the gate counts.
    pub count: usize,
    /// Lines over the limit, summed across every function that exceeds it.
    pub excess: usize,
    /// Lines of Rust in the measured directories.
    pub loc: usize,
}

impl Measured {
    /// Warnings per thousand lines, in TENTHS.
    #[must_use]
    pub const fn density(self) -> usize {
        // `checked_div` rather than a guard plus `/`: a zero denominator is
        // "nothing measured", which is what `0` means here, and stating it
        // once beats stating it twice.
        match self.count.saturating_mul(10_000).checked_div(self.loc) {
            Some(d) => d,
            None => 0,
        }
    }

    /// Share of the tree inside an over-long function, in TENTHS of a
    /// percent -- `92` is 9.2%.
    #[must_use]
    pub const fn shape(self) -> usize {
        match self.excess.saturating_mul(1_000).checked_div(self.loc) {
            Some(s) => s,
            None => 0,
        }
    }
}

/// Lines over `too_many_lines`' limit on one warning line, if it is one.
///
/// `(269/15)` is 254. The LIMIT is read from the message rather than assumed,
/// so raising it in `clippy.toml` cannot leave this measuring the old one.
#[must_use]
pub fn excess_lines(line: &str) -> Option<usize> {
    let (_, tail) = line.split_once("too many lines (")?;
    let (nums, _) = tail.split_once(')')?;
    let (had, limit) = nums.split_once('/')?;
    Some(
        had.parse::<usize>()
            .ok()?
            .saturating_sub(limit.parse().ok()?),
    )
}

/// Measure the tree exactly as the gate does.
///
/// `None` when clippy could not run or the build failed: a count from a build
/// that did not compile is not a measurement (`V3`).
#[must_use]
pub fn measure(root: &Path, cargo: &str) -> Option<Measured> {
    let o = match Command::new(cargo)
        .args(GATE_ARGS)
        .current_dir(root)
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            eprintln!("sherd/debt: could not launch `{cargo}`: {e}");
            return None;
        }
    };
    let out = String::from_utf8_lossy(&o.stderr);
    // The STATUS, not only the text (`V3`): a clippy killed by a signal or
    // refused by cargo may print no `error[`, and the gate used to say only
    // "did not COMPILE" with nothing to read. Name what it said.
    if !o.status.success() || out.lines().any(build_failed) {
        eprintln!("sherd/debt: `{cargo} clippy` exited {}:", o.status);
        out.lines()
            .filter(|l| build_failed(l))
            .chain(out.lines().rev().take(5))
            .for_each(|l| eprintln!("  {l}"));
        return None;
    }
    // No denominator is NOTHING MEASURED, never "zero debt": a ratio over
    // an empty tree would report PASS at 0.0 and claim a tree nobody built
    // is clean (`V3`). Caught by the test asserting silence on a tree with
    // no Rust, after `Measured` replaced a fn that returned `None` here.
    let loc = measured_lines(root);
    if loc == 0 {
        eprintln!("sherd/debt: no Rust found under {}", root.display());
        return None;
    }
    let hits: Vec<&str> = out.lines().filter(|l| gate_counts(l)).collect();
    Some(Measured {
        count: hits.len(),
        excess: hits.iter().filter_map(|l| excess_lines(l)).sum(),
        loc,
    })
}

/// The two gated ceilings from `.lint-debt`, in TENTHS.
#[must_use]
pub fn recorded_ceilings(root: &Path) -> Option<(usize, usize)> {
    let text = std::fs::read_to_string(root.join(".lint-debt")).ok()?;
    let read = |k: &str| text.lines().find_map(|l| tenths(l.strip_prefix(k)?));
    Some((read("density ")?, read("shape ")?))
}

/// The density breach message, if it rose.
fn breach_density(now: usize, was: usize) -> Option<String> {
    (now > was).then(|| {
        format!(
            "sherd/debt:V2: lint DENSITY rose, {} -> {} per KLoC. Fix the \
             new sites, or record WHY in .lint-debt with the raise.",
            per_kloc(was),
            per_kloc(now)
        )
    })
}

/// The shape breach message, if it rose.
fn breach_shape(now: usize, was: usize) -> Option<String> {
    (now > was).then(|| {
        format!(
            "sherd/debt:V1: SHAPE rose, {}% -> {}% of lines inside an \
             over-long function. Counting functions punishes splitting one, \
             so this counts lines OVER the limit.",
            per_kloc(was),
            per_kloc(now)
        )
    })
}

/// Did either ratio RISE? The report, and whether it refuses.
///
/// Both are checked and both are reported, because a run that stops at the
/// first breach hides the second and the next commit meets it alone.
#[must_use]
pub fn verdict(now: Measured, was: (usize, usize)) -> (bool, String) {
    let (dw, sw) = was;
    let (d, s) = (now.density(), now.shape());
    let mut lines: Vec<String> = [breach_density(d, dw), breach_shape(s, sw)]
        .into_iter()
        .flatten()
        .collect();
    let ok = lines.is_empty();
    // `V48`: state what was EXAMINED, not only what failed.
    lines.push(format!(
        "  lint {} per KLoC (ceiling {}) · shape {}% (ceiling {}%) · {} \
         warnings and {} excess lines over {} lines of Rust",
        per_kloc(d),
        per_kloc(dw),
        per_kloc(s),
        per_kloc(sw),
        now.count,
        now.excess,
        now.loc
    ));
    (ok, lines.join("\n"))
}

/// One `.lint-debt` line, with its number brought current. Every other line
/// -- every comment, every recorded reason -- passes through untouched: the
/// file is the audit trail (`V7`).
fn restate(line: &str, now: Measured) -> String {
    match line.split_once(' ').map(|(k, _)| k) {
        Some("density") => format!("density {}", per_kloc(now.density())),
        Some("shape") => format!("shape {}", per_kloc(now.shape())),
        Some("count") => format!("count {}", now.count),
        Some("excess") => format!("excess {}", now.excess),
        Some("loc") => format!("loc {}", now.loc),
        _ => line.to_string(),
    }
}

/// Rewrite `.lint-debt`'s numbers, refusing a RAISE (`V6`).
///
/// # Errors
/// The file could not be read or written, or either ratio rose -- a ratchet
/// that writes down whatever it measures is not a ratchet.
pub fn record(root: &Path, now: Measured) -> Result<String, String> {
    let path = root.join(".lint-debt");
    let text = std::fs::read_to_string(&path).map_err(|e| format!("{e}"))?;
    let was = recorded_ceilings(root).ok_or_else(|| {
        "no `density`/`shape` rows to record into".to_string()
    })?;
    if !verdict(now, was).0 {
        return Err(
            "refusing to RECORD a raise. A ratchet that writes down whatever \
             it measures is not a ratchet."
                .into(),
        );
    }
    let out: String = text.lines().fold(String::new(), |mut acc, l| {
        acc.push_str(&restate(l, now));
        acc.push('\n');
        acc
    });
    std::fs::write(&path, &out).map_err(|e| format!("{e}"))?;
    Ok(format!(
        "recorded density {} · shape {}%",
        per_kloc(now.density()),
        per_kloc(now.shape())
    ))
}

/// The `density` ceiling from `.lint-debt`, in TENTHS, if the file is there.
#[must_use]
pub fn recorded(root: &Path) -> Option<usize> {
    let text = std::fs::read_to_string(root.join(".lint-debt")).ok()?;
    text.lines()
        .find_map(|l| tenths(l.strip_prefix("density ")?))
}

/// `"14.6"` as `146`. A missing decimal reads as `.0`.
fn tenths(v: &str) -> Option<usize> {
    let v = v.trim();
    let (whole, frac) = v.split_once('.').unwrap_or((v, "0"));
    let tenth = frac.chars().next()?.to_digit(10)? as usize;
    whole
        .parse::<usize>()
        .ok()?
        .checked_mul(10)?
        .checked_add(tenth)
}

/// The coverage floor, in HUNDREDTHS. `9227` is `92.27%`.
///
/// Hundredths, where the lint ratios are tenths: `.coverage` has always
/// carried two decimals and rounding it to one would move the floor by up to
/// five hundredths, which is more than most of today's real changes.
pub const COVERAGE_SCALE: usize = 100;

/// Which build a coverage figure is OF (`V4`).
///
/// The floor measured `--all-features` alone while `default = []` is what
/// `cargo install` ships, so code the shipped binary runs could lose every
/// test that reached it and no floor moved (`B8`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Build {
    /// `--all-features`: the model half included. `.coverage`'s `lines` row.
    All,
    /// The default features, `[]` here: what a consumer installs.
    /// `.coverage`'s `lines-default` row.
    Default,
}

impl Build {
    /// Both, in the order the gate reports them.
    pub const BOTH: [Self; 2] = [Self::All, Self::Default];

    /// The `.coverage` row this build's floor lives in.
    #[must_use]
    pub const fn row(self) -> &'static str {
        match self {
            Self::All => "lines",
            Self::Default => "lines-default",
        }
    }

    /// The feature flags `cargo llvm-cov` takes for this build.
    const fn flags(self) -> &'static [&'static str] {
        match self {
            Self::All => &["--all-features"],
            Self::Default => &[],
        }
    }
}

/// `cargo llvm-cov`'s TOTAL line percentage, in hundredths, for the
/// `--all-features` build. See [`coverage_of`].
#[must_use]
pub fn coverage(root: &Path, cargo: &str) -> Option<usize> {
    coverage_of(root, cargo, Build::All)
}

/// `cargo llvm-cov`'s TOTAL line percentage for `build`, in hundredths.
///
/// The MIRROR of `density`: this one may only RISE. Everything else is the
/// same shape, which is why it lives here (`T2`).
///
/// `None` when the tool could not run or printed no TOTAL -- a gate that did
/// not EXECUTE is an ERROR, not a floor breach (`src/tdd:V26`).
#[must_use]
pub fn coverage_of(root: &Path, cargo: &str, build: Build) -> Option<usize> {
    let o = Command::new(cargo)
        .args(["llvm-cov", "--workspace"])
        .args(build.flags())
        .arg("--summary-only")
        .current_dir(root)
        .output()
        .ok()?;
    if !o.status.success() {
        return None;
    }
    let text = String::from_utf8_lossy(&o.stdout);
    let total = text.lines().find(|l| l.starts_with("TOTAL"))?;
    // itok's format: the tenth field is the line percentage.
    hundredths(total.split_whitespace().nth(9)?.trim_end_matches('%'))
}

/// The floor `.coverage` records for `--all-features`, in hundredths.
#[must_use]
pub fn recorded_floor(root: &Path) -> Option<usize> {
    recorded_floor_of(root, Build::All)
}

/// The floor `.coverage` records for `build`, in hundredths. `None` when the
/// file or the row is absent.
#[must_use]
pub fn recorded_floor_of(root: &Path, build: Build) -> Option<usize> {
    let text = std::fs::read_to_string(root.join(".coverage")).ok()?;
    text.lines().find_map(|l| {
        hundredths(l.strip_prefix(build.row())?.strip_prefix(' ')?)
    })
}

/// `"92.27"` as `9227`. One decimal or none still parses.
fn hundredths(v: &str) -> Option<usize> {
    let v = v.trim();
    let (whole, frac) = v.split_once('.').unwrap_or((v, "0"));
    let mut d = frac.chars().filter(char::is_ascii_digit);
    let tens = d.next()?.to_digit(10)? as usize;
    let ones = d.next().and_then(|c| c.to_digit(10)).unwrap_or(0) as usize;
    whole
        .parse::<usize>()
        .ok()?
        .checked_mul(COVERAGE_SCALE)?
        .checked_add(tens.saturating_mul(10).saturating_add(ones))
}

/// Hundredths as the number a reader sees: `9227` is `92.27`.
#[must_use]
pub fn percent(h: usize) -> String {
    format!("{}.{:02}", h / COVERAGE_SCALE, h % COVERAGE_SCALE)
}

/// Did coverage FALL? The report, and whether it refuses.
#[must_use]
pub fn coverage_verdict(now: usize, was: usize) -> (bool, String) {
    if now < was {
        return (
            false,
            format!(
                "sherd/debt:V9: coverage FELL, {}% -> {}%. A line that \
                 stopped being covered is a test that stopped asserting. \
                 Cover it, or say why in .coverage with the drop.",
                percent(was),
                percent(now)
            ),
        );
    }
    // `.:V48`: state what was examined either way.
    (
        true,
        format!("  coverage {}% (floor {}%)", percent(now), percent(was)),
    )
}

/// [`record_coverage_of`] for `--all-features`.
///
/// # Errors
/// See [`record_coverage_of`].
pub fn record_coverage(root: &Path, now: usize) -> Result<String, String> {
    record_coverage_of(root, Build::All, now)
}

/// Rewrite the `build` row of `.coverage`, refusing a DROP. Every other line,
/// the other build's row included, is kept as it was.
///
/// # Errors
/// The file could not be read or written, the row is absent, or coverage
/// fell -- recording a drop is filing down the ratchet's own teeth.
pub fn record_coverage_of(
    root: &Path,
    build: Build,
    now: usize,
) -> Result<String, String> {
    let path = root.join(".coverage");
    let text = std::fs::read_to_string(&path).map_err(|e| format!("{e}"))?;
    let row = build.row();
    let was = recorded_floor_of(root, build)
        .ok_or_else(|| format!("no `{row}` row to record into"))?;
    if !coverage_verdict(now, was).0 {
        return Err(format!(
            "refusing to RECORD a drop in `{row}`, {}% -> {}%. Cover the \
             gap, or edit .coverage by hand with the reason.",
            percent(was),
            percent(now)
        ));
    }
    let prefix = format!("{row} ");
    let out: String = text.lines().fold(String::new(), |mut acc, l| {
        if l.starts_with(&prefix) {
            acc.push_str(&format!("{row} {}", percent(now)));
        } else {
            acc.push_str(l);
        }
        acc.push('\n');
        acc
    });
    std::fs::write(&path, &out).map_err(|e| format!("{e}"))?;
    Ok(format!("recorded `{row}` coverage {}%", percent(now)))
}

#[cfg(test)]
#[path = "tests/debt.rs"]
mod tests;

#[cfg(test)]
#[path = "tests/coverage.rs"]
pub(crate) mod coverage_tests;