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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! Logic for the `timebomb delay` subcommand.
//!
//! This module implements the core logic for bumping the expiry date of an
//! existing timebomb fuse in-place without manually editing the file.

use crate::add::{find_matching_lines, parse_target};
use crate::error::{Error, Result};
use chrono::{Duration, NaiveDate};
use std::io::{self, BufRead, Write};
use std::path::PathBuf;

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Core logic for `timebomb delay`.
///
/// All parameters are primitives so this compiles independently of `cli.rs`
/// changes.
///
/// # Parameters
/// - `target`   — `"path/to/file.rs:42"` when search is None; plain file path when search is Some
/// - `date_str` — optional `"YYYY-MM-DD"` new expiry date
/// - `in_days`  — optional number of days from `today` until new expiry
/// - `reason`   — optional reason text appended to the annotation
/// - `yes`      — skip confirmation prompt when `true`
/// - `today`    — the current date (injected for testability)
/// - `search`   — optional pattern; when Some, `target` is a plain file path
#[allow(clippy::too_many_arguments)]
pub fn run_snooze(
    target: &str,
    date_str: Option<&str>,
    in_days: Option<u32>,
    reason: Option<&str>,
    yes: bool,
    today: NaiveDate,
    search: Option<&str>,
) -> Result<i32> {
    // 1. Resolve file path and line number -----------------------------------
    let (file_path, line_number) = if let Some(pattern) = search {
        let path = PathBuf::from(target);
        let matches = find_matching_lines(&path, pattern)?;
        match matches.len() {
            0 => {
                return Err(Error::InvalidArgument(format!(
                    "no lines matching '{}' found in {}",
                    pattern, target
                )));
            }
            1 => {
                println!("matched line {}: {}", matches[0].0, matches[0].1.trim_end());
                (path, matches[0].0)
            }
            n => {
                let mut detail =
                    format!("pattern '{}' matched {} lines in {}:", pattern, n, target);
                for (ln, content) in &matches {
                    detail.push_str(&format!("\n  line {}: {}", ln, content.trim_end()));
                }
                detail.push_str("\nuse FILE:LINE to be specific");
                return Err(Error::InvalidArgument(detail));
            }
        }
    } else {
        parse_target(target)?
    };

    // 2. Resolve the new expiry date ----------------------------------------
    let new_date = resolve_new_date(date_str, in_days, today, yes)?;

    // 3. Read the file -------------------------------------------------------
    let content = std::fs::read_to_string(&file_path).map_err(|e| Error::Io {
        source: e,
        path: Some(file_path.clone()),
    })?;

    // 4. Validate line number is in range ------------------------------------
    let lines: Vec<&str> = content.lines().collect();
    let line_count = lines.len();

    if line_number < 1 || line_number > line_count {
        return Err(Error::InvalidArgument(format!(
            "line {} does not exist in file (file has {} lines)",
            line_number, line_count,
        )));
    }

    // 5. Extract the target line (0-indexed) ---------------------------------
    let original_line = lines[line_number - 1];

    // 6. Call snooze_line to replace the date --------------------------------
    let snoozed = snooze_line(original_line, new_date).ok_or_else(|| {
        Error::InvalidArgument(format!(
            "no timebomb date bracket found on line {} of {}",
            line_number,
            file_path.display(),
        ))
    })?;

    // 7. Optionally append reason --------------------------------------------
    let new_line = match reason {
        Some(r) => append_reason(&snoozed, r),
        None => snoozed,
    };

    // 8. Reconstruct the full file -------------------------------------------
    let mut new_content = String::with_capacity(content.len() + new_line.len());
    for (i, line) in lines.iter().enumerate() {
        if i == line_number - 1 {
            new_content.push_str(&new_line);
        } else {
            new_content.push_str(line);
        }
        new_content.push('\n');
    }
    // Preserve the original file's trailing newline behaviour
    if !content.ends_with('\n') {
        new_content.pop();
    }

    // 9. Print before/after diff ---------------------------------------------
    println!(
        "- {}:{}  {}",
        file_path.display(),
        line_number,
        original_line
    );
    println!("+ {}:{}  {}", file_path.display(), line_number, new_line);

    // 10. Prompt for confirmation (unless --yes) -----------------------------
    if !yes {
        print!("Write change? [y/N]: ");
        io::stdout().flush().map_err(|e| Error::Io {
            source: e,
            path: None,
        })?;

        let stdin = io::stdin();
        let mut line_buf = String::new();
        stdin
            .lock()
            .read_line(&mut line_buf)
            .map_err(|e| Error::Io {
                source: e,
                path: None,
            })?;

        let response = line_buf.trim();
        if response != "y" && response != "Y" {
            return Ok(0);
        }
    }

    // 11. Write the file atomically ------------------------------------------
    // Write to a sibling temp file then rename so a mid-write crash never
    // leaves a partially-written source file.
    let tmp_path = file_path.with_extension(format!("tmp.{}", std::process::id()));
    std::fs::write(&tmp_path, &new_content).map_err(|e| Error::Io {
        source: e,
        path: Some(tmp_path.clone()),
    })?;
    std::fs::rename(&tmp_path, &file_path).map_err(|e| Error::Io {
        source: e,
        path: Some(file_path.clone()),
    })?;

    // 12. Print confirmation -------------------------------------------------
    println!(
        "snoozed {}:{}{}",
        file_path.display(),
        line_number,
        new_date.format("%Y-%m-%d"),
    );

    // 13. Return success -----------------------------------------------------
    Ok(0)
}

