timebomb-cli 0.5.0

Scan source code for deadline-tagged fuses and fail when they detonate
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
//! Integration tests for the `timebomb bunker` feature and ratchet enforcement.

use std::io::Write as _;
use std::path::Path;

use chrono::NaiveDate;
use timebomb::baseline::{
    check_ratchet, load_baseline, run_baseline_save, run_baseline_show, Baseline,
};
use timebomb::cli::Cli;
use timebomb::config::{load_config, CliOverrides};

// ─── Helpers ──────────────────────────────────────────────────────────────────

fn fixed_today() -> NaiveDate {
    NaiveDate::parse_from_str("2025-06-01", "%Y-%m-%d").unwrap()
}

fn no_overrides() -> CliOverrides {
    CliOverrides::default()
}

/// Write a `.timebomb.toml` into a temp directory and return the dir.
fn write_config(content: &str) -> tempfile::TempDir {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join(".timebomb.toml");
    let mut f = std::fs::File::create(&config_path).unwrap();
    write!(f, "{}", content).unwrap();
    dir
}

// ─── Config field tests ───────────────────────────────────────────────────────

#[test]
fn test_config_max_detonated_parsed() {
    let dir = write_config("max_detonated = 5\n");
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    assert_eq!(cfg.max_detonated, Some(5));
}

#[test]
fn test_config_max_ticking_parsed() {
    let dir = write_config("max_ticking = 10\n");
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    assert_eq!(cfg.max_ticking, Some(10));
}

#[test]
fn test_config_max_fields_default_none() {
    let dir = tempfile::tempdir().unwrap();
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    assert_eq!(cfg.max_detonated, None);
    assert_eq!(cfg.max_ticking, None);
}

#[test]
fn test_config_both_max_fields_parsed() {
    let dir = write_config("max_detonated = 3\nmax_ticking = 7\n");
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    assert_eq!(cfg.max_detonated, Some(3));
    assert_eq!(cfg.max_ticking, Some(7));
}

// ─── baseline save tests ──────────────────────────────────────────────────────

#[test]
fn test_baseline_save_creates_file() {
    let dir = tempfile::tempdir().unwrap();

    // Write a file with one detonated fuse
    let mut f = std::fs::File::create(dir.path().join("main.rs")).unwrap();
    writeln!(f, "// TODO[2020-01-01]: expired").unwrap();

    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let baseline_path = dir.path().join(".timebomb-baseline.json");
    let generated_at = "2025-06-01T12:00:00Z";

    let code = run_baseline_save(
        dir.path(),
        &cfg,
        fixed_today(),
        &baseline_path,
        generated_at,
    )
    .unwrap();
    assert_eq!(code, 0);

    // File must exist and be parseable
    assert!(baseline_path.exists());
    let loaded = load_baseline(&baseline_path).unwrap().unwrap();
    assert_eq!(loaded.detonated, 1);
    assert_eq!(loaded.ticking, 0);
    assert_eq!(loaded.generated_at, generated_at);
}

#[test]
fn test_baseline_save_empty_dir_writes_zeros() {
    let dir = tempfile::tempdir().unwrap();
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let baseline_path = dir.path().join(".timebomb-baseline.json");

    run_baseline_save(dir.path(), &cfg, fixed_today(), &baseline_path, "ts").unwrap();

    let loaded = load_baseline(&baseline_path).unwrap().unwrap();
    assert_eq!(loaded.detonated, 0);
    assert_eq!(loaded.ticking, 0);
}

// ─── baseline ratchet enforcement via `sweep` ─────────────────────────────────

#[test]
fn test_sweep_exits_one_when_ratchet_violated() {
    use clap::Parser;

    let dir = tempfile::tempdir().unwrap();

    // Save a baseline with 0 detonated
    {
        let baseline = Baseline {
            generated_at: "2025-01-01T00:00:00Z".to_string(),
            detonated: 0,
            ticking: 0,
        };
        timebomb::baseline::save_baseline(&baseline, &dir.path().join(".timebomb-baseline.json"))
            .unwrap();
    }

    // Write a file with 1 detonated fuse — violates baseline
    {
        let mut f = std::fs::File::create(dir.path().join("main.rs")).unwrap();
        writeln!(f, "// TODO[2020-01-01]: expired").unwrap();
    }

    let cli = Cli::parse_from(["timebomb", "sweep", dir.path().to_str().unwrap()]);
    // run is private; invoke via the binary entry point through the public API instead
    // by constructing the args and calling sweep directly via library code
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let result = timebomb::scanner::scan(dir.path(), &cfg, fixed_today()).unwrap();
    let baseline = load_baseline(&dir.path().join(".timebomb-baseline.json"))
        .unwrap()
        .unwrap();

    let violations = check_ratchet(
        result.detonated().len(),
        result.ticking().len(),
        Some(&baseline),
        cfg.max_detonated,
        cfg.max_ticking,
    );
    assert!(!violations.is_empty(), "ratchet should be violated");
    // Also confirm cli parses without error
    let _ = cli;
}

