dead-poets 0.1.1

Find unused (dead) gettext PO/POT keys across a polyglot codebase (PHP, Twig, JS/TS) via real AST parsing.
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
//! Reporter — render the liveness result and decide the process exit code
//! (PLAN Addendum 2 §7, §8).
//!
//! Two formats mirror the same buckets:
//! - **text**: a one-line scope caveat header, the ranked `Dead` list (colored),
//!   the `Suspect` list (literal present but no modeled call), the per-language
//!   blind summary, and a count line.
//! - **json**: `dead` / `suspect` / `alive` (with `alive_via`) / `blind`.
//!
//! Exit policy is `fail_on`: `never` → 0; `dead` → 1 if any Dead; `dead-or-blind`
//! → 1 if any Dead or any blind site. `Suspect` is exit-neutral by design — it is
//! a review hint, not a failure. Code `2` (operational error) is owned by the
//! CLI, not this module.

use std::collections::BTreeMap;

use anyhow::Result;
use colored::Colorize;
use serde::Serialize;

use crate::audit::{AuditReport, Trace};
use crate::config::{FailOn, OutputFormat};
use crate::liveness::{AliveVia, LivenessReport, Status};
use crate::po::PoKey;

/// One-line caveat printed on every report: static analysis can't see external
/// consumers, so a `Dead` key may still be used outside the scanned roots.
pub const SCOPE_CAVEAT: &str = "scope = scanned source roots only; external consumers (DB/config, other services, email/cron templates) are invisible — verify in your TMS before deleting.";

fn alive_via_str(via: AliveVia) -> &'static str {
    match via {
        AliveVia::Literal => "literal",
        AliveVia::Guard => "guard",
        AliveVia::Whitelist => "whitelist",
    }
}

/// Dead keys sorted for stable, reviewable output.
fn sorted_dead(report: &LivenessReport) -> Vec<&PoKey> {
    let mut dead: Vec<&PoKey> = report.dead().map(|v| &v.key).collect();
    dead.sort_by(|a, b| (&a.msgctxt, &a.msgid).cmp(&(&b.msgctxt, &b.msgid)));
    dead
}

/// Suspect keys sorted for stable output.
fn sorted_suspect(report: &LivenessReport) -> Vec<&PoKey> {
    let mut suspect: Vec<&PoKey> = report.suspect().map(|v| &v.key).collect();
    suspect.sort_by(|a, b| (&a.msgctxt, &a.msgid).cmp(&(&b.msgctxt, &b.msgid)));
    suspect
}

/// Render a key for display: `[ctxt] msgid (+ plural)`.
fn display_key(key: &PoKey) -> String {
    let mut s = String::new();
    if let Some(ctxt) = &key.msgctxt {
        s.push_str(&format!("[{ctxt}] "));
    }
    s.push_str(&key.msgid);
    if let Some(plural) = &key.msgid_plural {
        s.push_str(&format!("  / {plural}"));
    }
    s
}

fn blind_line(blind: &BTreeMap<String, usize>) -> String {
    if blind.is_empty() {
        return "Blind spots: none".to_string();
    }
    let parts: Vec<String> = blind.iter().map(|(k, v)| format!("{k}={v}")).collect();
    format!(
        "Blind spots (unverifiable call sites): {}",
        parts.join(", ")
    )
}

fn trace_str(trace: Trace) -> &'static str {
    match trace {
        Trace::Substring => "substring",
        Trace::Skeleton => "skeleton",
        Trace::None => "none",
    }
}

/// The advisory dead-bucket trust block (text). One headline number plus a
/// pointer to the full recheck list, which lives in the JSON output.
fn audit_block(audit: &AuditReport) -> String {
    let mut s = String::new();
    s.push_str(&format!(
        "Audit (dead-bucket trust): {} dead — {} no trace (high-confidence), {} substring, {} skeleton — recheck before deleting.\n",
        audit.dead_total, audit.no_trace, audit.substring, audit.skeleton,
    ));
    if !audit.traced.is_empty() {
        s.push_str(
            &format!(
                "  {} dead keys still trace to source — see --format json for the list.",
                audit.traced.len()
            )
            .dimmed()
            .to_string(),
        );
        s.push('\n');
    }
    s
}