// ---------------------------------------------------------------------------
// Helper: resolve_new_date
// ---------------------------------------------------------------------------

/// Resolve the new expiry `NaiveDate` from `--date` or `--in-days` arguments.
///
/// When both are None:
/// - If `yes` is true: default to 90 days silently (prints a notice)
/// - If `yes` is false: prompt the user for a number of days (default 90)
///
/// `date_str` takes priority if both are somehow provided.
pub fn resolve_new_date(
    date_str: Option<&str>,
    in_days: Option<u32>,
    today: NaiveDate,
    yes: bool,
) -> Result<NaiveDate> {
    match (date_str, in_days) {
        (Some(s), _) => NaiveDate::parse_from_str(s, "%Y-%m-%d").map_err(|_| {
            Error::InvalidArgument(format!("'{}' is not a valid date — expected YYYY-MM-DD", s))
        }),
        (None, Some(days)) => {
            let new_date = today + Duration::days(days as i64);
            Ok(new_date)
        }
        (None, None) => {
            let days: u32 = if yes {
                let default_date =
                    today
                        .checked_add_signed(Duration::days(90))
                        .ok_or_else(|| {
                            Error::InvalidArgument(
                                "90-day default overflows the calendar".to_string(),
                            )
                        })?;
                println!(
                    "No expiry specified; defaulting to 90 days from today ({})",
                    default_date.format("%Y-%m-%d")
                );
                90
            } else {
                print!("Expire in how many days? [90]: ");
                io::stdout().flush().map_err(|e| Error::Io {
                    source: e,
                    path: None,
                })?;
                let stdin = io::stdin();
                let mut buf = String::new();
                stdin.lock().read_line(&mut buf).map_err(|e| Error::Io {
                    source: e,
                    path: None,
                })?;
                let trimmed = buf.trim();
                if trimmed.is_empty() {
                    90
                } else {
                    trimmed.parse::<u32>().map_err(|_| {
                        Error::InvalidArgument(format!(
                            "'{}' is not a valid number of days",
                            trimmed
                        ))
                    })?
                }
            };
            today
                .checked_add_signed(Duration::days(days as i64))
                .ok_or_else(|| {
                    Error::InvalidArgument(format!("--in-days {} overflows the calendar", days))
                })
        }
    }
}

// ---------------------------------------------------------------------------
// Helper: snooze_line
// ---------------------------------------------------------------------------

/// Given a single source line string, find the first occurrence of a date in
/// the pattern `[YYYY-MM-DD]` and replace it with `[{new_date}]`.
///
/// Returns `Some(new_line)` if a replacement was made, `None` if no date
/// bracket was found on the line.
///
/// Only the FIRST bracketed date is replaced (the expiry date), not any
/// subsequent bracket (e.g. an owner bracket like `[alice]`).
static DATE_BRACKET_RE: std::sync::LazyLock<regex::Regex> = std::sync::LazyLock::new(|| {
    regex::Regex::new(r"\[(\d{4}-\d{2}-\d{2})\]").expect("hardcoded regex is valid")
});

pub fn snooze_line(line: &str, new_date: NaiveDate) -> Option<String> {
    let re = &*DATE_BRACKET_RE;

    let mat = re.find(line)?;

    let new_bracket = format!("[{}]", new_date.format("%Y-%m-%d"));
    let new_line = format!(
        "{}{}{}",
        &line[..mat.start()],
        new_bracket,
        &line[mat.end()..]
    );

    Some(new_line)
}

// ---------------------------------------------------------------------------
// Helper: append_reason
// ---------------------------------------------------------------------------

