brake 2026.11.3

A brake on breaking API changes. Checks OpenAPI, protobuf and GraphQL contracts for backward compatibility, hermetically.
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
//! The rustc-style text diagnostic.
//!
//! Rendered with `annotate-snippets`, the same renderer tropism uses, so the
//! two tools' output is indistinguishable in a hook. The rationale line is
//! rendered verbatim at the moment a developer is blocked, on the grounds that
//! this is when someone actually wants to know why the constraint exists.

use crate::Severity;
use crate::report::Report;
use crate::rules::Finding;

#[cfg(feature = "cli")]
use crate::rules::catalogue;

#[cfg(feature = "cli")]
use annotate_snippets::{AnnotationKind, Group, Level, Origin, Renderer, Snippet};

pub fn render(report: &Report) -> String {
    let mut out = String::new();

    for finding in &report.findings {
        out.push_str(&render_finding(report, finding));
        out.push('\n');
    }

    for unavailable in &report.unavailable {
        let contract = unavailable.contract.as_deref().unwrap_or("<unknown>");
        out.push_str(&format!(
            "error: brake could not check `{contract}`: {}\n\
             note: this is a tool failure, not an API break — exiting 2\n\n",
            unavailable.message
        ));
    }

    if report.findings.is_empty() && report.unavailable.is_empty() {
        out.push_str(&format!(
            "clean: {} contract{} checked, no findings at the selected threshold\n",
            report.contracts_checked,
            if report.contracts_checked == 1 {
                ""
            } else {
                "s"
            }
        ));
    }

    out
}

#[cfg(feature = "cli")]
fn render_finding(report: &Report, finding: &Finding) -> String {
    let level = match finding.severity {
        Severity::Error => Level::ERROR,
        Severity::Warning => Level::WARNING,
        Severity::Info => Level::INFO,
    };

    let rule = catalogue::lookup(finding.rule_id);
    // A finding about an undeclared file has no contract to name, and
    // printing an empty one reads worse than printing none.
    let contract_note = if finding.contract.is_empty() {
        finding
            .path
            .as_deref()
            .map_or_else(String::new, |path| format!("file: `{path}`"))
    } else {
        format!("contract: `{}`", finding.contract)
    };

    // The help block is what someone reads at the moment they are blocked, so
    // it carries what to *do*. The rationale for why the rule exists is a
    // paragraph they do not need in order to act, and lives in `brake explain`.
    let help = rule.map(|rule| help_text(rule, finding));

    // Only quote source when the artifact's text is on the report; a baseline
    // resolved from a git blob has text, one that failed to read does not.
    let quoted = finding.span.as_ref().and_then(|span| {
        let source = report.sources.get(&span.file)?;
        let (start, end) = line_range(source, span.line, span.column)?;
        Some((span, source.as_str(), start, end))
    });

    // The rule id only, without `id_url`: a terminal hyperlink writes OSC-8
    // escapes even from the plain renderer, and output has to stay byte-stable
    // and pipe-safe. The help URI is in the SARIF and in `brake explain`.
    let primary = level.primary_title(&finding.message).id(finding.rule_id);

    let mut group = match quoted {
        Some((span, source, start, end)) => primary.element(
            Snippet::source(source)
                .path(&span.file)
                .fold(true)
                .annotation(AnnotationKind::Primary.span(start..end).label("here")),
        ),
        None => {
            let group = primary.element(Level::NOTE.message(&contract_note));
            match &finding.span {
                Some(span) => group.element(
                    Origin::path(span.file.clone())
                        .line(span.line)
                        .char_column(span.column),
                ),
                None => group,
            }
        }
    };

    if quoted.is_some() {
        group = group.element(Level::NOTE.message(&contract_note));
    }

    // Who this breaks, and where they said so. The interaction line is the
    // evidence: it turns "this might break somebody" into a name and a file.
    let affects = affects_notes(finding);
    for note in &affects {
        group = group.element(Level::NOTE.message(note));
    }
    if let Some(note) = &finding.note {
        group = group.element(Level::NOTE.message(note));
    }

    let mut report_groups = vec![group];
    if let Some(help) = &help {
        report_groups.push(Group::with_title(Level::HELP.secondary_title(help)));
    }

    format!("{}\n", Renderer::plain().render(&report_groups))
}

