Skip to main content

devclean/
render.rs

1use std::fmt::Write as _;
2use std::path::{Path, PathBuf};
3use std::time::{SystemTime, UNIX_EPOCH};
4
5use anyhow::Result;
6use serde_json::json;
7
8use crate::model::{Candidate, OutputFormat, RenderOptions, ScanReport};
9use crate::scanner::totals_by_category;
10
11/// Renders a scan report without path redaction.
12///
13/// # Errors
14///
15/// Returns an error when JSON serialization fails.
16pub fn render(report: &ScanReport, format: OutputFormat) -> Result<String> {
17    render_with_options(report, format, RenderOptions::default())
18}
19
20/// Renders a scan report with presentation controls.
21///
22/// # Errors
23///
24/// Returns an error when JSON serialization fails.
25pub fn render_with_options(
26    report: &ScanReport,
27    format: OutputFormat,
28    options: RenderOptions,
29) -> Result<String> {
30    let display_report = if options.redact_paths {
31        redact_report(report)
32    } else {
33        report.clone()
34    };
35    match format {
36        OutputFormat::Table => Ok(render_table(&display_report)),
37        OutputFormat::Json => Ok(serde_json::to_string_pretty(&display_report)?),
38        OutputFormat::Jsonl => render_jsonl(&display_report),
39        OutputFormat::Html => Ok(render_html(&display_report)),
40    }
41}
42
43/// Formats bytes with binary units.
44#[must_use]
45pub fn human_bytes(bytes: u64) -> String {
46    const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
47    let mut unit = 0;
48    let mut divisor = 1_u64;
49    while bytes / divisor >= 1024 && unit < UNITS.len() - 1 {
50        divisor = divisor.saturating_mul(1024);
51        unit += 1;
52    }
53    if unit == 0 {
54        format!("{bytes} {}", UNITS[unit])
55    } else {
56        let whole = bytes / divisor;
57        let hundredths = bytes % divisor * 100 / divisor;
58        format!("{whole}.{hundredths:02} {}", UNITS[unit])
59    }
60}
61
62fn render_table(report: &ScanReport) -> String {
63    let mut output = String::new();
64    let _ = writeln!(
65        output,
66        "{:<23} {:>12} {:>10}  PATH",
67        "CATEGORY", "SIZE", "AGE"
68    );
69    let _ = writeln!(output, "{}", "-".repeat(92));
70    for candidate in &report.candidates {
71        let _ = writeln!(
72            output,
73            "{:<23} {:>12} {:>10}  {}",
74            candidate.category,
75            human_bytes(candidate.bytes),
76            human_age(candidate),
77            candidate.path.display()
78        );
79    }
80    let _ = writeln!(output, "{}", "-".repeat(92));
81    let _ = writeln!(
82        output,
83        "{} candidates, {} reclaimable",
84        report.candidates.len(),
85        human_bytes(report.total_bytes)
86    );
87    for warning in &report.warnings {
88        let _ = writeln!(output, "warning: {warning}");
89    }
90    output
91}
92
93fn render_jsonl(report: &ScanReport) -> Result<String> {
94    let mut output = String::new();
95    for candidate in &report.candidates {
96        writeln!(
97            output,
98            "{}",
99            serde_json::to_string(&json!({"type": "candidate", "candidate": candidate}))?
100        )?;
101    }
102    writeln!(
103        output,
104        "{}",
105        serde_json::to_string(&json!({
106            "type": "summary",
107            "candidate_count": report.candidates.len(),
108            "total_bytes": report.total_bytes,
109            "warnings": report.warnings,
110        }))?
111    )?;
112    Ok(output)
113}
114
115fn render_html(report: &ScanReport) -> String {
116    let totals = totals_by_category(report);
117    let mut cards = String::new();
118    for (category, bytes) in totals {
119        let _ = write!(
120            cards,
121            "<article><span>{}</span><strong>{}</strong></article>",
122            escape_html(&category.to_string()),
123            human_bytes(bytes)
124        );
125    }
126
127    let mut rows = String::new();
128    for candidate in &report.candidates {
129        let _ = write!(
130            rows,
131            "<tr><td>{}</td><td><code>{}</code></td><td>{}</td><td>{}</td><td>{}</td></tr>",
132            escape_html(&candidate.category.to_string()),
133            escape_html(&candidate.path.to_string_lossy()),
134            human_bytes(candidate.bytes),
135            human_age(candidate),
136            escape_html(&candidate.reason)
137        );
138    }
139
140    let mut warnings = String::new();
141    for warning in &report.warnings {
142        let _ = write!(warnings, "<li>{}</li>", escape_html(warning));
143    }
144    format!(
145        r#"<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>devclean scan report</title><style>
146:root{{color-scheme:dark;font-family:Inter,ui-sans-serif,system-ui;background:#08111f;color:#ecf3ff}}body{{margin:0}}main{{max-width:1180px;margin:auto;padding:48px 24px}}h1{{font-size:42px;margin-bottom:8px}}.lead{{color:#aebdd2}}.summary{{display:grid;grid-template-columns:repeat(auto-fit,minmax(170px,1fr));gap:12px;margin:28px 0}}article{{background:#111d31;border:1px solid #263854;border-radius:14px;padding:16px}}article span{{display:block;color:#94a7c2;font-size:12px}}article strong{{font-size:22px}}.total{{color:#5fe0a5}}.table{{overflow:auto;border:1px solid #263854;border-radius:14px}}table{{width:100%;border-collapse:collapse;min-width:900px}}th,td{{padding:12px;text-align:left;border-bottom:1px solid #263854}}th{{background:#15233a;color:#cbd9ed}}td{{color:#b7c5da}}code{{color:#dbe9ff}}.warnings{{color:#ffcf72}}</style></head><body><main><h1>devclean scan</h1><p class="lead">Read-only inventory of rebuildable development artifacts.</p><p class="total"><strong>{}</strong> across {} candidates</p><section class="summary">{}</section><div class="table"><table><thead><tr><th>Category</th><th>Path</th><th>Size</th><th>Age</th><th>Evidence</th></tr></thead><tbody>{}</tbody></table></div><section class="warnings"><h2>Warnings</h2><ul>{}</ul></section></main></body></html>"#,
147        human_bytes(report.total_bytes),
148        report.candidates.len(),
149        cards,
150        rows,
151        warnings
152    )
153}
154
155fn redact_report(report: &ScanReport) -> ScanReport {
156    let mut redacted = report.clone();
157    for candidate in &mut redacted.candidates {
158        candidate.path = redact_path(&candidate.path, &report.roots);
159    }
160    redacted.roots = report
161        .roots
162        .iter()
163        .enumerate()
164        .map(|(index, _)| PathBuf::from(format!("<root:{}>", index + 1)))
165        .collect();
166    redacted.warnings = report
167        .warnings
168        .iter()
169        .map(|warning| redact_text(warning, &report.roots))
170        .collect();
171    redacted
172}
173
174fn redact_text(value: &str, roots: &[PathBuf]) -> String {
175    let mut redacted = value.to_owned();
176    for (index, root) in roots.iter().enumerate() {
177        let root_text = root.to_string_lossy();
178        redacted = redacted.replace(root_text.as_ref(), &format!("<root:{}>", index + 1));
179    }
180    if let Some(base) = directories::BaseDirs::new() {
181        let home = base.home_dir().to_string_lossy();
182        redacted = redacted.replace(home.as_ref(), "<home>");
183    }
184    redacted
185}
186
187fn redact_path(path: &Path, roots: &[PathBuf]) -> PathBuf {
188    for (index, root) in roots.iter().enumerate() {
189        if let Ok(relative) = path.strip_prefix(root) {
190            return PathBuf::from(format!("<root:{}>", index + 1)).join(relative);
191        }
192    }
193    if let Some(base) = directories::BaseDirs::new() {
194        if let Ok(relative) = path.strip_prefix(base.home_dir()) {
195            return PathBuf::from("<home>").join(relative);
196        }
197    }
198    PathBuf::from("<external>").join(path.file_name().unwrap_or_default())
199}
200
201fn human_age(candidate: &Candidate) -> String {
202    let Some(modified) = candidate.modified_at_unix else {
203        return "unknown".to_owned();
204    };
205    let now = SystemTime::now()
206        .duration_since(UNIX_EPOCH)
207        .map_or(modified, |duration| duration.as_secs());
208    let seconds = now.saturating_sub(modified);
209    if seconds >= 86_400 {
210        format!("{}d", seconds / 86_400)
211    } else if seconds >= 3_600 {
212        format!("{}h", seconds / 3_600)
213    } else if seconds >= 60 {
214        format!("{}m", seconds / 60)
215    } else {
216        format!("{seconds}s")
217    }
218}
219
220fn escape_html(value: &str) -> String {
221    value
222        .replace('&', "&amp;")
223        .replace('<', "&lt;")
224        .replace('>', "&gt;")
225        .replace('"', "&quot;")
226        .replace('\'', "&#39;")
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232    use crate::model::{Category, ScanReport};
233
234    fn report(path: &str) -> ScanReport {
235        ScanReport {
236            roots: vec![PathBuf::from("/private/project")],
237            candidates: vec![Candidate {
238                category: Category::NodeModules,
239                path: PathBuf::from(path),
240                bytes: 1024,
241                reason: "test".to_owned(),
242                modified_at_unix: None,
243            }],
244            warnings: Vec::new(),
245            total_bytes: 1024,
246            protect_git_tracked: true,
247        }
248    }
249
250    #[test]
251    fn human_bytes_should_use_binary_units() {
252        assert_eq!(human_bytes(1024), "1.00 KiB");
253    }
254
255    #[test]
256    fn render_html_should_escape_candidate_paths() -> Result<()> {
257        let output = render(&report("/tmp/<script>"), OutputFormat::Html)?;
258
259        assert!(!output.contains("<script>"));
260        Ok(())
261    }
262
263    #[test]
264    fn render_should_redact_paths_in_json() -> Result<()> {
265        let output = render_with_options(
266            &report("/private/project/node_modules"),
267            OutputFormat::Json,
268            RenderOptions { redact_paths: true },
269        )?;
270
271        assert!(!output.contains("/private/project"));
272        Ok(())
273    }
274
275    #[test]
276    fn render_should_redact_paths_inside_warnings() -> Result<()> {
277        let mut input = report("/private/project/node_modules");
278        input
279            .warnings
280            .push("protected /private/project/node_modules".to_owned());
281
282        let output = render_with_options(
283            &input,
284            OutputFormat::Json,
285            RenderOptions { redact_paths: true },
286        )?;
287
288        assert!(!output.contains("/private/project"));
289        Ok(())
290    }
291}