/// Render the text report.
pub fn render_text(report: &LivenessReport, audit: Option<&AuditReport>) -> String {
    let mut out = String::new();
    out.push_str(&format!(
        "{} {}\n\n",
        "dead-poets".bold(),
        SCOPE_CAVEAT.dimmed()
    ));

    let dead = sorted_dead(report);
    if dead.is_empty() {
        out.push_str(&"No dead keys found.\n".green().to_string());
    } else {
        out.push_str(&format!(
            "{}\n",
            format!("Dead keys ({}):", dead.len()).bold()
        ));
        for key in &dead {
            out.push_str(&format!("  {}\n", display_key(key).red()));
        }
    }

    let suspect = sorted_suspect(report);
    if !suspect.is_empty() {
        out.push('\n');
        out.push_str(&format!(
            "{} {}\n",
            format!("Suspect ({}):", suspect.len()).bold(),
            "literal present in source but no modeled call — verify, don't delete".dimmed(),
        ));
        for key in &suspect {
            out.push_str(&format!("  {}\n", display_key(key).yellow()));
        }
    }

    out.push('\n');
    out.push_str(&blind_line(&report.blind));
    out.push('\n');
    out.push_str(&format!(
        "Summary: {} keys, {} alive, {} suspect, {} dead, {} blind\n",
        report.verdicts.len(),
        report.alive_count(),
        report.suspect_count(),
        report.dead_count(),
        report.total_blind(),
    ));

    if let Some(audit) = audit {
        out.push('\n');
        out.push_str(&audit_block(audit));
    }
    out
}

// --- JSON ------------------------------------------------------------------

#[derive(Serialize)]
struct JsonKey {
    #[serde(skip_serializing_if = "Option::is_none")]
    msgctxt: Option<String>,
    msgid: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    msgid_plural: Option<String>,
}

impl From<&PoKey> for JsonKey {
    fn from(k: &PoKey) -> Self {
        JsonKey {
            msgctxt: k.msgctxt.clone(),
            msgid: k.msgid.clone(),
            msgid_plural: k.msgid_plural.clone(),
        }
    }
}

#[derive(Serialize)]
struct JsonAliveKey {
    #[serde(flatten)]
    key: JsonKey,
    alive_via: &'static str,
}

#[derive(Serialize)]
struct JsonSummary {
    total: usize,
    alive: usize,
    suspect: usize,
    dead: usize,
    blind: usize,
}

#[derive(Serialize)]
struct JsonTracedKey {
    #[serde(flatten)]
    key: JsonKey,
    trace: &'static str,
}

#[derive(Serialize)]
struct JsonAudit {
    dead_total: usize,
    no_trace: usize,
    substring: usize,
    skeleton: usize,
    traced: Vec<JsonTracedKey>,
}

impl From<&AuditReport> for JsonAudit {
    fn from(a: &AuditReport) -> Self {
        JsonAudit {
            dead_total: a.dead_total,
            no_trace: a.no_trace,
            substring: a.substring,
            skeleton: a.skeleton,
            traced: a
                .traced
                .iter()
                .map(|(k, t)| JsonTracedKey {
                    key: JsonKey::from(k),
                    trace: trace_str(*t),
                })
                .collect(),
        }
    }
}

#[derive(Serialize)]
struct JsonReport {
    scope_caveat: &'static str,
    summary: JsonSummary,
    dead: Vec<JsonKey>,
    suspect: Vec<JsonKey>,
    alive: Vec<JsonAliveKey>,
    blind: BTreeMap<String, usize>,
    #[serde(skip_serializing_if = "Option::is_none")]
    audit: Option<JsonAudit>,
}