/// `breaks web-checkout — pacts/web-checkout-payments.json:88`, one per
/// affected consumer.
///
/// "breaks" only where the finding is an error. A warning or a note is not a
/// break, and saying it is would be the kind of confident overstatement that
/// teaches a team to stop reading the output.
#[cfg(feature = "cli")]
fn affects_notes(finding: &Finding) -> Vec<String> {
    finding
        .affects
        .iter()
        .map(|reference| {
            format!(
                "{} {} — {}:{}",
                verb(finding.severity),
                reference.consumer,
                reference.source,
                reference.span.line
            )
        })
        .collect()
}

#[cfg(feature = "cli")]
fn verb(severity: Severity) -> &'static str {
    match severity {
        Severity::Error => "breaks",
        Severity::Warning | Severity::Info => "declared by",
    }
}

/// Fallback when the crate is built without the `cli` feature: a consumer
/// embedding the library renders findings itself.
#[cfg(not(feature = "cli"))]
fn render_finding(_report: &Report, finding: &Finding) -> String {
    let mut out = format!(
        "{}[{}]: {}",
        severity_label(finding.severity),
        finding.rule_id,
        finding.message
    );
    if let Some(span) = &finding.span {
        out.push_str(&format!(
            "\n  --> {}:{}:{}",
            span.file, span.line, span.column
        ));
    }
    out.push_str(&format!("\n  = contract: {}\n", finding.contract));
    for reference in &finding.affects {
        out.push_str(&format!(
            "  = consumer {} — {}:{}\n",
            reference.consumer, reference.source, reference.span.line
        ));
    }
    if let Some(note) = &finding.note {
        out.push_str(&format!("  = {note}\n"));
    }
    out
}

#[cfg(not(feature = "cli"))]
fn severity_label(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => "info",
        Severity::Warning => "warning",
        Severity::Error => "error",
    }
}

/// The `help:` block: the ways out, then where to read more.
///
/// brake names the applicable strategies and what each costs, and does not
/// pick between them — which one fits depends on whether you control every
/// consumer and whether you have a version scheme, neither of which brake can
/// see. Saying so is more useful than a confident guess.
#[cfg(feature = "cli")]
fn help_text(rule: &catalogue::Rule, finding: &Finding) -> String {
    let remediations = finding.remediations();
    if remediations.is_empty() {
        return format!(
            "{}\n\nrun `brake explain {}` for the full rationale",
            rule.summary, rule.id
        );
    }

    let count = match remediations.len() {
        1 => "one way".to_owned(),
        2 => "two ways".to_owned(),
        3 => "three ways".to_owned(),
        other => format!("{other} ways"),
    };
    let mut out = format!("{count} to make this change safely\n");
    for (index, remediation) in remediations.iter().enumerate() {
        // No leading indent: annotate-snippets already indents the whole
        // help block, and the two compound into a hanging column.
        out.push_str(&format!(
            "{}. {} — {}\n   costs: {}\n",
            index + 1,
            remediation.strategy,
            remediation.summary,
            remediation.cost
        ));
    }
    // Only where there is a genuine choice: a single option is not a
    // decision, and saying otherwise reads as boilerplate.
    if remediations.len() > 1 {
        out.push_str(
            "\nwhich one fits depends on whether you control every consumer — brake \
cannot see that.\n",
        );
    } else {
        out.push('\n');
    }
    out.push_str(&format!(
        "run `brake explain {}` for why this breaks",
        rule.id
    ));
    out
}

/// Byte offsets for the annotated span, clamped to the line.
///
/// A one-based line and column from the ingester become the byte range
/// `annotate-snippets` needs, without assuming the file is ASCII.
#[cfg(feature = "cli")]
fn line_range(source: &str, line: usize, column: usize) -> Option<(usize, usize)> {
    let mut offset = 0;
    for (index, text) in source.split_inclusive('\n').enumerate() {
        if index + 1 == line {
            let trimmed = text.trim_end_matches(['\n', '\r']);
            let start_in_line = trimmed
                .char_indices()
                .nth(column.saturating_sub(1))
                .map_or(trimmed.len(), |(byte, _)| byte);
            let start = offset + start_in_line;
            // Underline the token at the column, or the rest of the line.
            let token_length = trimmed[start_in_line..]
                .find(|c: char| c.is_whitespace() || c == ':')
                .unwrap_or(trimmed.len() - start_in_line);
            let end = start + token_length.max(1);
            return Some((start, end.min(offset + trimmed.len()).max(start + 1)));
        }
        offset += text.len();
    }
    None
}