#[test]
fn test_sweep_exits_zero_within_baseline() {
    let dir = tempfile::tempdir().unwrap();

    // Save a baseline with 2 detonated
    {
        let baseline = Baseline {
            generated_at: "2025-01-01T00:00:00Z".to_string(),
            detonated: 2,
            ticking: 0,
        };
        timebomb::baseline::save_baseline(&baseline, &dir.path().join(".timebomb-baseline.json"))
            .unwrap();
    }

    // Write a file with exactly 2 detonated fuses — same as baseline
    {
        let mut f = std::fs::File::create(dir.path().join("main.rs")).unwrap();
        writeln!(f, "// TODO[2020-01-01]: expired one").unwrap();
        writeln!(f, "// FIXME[2019-01-01]: expired two").unwrap();
    }

    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let result = timebomb::scanner::scan(dir.path(), &cfg, fixed_today()).unwrap();
    let baseline = load_baseline(&dir.path().join(".timebomb-baseline.json"))
        .unwrap()
        .unwrap();

    let violations = check_ratchet(
        result.detonated().len(),
        result.ticking().len(),
        Some(&baseline),
        cfg.max_detonated,
        cfg.max_ticking,
    );
    assert!(
        violations.is_empty(),
        "no ratchet violation when count matches baseline: {:?}",
        violations
    );
}

// ─── baseline show tests ──────────────────────────────────────────────────────

#[test]
fn test_baseline_show_no_file_exits_zero() {
    let dir = tempfile::tempdir().unwrap();
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let baseline_path = dir.path().join(".timebomb-baseline.json");

    // No baseline file — should still succeed with exit code 0
    let code = run_baseline_show(dir.path(), &cfg, fixed_today(), &baseline_path).unwrap();
    assert_eq!(code, 0);
}

#[test]
fn test_baseline_show_with_file_exits_zero() {
    let dir = tempfile::tempdir().unwrap();
    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let baseline_path = dir.path().join(".timebomb-baseline.json");

    // Save a baseline first
    run_baseline_save(dir.path(), &cfg, fixed_today(), &baseline_path, "ts").unwrap();

    let code = run_baseline_show(dir.path(), &cfg, fixed_today(), &baseline_path).unwrap();
    assert_eq!(code, 0);
}

// ─── CLI parsing tests ────────────────────────────────────────────────────────

#[test]
fn test_cli_bunker_save_defaults() {
    use clap::Parser;
    use timebomb::cli::{BaselineCommand, Command};

    let cli = Cli::parse_from(["timebomb", "bunker", "save"]);
    match cli.command {
        Command::Bunker(args) => match args.command {
            BaselineCommand::Save(a) => {
                assert_eq!(a.path, ".");
                assert_eq!(a.baseline_file, ".timebomb-baseline.json");
                assert!(a.config.is_none());
                assert!(a.fuse.is_none());
            }
            _ => panic!("expected Save"),
        },
        _ => panic!("expected Bunker"),
    }
}

#[test]
fn test_cli_bunker_show_defaults() {
    use clap::Parser;
    use timebomb::cli::{BaselineCommand, Command};

    let cli = Cli::parse_from(["timebomb", "bunker", "show"]);
    match cli.command {
        Command::Bunker(args) => match args.command {
            BaselineCommand::Show(a) => {
                assert_eq!(a.path, ".");
                assert_eq!(a.baseline_file, ".timebomb-baseline.json");
                assert!(a.config.is_none());
                assert!(a.fuse.is_none());
            }
            _ => panic!("expected Show"),
        },
        _ => panic!("expected Bunker"),
    }
}

#[test]
fn test_cli_bunker_save_custom_file() {
    use clap::Parser;
    use timebomb::cli::{BaselineCommand, Command};

    let cli = Cli::parse_from([
        "timebomb",
        "bunker",
        "save",
        "--baseline-file",
        "custom.json",
    ]);
    match cli.command {
        Command::Bunker(args) => match args.command {
            BaselineCommand::Save(a) => {
                assert_eq!(a.baseline_file, "custom.json");
            }
            _ => panic!("expected Save"),
        },
        _ => panic!("expected Bunker"),
    }
}

#[test]
fn test_cli_bunker_show_custom_file() {
    use clap::Parser;
    use timebomb::cli::{BaselineCommand, Command};

    let cli = Cli::parse_from([
        "timebomb",
        "bunker",
        "show",
        "--baseline-file",
        "custom.json",
    ]);
    match cli.command {
        Command::Bunker(args) => match args.command {
            BaselineCommand::Show(a) => {
                assert_eq!(a.baseline_file, "custom.json");
            }
            _ => panic!("expected Show"),
        },
        _ => panic!("expected Bunker"),
    }
}