/// Render the JSON report.
pub fn render_json(report: &LivenessReport, audit: Option<&AuditReport>) -> Result<String> {
    let dead: Vec<JsonKey> = sorted_dead(report).into_iter().map(JsonKey::from).collect();
    let suspect: Vec<JsonKey> = sorted_suspect(report)
        .into_iter()
        .map(JsonKey::from)
        .collect();
    let alive: Vec<JsonAliveKey> = report
        .verdicts
        .iter()
        .filter_map(|v| match v.status {
            Status::Alive(via) => Some(JsonAliveKey {
                key: JsonKey::from(&v.key),
                alive_via: alive_via_str(via),
            }),
            Status::Suspect | Status::Dead => None,
        })
        .collect();

    let json = JsonReport {
        scope_caveat: SCOPE_CAVEAT,
        summary: JsonSummary {
            total: report.verdicts.len(),
            alive: report.alive_count(),
            suspect: report.suspect_count(),
            dead: report.dead_count(),
            blind: report.total_blind(),
        },
        dead,
        suspect,
        alive,
        blind: report.blind.clone(),
        audit: audit.map(JsonAudit::from),
    };
    Ok(serde_json::to_string_pretty(&json)?)
}

/// Render in the requested format.
pub fn render(
    report: &LivenessReport,
    audit: Option<&AuditReport>,
    format: OutputFormat,
) -> Result<String> {
    match format {
        OutputFormat::Text => Ok(render_text(report, audit)),
        OutputFormat::Json => render_json(report, audit),
    }
}