/// Append ` [snoozed: {reason}]` to the end of `line` after trimming trailing
/// whitespace/newline characters.
///
/// Returns the new string without a trailing newline — the caller handles line
/// endings.
pub fn append_reason(line: &str, reason: &str) -> String {
    let trimmed = line.trim_end();
    format!("{} [snoozed: {}]", trimmed, reason)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::NaiveDate;
    use std::fs;
    use tempfile::tempdir;

    fn date(s: &str) -> NaiveDate {
        NaiveDate::parse_from_str(s, "%Y-%m-%d").unwrap()
    }

    /// Fixed "today" used in all tests.
    fn today() -> NaiveDate {
        NaiveDate::from_ymd_opt(2025, 6, 1).unwrap()
    }

    // -- resolve_new_date ----------------------------------------------------

    #[test]
    fn test_resolve_new_date_from_str() {
        let result = resolve_new_date(Some("2026-06-01"), None, today(), true).unwrap();
        assert_eq!(result, date("2026-06-01"));
    }

    #[test]
    fn test_resolve_new_date_from_in_days() {
        // today = 2025-06-01, +30 days = 2025-07-01
        let result = resolve_new_date(None, Some(30), today(), true).unwrap();
        assert_eq!(result, date("2025-07-01"));
    }

    #[test]
    fn test_resolve_new_date_neither_yes_defaults_90() {
        // When yes=true and no date/in_days, should default to 90 days
        let t = today();
        let result = resolve_new_date(None, None, t, true).unwrap();
        let expected = t + Duration::days(90);
        assert_eq!(result, expected);
    }

    #[test]
    fn test_resolve_new_date_prefers_date_str() {
        // When both are provided, date_str wins
        let result = resolve_new_date(Some("2026-06-01"), Some(30), today(), true).unwrap();
        assert_eq!(result, date("2026-06-01"));
    }

    #[test]
    fn test_resolve_new_date_invalid_date_str() {
        let result = resolve_new_date(Some("not-a-date"), None, today(), true);
        assert!(result.is_err());
    }

    // -- snooze_line ---------------------------------------------------------

    #[test]
    fn test_snooze_line_basic() {
        let line = "    // TODO[2025-01-15]: remove legacy oauth flow";
        let new_date = date("2026-03-01");
        let result = snooze_line(line, new_date).unwrap();
        assert_eq!(result, "    // TODO[2026-03-01]: remove legacy oauth flow");
    }

    #[test]
    fn test_snooze_line_no_bracket() {
        let line = "    // TODO: plain comment with no date";
        let result = snooze_line(line, date("2026-01-01"));
        assert!(result.is_none());
    }

    #[test]
    fn test_snooze_line_only_replaces_first_bracket() {
        // Owner bracket [alice] must remain untouched
        let line = "    // TODO[2025-01-15][alice]: remove legacy oauth flow";
        let new_date = date("2026-03-01");
        let result = snooze_line(line, new_date).unwrap();
        assert_eq!(
            result,
            "    // TODO[2026-03-01][alice]: remove legacy oauth flow"
        );
        // Ensure [alice] is still there and unchanged
        assert!(result.contains("[alice]"));
        // Ensure the old date is gone
        assert!(!result.contains("2025-01-15"));
    }

    #[test]
    fn test_snooze_line_preserves_rest_of_line() {
        let line = "    // FIXME[2025-03-10]: this is the message text, do not change";
        let new_date = date("2026-12-01");
        let result = snooze_line(line, new_date).unwrap();
        assert!(result.contains("this is the message text, do not change"));
        assert!(result.contains("2026-12-01"));
        assert!(!result.contains("2025-03-10"));
    }

    // -- append_reason -------------------------------------------------------

    #[test]
    fn test_append_reason_basic() {
        let line = "    // TODO[2026-01-01]: msg";
        let result = append_reason(line, "reason");
        assert_eq!(result, "    // TODO[2026-01-01]: msg [snoozed: reason]");
    }

    #[test]
    fn test_append_reason_trims_trailing_whitespace() {
        let line = "    // TODO[2026-01-01]: msg   ";
        let result = append_reason(line, "because");
        // Trailing spaces should be stripped before appending
        assert_eq!(result, "    // TODO[2026-01-01]: msg [snoozed: because]");
    }

    #[test]
    fn test_append_reason_trims_trailing_newline() {
        let line = "    // TODO[2026-01-01]: msg\n";
        let result = append_reason(line, "upstream");
        assert_eq!(result, "    // TODO[2026-01-01]: msg [snoozed: upstream]");
    }

    // -- run_snooze integration tests ----------------------------------------

    #[test]
    fn test_run_snooze_rewrites_file() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "fn foo() {}\n// TODO[2025-01-15]: remove me\nfn bar() {}\n";
        fs::write(&file_path, content).unwrap();

        let target = format!("{}:2", file_path.display());
        let result = run_snooze(&target, Some("2026-06-01"), None, None, true, today(), None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 0);

        let updated = fs::read_to_string(&file_path).unwrap();
        assert!(updated.contains("2026-06-01"));
        assert!(!updated.contains("2025-01-15"));
        // Other lines untouched
        assert!(updated.contains("fn foo() {}"));
        assert!(updated.contains("fn bar() {}"));
    }

    #[test]
    fn test_run_snooze_no_annotation_on_line() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "fn foo() {}\nfn bar() {}\n";
        fs::write(&file_path, content).unwrap();

        let target = format!("{}:1", file_path.display());
        let result = run_snooze(&target, Some("2026-06-01"), None, None, true, today(), None);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("no timebomb date bracket found") || msg.contains("date bracket"));
    }

    #[test]
    fn test_run_snooze_line_out_of_range() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "fn foo() {}\nfn bar() {}\n";
        fs::write(&file_path, content).unwrap();

        let target = format!("{}:99", file_path.display());
        let result = run_snooze(&target, Some("2026-06-01"), None, None, true, today(), None);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("99") && (msg.contains("does not exist") || msg.contains("out of range"))
        );
    }

    #[test]
    fn test_run_snooze_with_reason() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content =
            "fn alpha() {}\n// TODO[2025-01-15]: remove legacy oauth flow\nfn beta() {}\n";
        fs::write(&file_path, content).unwrap();

        let target = format!("{}:2", file_path.display());
        let result = run_snooze(
            &target,
            Some("2026-03-01"),
            None,
            Some("blocked on upstream release"),
            true,
            today(),
            None,
        );
        assert!(result.is_ok());

        let updated = fs::read_to_string(&file_path).unwrap();
        assert!(updated.contains("2026-03-01"));
        assert!(updated.contains("[snoozed: blocked on upstream release]"));
        assert!(!updated.contains("2025-01-15"));
    }

    #[test]
    fn test_run_snooze_uses_in_days() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "// TODO[2025-01-15]: something\n";
        fs::write(&file_path, content).unwrap();

        let target = format!("{}:1", file_path.display());
        // today = 2025-06-01, +30 days = 2025-07-01
        let result = run_snooze(&target, None, Some(30), None, true, today(), None);
        assert!(result.is_ok());

        let updated = fs::read_to_string(&file_path).unwrap();
        assert!(updated.contains("2025-07-01"));
    }

    #[test]
    fn test_run_snooze_nonexistent_file_returns_io_error() {
        let result = run_snooze(
            "/nonexistent/path/file.rs:1",
            Some("2026-01-01"),
            None,
            None,
            true,
            today(),
            None,
        );
        assert!(result.is_err());
        // Should be an Io error
        let err = result.unwrap_err();
        assert!(matches!(err, crate::error::Error::Io { .. }));
    }

    #[test]
    fn test_run_snooze_line_1_of_1() {
        // Edge case: single line file, target line 1
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("single.rs");

        let content = "// TODO[2024-12-31]: single line\n";
        fs::write(&file_path, content).unwrap();

        let target = format!("{}:1", file_path.display());
        let result = run_snooze(&target, Some("2026-01-01"), None, None, true, today(), None);
        assert!(result.is_ok());

        let updated = fs::read_to_string(&file_path).unwrap();
        assert!(updated.contains("2026-01-01"));
        assert!(!updated.contains("2024-12-31"));
    }

    // -- search-based run_snooze tests ---------------------------------------

    #[test]
    fn test_run_snooze_with_search_single_match() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "fn alpha() {}\n// TODO[2025-01-15]: legacy_auth remove\nfn beta() {}\n";
        fs::write(&file_path, content).unwrap();

        let result = run_snooze(
            file_path.to_str().unwrap(),
            Some("2027-01-01"),
            None,
            None,
            true,
            today(),
            Some("legacy_auth"),
        );
        assert!(result.is_ok());

        let updated = fs::read_to_string(&file_path).unwrap();
        assert!(updated.contains("2027-01-01"));
        assert!(!updated.contains("2025-01-15"));
    }

    #[test]
    fn test_run_snooze_with_search_no_match() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "fn alpha() {}\nfn beta() {}\n";
        fs::write(&file_path, content).unwrap();

        let result = run_snooze(
            file_path.to_str().unwrap(),
            Some("2027-01-01"),
            None,
            None,
            true,
            today(),
            Some("zzz_no_match"),
        );
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("no lines matching"));
    }

    #[test]
    fn test_run_snooze_with_search_multiple_matches() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.rs");

        let content = "fn foo_a() {}\n// TODO[2025-01-15]: foo remove\nfn foo_b() {}\n";
        fs::write(&file_path, content).unwrap();

        let result = run_snooze(
            file_path.to_str().unwrap(),
            Some("2027-01-01"),
            None,
            None,
            true,
            today(),
            Some("foo"),
        );
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("matched") || msg.contains("lines"));
    }
}