#[cfg(test)]
mod tests {
    use crate::Severity;
    use crate::contract::Span;
    use crate::report::{Report, Unavailable};
    use crate::rules::Finding;

    use super::render;

    fn finding(rule_id: &'static str, severity: Severity, span: Option<Span>) -> Finding {
        Finding {
            affects: Vec::new(),
            note: None,
            rule_id,
            severity,
            contract: "payments".to_owned(),
            message: "response field removed: field `customer_id`".to_owned(),
            method: Some("GET".to_owned()),
            path: Some("/payments/{id}".to_owned()),
            pointer: "/paths/~1payments~1{id}/get/responses/200".to_owned(),
            subject: Some("customer_id".to_owned()),
            span,
        }
    }

    fn report_with_source() -> Report {
        let mut report = Report::new(
            vec![finding(
                "response-field-removed",
                Severity::Error,
                Some(Span::new("api/openapi.yaml", 4, 9, "/paths")),
            )],
            Vec::new(),
            1,
        );
        report.sources.insert(
            "api/openapi.yaml".to_owned(),
            "openapi: 3.1.0\npaths:\n  /payments:\n        customer_id: gone\n".to_owned(),
        );
        report
    }

    #[test]
    fn quotes_the_offending_line_from_the_artifact() {
        let rendered = render(&report_with_source());
        assert!(rendered.contains("response-field-removed"), "{rendered}");
        assert!(rendered.contains("api/openapi.yaml"), "{rendered}");
        assert!(
            rendered.contains("customer_id"),
            "the diagnostic should quote the source line:\n{rendered}"
        );
        assert!(
            rendered.contains('^'),
            "the diagnostic should underline the span:\n{rendered}"
        );
    }

    #[test]
    fn tells_a_blocked_developer_how_to_make_the_change_safely() {
        let rendered = render(&report_with_source());

        assert!(
            rendered.contains("three ways to make this change safely"),
            "{rendered}"
        );
        assert!(rendered.contains("deprecate-then-remove"), "{rendered}");
        assert!(
            rendered.contains("`customer_id`"),
            "the strategy must name the field it is about:\n{rendered}"
        );
        // Options with no costs read as though they are all free.
        assert!(rendered.contains("costs:"), "{rendered}");
        // And brake must not pretend it can choose.
        assert!(
            rendered.contains("brake\ncannot see that") || rendered.contains("cannot see that"),
            "{rendered}"
        );
        assert!(
            rendered.contains("brake explain response-field-removed"),
            "{rendered}"
        );
    }

    #[test]
    fn names_the_contract_a_finding_came_from() {
        let rendered = render(&report_with_source());
        assert!(rendered.contains("payments"), "{rendered}");
    }

    #[test]
    fn renders_a_finding_with_no_source_text_available() {
        let report = Report::new(
            vec![finding(
                "endpoint-removed",
                Severity::Error,
                Some(Span::new(
                    "git:origin/main:api/openapi.yaml",
                    42,
                    9,
                    "/paths",
                )),
            )],
            Vec::new(),
            1,
        );
        let rendered = render(&report);
        assert!(
            rendered.contains("git:origin/main:api/openapi.yaml:42:9"),
            "{rendered}"
        );
    }

    #[test]
    fn distinguishes_a_tool_failure_from_an_api_break() {
        let report = Report::new(
            Vec::new(),
            vec![Unavailable {
                contract: Some("ledger".to_owned()),
                message: "baseline file missing".to_owned(),
            }],
            1,
        );
        let rendered = render(&report);
        assert!(rendered.contains("could not check `ledger`"), "{rendered}");
        assert!(rendered.contains("tool failure"), "{rendered}");
    }

    #[test]
    fn reports_how_much_was_checked_when_clean() {
        let rendered = render(&Report::new(Vec::new(), Vec::new(), 3));
        assert!(rendered.contains("3 contracts checked"), "{rendered}");
    }

    #[test]
    fn output_is_plain_text_with_no_terminal_escapes() {
        let rendered = render(&report_with_source());
        assert!(
            !rendered.contains('\u{1b}'),
            "piped output must not carry terminal escape sequences:\n{rendered:?}"
        );
    }

    #[test]
    fn rendering_is_byte_stable() {
        let report = report_with_source();
        assert_eq!(render(&report), render(&report));
    }
}