/// The process exit code implied by the report under `fail_on`. Operational
/// errors (code `2`) are decided by the caller, not here.
pub fn exit_code(report: &LivenessReport, fail_on: FailOn) -> i32 {
    match fail_on {
        FailOn::Never => 0,
        FailOn::Dead => i32::from(report.dead_count() > 0),
        FailOn::DeadOrBlind => i32::from(report.dead_count() > 0 || report.total_blind() > 0),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::liveness::{KeyVerdict, LivenessReport, Status};

    fn key(msgid: &str) -> PoKey {
        PoKey {
            msgctxt: None,
            msgid: msgid.to_string(),
            msgid_plural: None,
        }
    }

    fn report() -> LivenessReport {
        let mut blind = BTreeMap::new();
        blind.insert("js".to_string(), 2);
        blind.insert("twig".to_string(), 1);
        LivenessReport {
            verdicts: vec![
                KeyVerdict {
                    key: key("alive_lit"),
                    status: Status::Alive(AliveVia::Literal),
                },
                KeyVerdict {
                    key: key("alive_grd"),
                    status: Status::Alive(AliveVia::Guard),
                },
                KeyVerdict {
                    key: key("dead_two"),
                    status: Status::Dead,
                },
                KeyVerdict {
                    key: key("dead_one"),
                    status: Status::Dead,
                },
            ],
            blind,
        }
    }

    #[test]
    fn text_prints_only_dead_and_scope_header() {
        let text = render_text(&report(), None);
        // header carries the scope caveat
        assert!(text.contains("external consumers"));
        // both dead keys present, sorted
        let one = text.find("dead_one").unwrap();
        let two = text.find("dead_two").unwrap();
        assert!(one < two, "dead keys are sorted");
        // alive keys are NOT listed
        assert!(!text.contains("alive_lit"));
        assert!(!text.contains("alive_grd"));
        // blind summary present
        assert!(text.contains("js=2"));
        assert!(text.contains("twig=1"));
    }

    #[test]
    fn json_is_valid_and_dead_count_matches_text() {
        let r = report();
        let json = render_json(&r, None).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        // dead bucket count matches the report
        let dead = parsed["dead"].as_array().unwrap();
        assert_eq!(dead.len(), r.dead_count());
        assert_eq!(dead.len(), sorted_dead(&r).len());

        // alive carries alive_via
        let alive = parsed["alive"].as_array().unwrap();
        assert_eq!(alive.len(), 2);
        let vias: Vec<&str> = alive
            .iter()
            .map(|a| a["alive_via"].as_str().unwrap())
            .collect();
        assert!(vias.contains(&"literal"));
        assert!(vias.contains(&"guard"));

        // blind summary mirrored
        assert_eq!(parsed["blind"]["js"], 2);
        assert_eq!(parsed["summary"]["dead"], 2);
    }

    /// Suspect keys get their own labelled section (text) and bucket (json),
    /// are excluded from `alive`, and do not affect the exit code.
    #[test]
    fn suspect_rendered_and_exit_neutral() {
        let report = LivenessReport {
            verdicts: vec![
                KeyVerdict {
                    key: key("suspect_key"),
                    status: Status::Suspect,
                },
                KeyVerdict {
                    key: key("dead_key"),
                    status: Status::Dead,
                },
            ],
            blind: BTreeMap::new(),
        };

        let text = render_text(&report, None);
        assert!(text.contains("Suspect (1)"));
        assert!(text.contains("suspect_key"));
        assert!(text.contains("1 suspect"));

        let parsed: serde_json::Value =
            serde_json::from_str(&render_json(&report, None).unwrap()).unwrap();
        assert_eq!(parsed["summary"]["suspect"], 1);
        assert_eq!(parsed["suspect"][0]["msgid"], "suspect_key");
        assert!(parsed["alive"].as_array().unwrap().is_empty());

        // Suspect alone (no dead) must not fail the default `dead` gate.
        let suspect_only = LivenessReport {
            verdicts: vec![KeyVerdict {
                key: key("s"),
                status: Status::Suspect,
            }],
            blind: BTreeMap::new(),
        };
        assert_eq!(exit_code(&suspect_only, FailOn::Dead), 0);
    }

    /// With an `AuditReport` attached, the trust block appears in text and the
    /// `audit` object in JSON; the exit code is unaffected.
    #[test]
    fn audit_rendered_and_exit_neutral() {
        let r = report(); // 2 dead
        let audit = AuditReport {
            dead_total: 2,
            no_trace: 1,
            substring: 1,
            skeleton: 0,
            traced: vec![(key("dead_one"), Trace::Substring)],
        };

        let text = render_text(&r, Some(&audit));
        assert!(text.contains("Audit (dead-bucket trust): 2 dead"));
        assert!(text.contains("1 no trace"));
        assert!(text.contains("1 substring"));

        let parsed: serde_json::Value =
            serde_json::from_str(&render_json(&r, Some(&audit)).unwrap()).unwrap();
        assert_eq!(parsed["audit"]["dead_total"], 2);
        assert_eq!(parsed["audit"]["no_trace"], 1);
        assert_eq!(parsed["audit"]["substring"], 1);
        assert_eq!(parsed["audit"]["traced"][0]["msgid"], "dead_one");
        assert_eq!(parsed["audit"]["traced"][0]["trace"], "substring");

        // No audit -> no block, no json key.
        assert!(!render_text(&r, None).contains("Audit (dead-bucket trust)"));
        let no_audit: serde_json::Value =
            serde_json::from_str(&render_json(&r, None).unwrap()).unwrap();
        assert!(no_audit.get("audit").is_none());

        // Audit never changes the exit code.
        assert_eq!(exit_code(&r, FailOn::Dead), 1);
    }

    #[test]
    fn exit_codes_follow_fail_on() {
        let r = report(); // 2 dead, 3 blind
        assert_eq!(exit_code(&r, FailOn::Dead), 1);
        assert_eq!(exit_code(&r, FailOn::Never), 0);
        assert_eq!(exit_code(&r, FailOn::DeadOrBlind), 1);

        // a clean report
        let clean = LivenessReport {
            verdicts: vec![KeyVerdict {
                key: key("ok"),
                status: Status::Alive(AliveVia::Literal),
            }],
            blind: BTreeMap::new(),
        };
        assert_eq!(exit_code(&clean, FailOn::Dead), 0);
        assert_eq!(exit_code(&clean, FailOn::DeadOrBlind), 0);

        // clean of dead but has blind
        let mut blind = BTreeMap::new();
        blind.insert("js".to_string(), 1);
        let blindish = LivenessReport {
            verdicts: vec![],
            blind,
        };
        assert_eq!(exit_code(&blindish, FailOn::Dead), 0);
        assert_eq!(exit_code(&blindish, FailOn::DeadOrBlind), 1);
    }
}