Repository navigation
Expand file tree
/
Copy pathrender.rs
More file actions
279 lines (262 loc) · 9.17 KB
/
Copy pathrender.rs
File metadata and controls
279 lines (262 loc) · 9.17 KB
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
//! Markdown rendering of a [`Report`] into the PR comment.
//!
//! Layout priority (from the spec): headline sentence first, one focused table,
//! the "why" callout, everything else collapsed. If the reader has to scroll to
//! learn the point, we failed.
use crate::attribute::Attribution;
use crate::compare::{Report, Status};
use std::collections::BTreeMap;
use std::fmt::Write;
/// Hidden marker so re-runs can find and PATCH the existing comment instead of
/// posting a new one each time.
pub const MARKER: &str = "<!-- bloatbot -->";
/// Format a byte count as a human-readable string using binary (KiB/MiB) units,
/// matching how `cargo bloat` reports sizes.
pub fn human_bytes(n: u64) -> String {
const KIB: f64 = 1024.0;
const MIB: f64 = KIB * 1024.0;
const GIB: f64 = MIB * 1024.0;
let f = n as f64;
if f >= GIB {
format!("{:.2} GiB", f / GIB)
} else if f >= MIB {
format!("{:.2} MiB", f / MIB)
} else if f >= KIB {
format!("{:.1} KiB", f / KIB)
} else {
format!("{n} B")
}
}
/// Format a signed delta with an explicit sign, e.g. `+41.0 KiB`, `-80.0 KiB`, `0 B`.
pub fn human_delta(delta: i64) -> String {
match delta {
0 => "0 B".to_string(),
d if d > 0 => format!("+{}", human_bytes(d as u64)),
d => format!("-{}", human_bytes(d.unsigned_abs())),
}
}
fn status_icon(status: Status, is_workspace: bool) -> &'static str {
match status {
Status::New => "🆕",
Status::Removed => "🗑️",
Status::Grew if is_workspace => "🔺",
Status::Grew => "🔺",
Status::Shrank => "🔻",
Status::Unchanged => "▪️",
}
}
fn pct_cell(row: &crate::compare::CrateDelta) -> String {
match row.status {
Status::New => "new".to_string(),
Status::Removed => "removed".to_string(),
_ => match row.delta_percent() {
Some(p) => format!("{p:+.1}%"),
None => "—".to_string(),
},
}
}
/// Render the full sticky comment body.
///
/// `attributions` maps crate name -> cause attribution (lock-diff + dependency
/// chain). It is optional so the core diff still renders when attribution is off
/// or unavailable (e.g. fork PRs).
pub fn render(report: &Report, attributions: &BTreeMap<String, Attribution>) -> String {
let mut out = String::new();
let _ = writeln!(out, "{MARKER}");
// ---- Headline -----------------------------------------------------------
let delta = report.file_delta();
let pct = report
.file_delta_percent()
.map(|p| format!(" ({p:+.1}%)"))
.unwrap_or_default();
let verb = if delta > 0 {
"grew"
} else if delta < 0 {
"shrank"
} else {
"is unchanged"
};
if delta == 0 {
let _ = writeln!(out, "### 📦 Binary size: `{}` is unchanged", report.binary);
} else {
let _ = writeln!(
out,
"### 📦 Binary size: `{}` {} {}{}",
report.binary,
verb,
human_delta(delta),
pct
);
}
let _ = writeln!(out);
let _ = writeln!(
out,
"**{} → {}**, gzip **{} → {}**",
human_bytes(report.base_file_bytes),
human_bytes(report.head_file_bytes),
human_bytes(report.base_gzip_bytes),
human_bytes(report.head_gzip_bytes),
);
let _ = writeln!(out);
// ---- "Your code" vs dependencies split ---------------------------------
let (yours, deps): (Vec<_>, Vec<_>) = report.significant_rows().partition(|r| r.is_workspace);
let yours_delta: i64 = yours.iter().map(|r| r.delta).sum();
let deps_delta: i64 = deps.iter().map(|r| r.delta).sum();
if !yours.is_empty() || !deps.is_empty() {
let _ = writeln!(
out,
"`.text` attribution: **{} from dependencies**, **{} from your code**.",
human_delta(deps_delta),
human_delta(yours_delta),
);
let _ = writeln!(out);
}
// Reconcile the headline (whole-file) against what per-crate `.text` attribution
// can explain. The remainder is data/rodata/padding that `cargo bloat --crates`
// doesn't break down — surface it rather than let the numbers appear not to add up.
let unattributed = report.unattributed_delta();
if unattributed.unsigned_abs() >= report.noise_floor {
let _ = writeln!(
out,
"_{} of the file change is outside `.text` (data/rodata/padding), which \
`cargo bloat` can't attribute per-crate._",
human_delta(unattributed),
);
let _ = writeln!(out);
}
// ---- Focused table: the top movers -------------------------------------
let significant: Vec<_> = report.significant_rows().collect();
if significant.is_empty() {
let _ = writeln!(
out,
"_No crate changed by more than the {} noise floor._",
human_bytes(report.noise_floor)
);
let _ = writeln!(out);
} else {
const TOP_N: usize = 8;
let _ = writeln!(out, "| Crate | Base | Head | Δ | Δ% |");
let _ = writeln!(out, "|-------|-----:|-----:|-----:|-----:|");
for row in significant.iter().take(TOP_N) {
let label = if row.is_workspace {
format!("{} (you)", row.name)
} else {
row.name.clone()
};
let _ = writeln!(
out,
"| {} {} | {} | {} | {} | {} |",
status_icon(row.status, row.is_workspace),
label,
human_bytes(row.base),
human_bytes(row.head),
human_delta(row.delta),
pct_cell(row),
);
}
if significant.len() > TOP_N {
let _ = writeln!(
out,
"\n_…and {} more changed crate(s) — see full breakdown below._",
significant.len() - TOP_N
);
}
let _ = writeln!(out);
}
// ---- The "why" callout: cause attribution ------------------------------
let new_deps: Vec<_> = report.new_dependencies().collect();
if !new_deps.is_empty() {
let _ = writeln!(out, "**New dependencies introduced by this PR:**");
let _ = writeln!(out);
for row in &new_deps {
let attr = attributions.get(&row.name);
let chain = attr
.and_then(|a| a.chain.as_ref())
.map(|c| c.join(" → "))
.unwrap_or_else(|| row.name.clone());
let lock_note = match attr.map(|a| a.newly_in_lock) {
Some(true) => " (added in `Cargo.lock`)",
_ => "",
};
let _ = writeln!(
out,
"- `{}` (+{}) — pulled in via `{}`{}",
row.name,
human_bytes(row.head),
chain,
lock_note,
);
}
let _ = writeln!(out);
}
// ---- Collapsed full breakdown ------------------------------------------
let _ = writeln!(
out,
"<details><summary>Full breakdown ({} crates)</summary>\n",
report.rows.len()
);
let _ = writeln!(out, "| Crate | Base | Head | Δ |");
let _ = writeln!(out, "|-------|-----:|-----:|-----:|");
for row in &report.rows {
let label = if row.is_workspace {
format!("{} (you)", row.name)
} else {
row.name.clone()
};
let _ = writeln!(
out,
"| {} | {} | {} | {} |",
label,
human_bytes(row.base),
human_bytes(row.head),
human_delta(row.delta),
);
}
if report.below_floor_count > 0 {
let _ = writeln!(
out,
"\n_{} crate(s) changed by less than the {} floor ({} net)._",
report.below_floor_count,
human_bytes(report.noise_floor),
human_delta(report.below_floor_net),
);
}
let _ = writeln!(out, "\n</details>");
let _ = writeln!(out);
// ---- Footer -------------------------------------------------------------
if report.toolchain_mismatch() {
let _ = writeln!(
out,
"> ⚠️ Toolchain mismatch: base built with `{}`, head with `{}`. \
Part of this delta may be compiler noise.",
report.base_toolchain, report.head_toolchain
);
let _ = writeln!(out);
}
let _ = writeln!(
out,
"_Base `{}` · head `{}` · toolchain `{}`. Noise floor {}. Measured by [bloatbot](https://github.com/Asuddle/BloatBot)._",
report.base_ref,
report.head_ref,
report.head_toolchain,
human_bytes(report.noise_floor),
);
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn human_bytes_units() {
assert_eq!(human_bytes(512), "512 B");
assert_eq!(human_bytes(1024), "1.0 KiB");
assert_eq!(human_bytes(41_984), "41.0 KiB");
assert_eq!(human_bytes(1_603_200), "1.53 MiB");
}
#[test]
fn human_delta_signs() {
assert_eq!(human_delta(0), "0 B");
assert_eq!(human_delta(41_984), "+41.0 KiB");
assert_eq!(human_delta(-1024), "-1.0 KiB");
}
}