#[test]
fn test_cli_bunker_save_with_path_and_fuse() {
    use clap::Parser;
    use timebomb::cli::{BaselineCommand, Command};

    let cli = Cli::parse_from(["timebomb", "bunker", "save", "./src", "--fuse", "14d"]);
    match cli.command {
        Command::Bunker(args) => match args.command {
            BaselineCommand::Save(a) => {
                assert_eq!(a.path, "./src");
                assert_eq!(a.fuse, Some("14d".to_string()));
            }
            _ => panic!("expected Save"),
        },
        _ => panic!("expected Bunker"),
    }
}

// ─── max_detonated config ratchet tests ─────────────────────────────────────────

#[test]
fn test_ratchet_max_detonated_from_config_causes_violation() {
    let dir = write_config("max_detonated = 0\n");

    // Write a file with 1 detonated fuse — exceeds max_detonated=0
    {
        let mut f = std::fs::File::create(dir.path().join("main.rs")).unwrap();
        writeln!(f, "// TODO[2020-01-01]: expired").unwrap();
    }

    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let result = timebomb::scanner::scan(dir.path(), &cfg, fixed_today()).unwrap();

    let violations = check_ratchet(
        result.detonated().len(),
        result.ticking().len(),
        None,
        cfg.max_detonated,
        cfg.max_ticking,
    );
    assert!(
        !violations.is_empty(),
        "should violate max_detonated=0 with 1 detonated"
    );
}

#[test]
fn test_ratchet_max_detonated_from_config_no_violation_at_limit() {
    let dir = write_config("max_detonated = 1\n");

    // Write a file with 1 detonated fuse — exactly at limit
    {
        let mut f = std::fs::File::create(dir.path().join("main.rs")).unwrap();
        writeln!(f, "// TODO[2020-01-01]: expired").unwrap();
    }

    let cfg = load_config(dir.path(), &no_overrides()).unwrap();
    let result = timebomb::scanner::scan(dir.path(), &cfg, fixed_today()).unwrap();

    let violations = check_ratchet(
        result.detonated().len(),
        result.ticking().len(),
        None,
        cfg.max_detonated,
        cfg.max_ticking,
    );
    assert!(
        violations.is_empty(),
        "should not violate max_detonated=1 with 1 detonated: {:?}",
        violations
    );
}

// ─── check_ratchet pure function tests (additional coverage) ──────────────────

#[test]
fn test_check_ratchet_all_zero_no_baseline() {
    let violations = check_ratchet(0, 0, None, None, None);
    assert!(violations.is_empty());
}

#[test]
fn test_check_ratchet_four_violations_at_once() {
    let baseline = Baseline {
        generated_at: "2025-01-01T00:00:00Z".to_string(),
        detonated: 1,
        ticking: 1,
    };
    // detonated=5 > max_detonated=2 AND > baseline=1
    // ticking=10 > max_ticking=5 AND > baseline=1
    let violations = check_ratchet(5, 10, Some(&baseline), Some(2), Some(5));
    assert_eq!(violations.len(), 4);
}

#[test]
fn test_check_ratchet_baseline_equal_not_violated() {
    let baseline = Baseline {
        generated_at: "2025-01-01T00:00:00Z".to_string(),
        detonated: 3,
        ticking: 2,
    };
    // Equal counts should not trigger ratchet
    let violations = check_ratchet(3, 2, Some(&baseline), None, None);
    assert!(violations.is_empty());
}

/// Check that load_baseline on a directory with a valid .timebomb-baseline.json
/// roundtrips correctly through save_baseline.
#[test]
fn test_load_baseline_from_saved() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join(".timebomb-baseline.json");

    let original = Baseline {
        generated_at: "2025-06-01T00:00:00+00:00".to_string(),
        detonated: 7,
        ticking: 3,
    };
    timebomb::baseline::save_baseline(&original, &path).unwrap();

    let loaded = load_baseline(&path).unwrap().unwrap();
    assert_eq!(loaded.detonated, 7);
    assert_eq!(loaded.ticking, 3);
    assert_eq!(loaded.generated_at, original.generated_at);
}

/// Confirm the baseline file is valid JSON (not just TOML or other format).
#[test]
fn test_baseline_file_is_json() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("baseline.json");

    let baseline = Baseline {
        generated_at: "2025-01-01T00:00:00Z".to_string(),
        detonated: 1,
        ticking: 2,
    };
    timebomb::baseline::save_baseline(&baseline, &path).unwrap();

    let content = std::fs::read_to_string(&path).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
    assert_eq!(parsed["detonated"], 1);
    assert_eq!(parsed["ticking"], 2);
    assert_eq!(parsed["generated_at"], "2025-01-01T00:00:00Z");
}

/// Verify load_baseline returns Err when the file exists but contains invalid JSON.
#[test]
fn test_load_baseline_corrupt_file_returns_error() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("bad.json");
    std::fs::write(&path, b"not json at all").unwrap();

    let result = load_baseline(Path::new(path.to_str().unwrap()));
    assert!(result.is_err(), "corrupt JSON should return Err");
}