dates-le 0.2.0

Extract every date and timestamp, and the exact instant each one resolves to
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
//! The terminal surface.
//!
//! stdout is always protocol — one JSON report per line, one line per
//! file. stderr is always for the human, and is a projection of the same
//! reports rather than parallel prose.

use std::io::{Read, Write};
use std::path::PathBuf;
use std::process::ExitCode;

use crate::extract::{extended, resolve_format};
use crate::scan::{self, FileReport, ScanOptions};
use crate::walk::{self, WalkOptions};

const USAGE: &str = "usage: dates-le [options] <file|dir>...
       dates-le [options] --stdin [--format <format>]
       dates-le mcp
       dates-le --version | --help

Finds every date and timestamp in a tree and puts them where a person
can read them: ISO 8601 in every form it is written — extended, basic,
week and ordinal — RFC 2822, Unix epochs from seconds to nanoseconds,
US notations, log and syslog lines, Apache access logs, and the strings
inside date constructors that nothing else would recognise as dates.

Every file is read. A name that matches no format is scanned with the
patterns every format shares, so a .py, .go, .toml or .md file yields
its dates rather than being skipped.

Each one carries the instant it actually resolves to, so `2024-01-15`,
`1705276800` and `Mon, 15 Jan 2024` can be compared rather than read.

Options:
  --after <date>       keep dates at or after this instant
  --before <date>      keep dates strictly before this instant
  --sort               order by instant rather than by position
  --dedupe             collapse repeated dates to their first occurrence
  --iso                add each instant as a UTC ISO 8601 string
  --tz <zone>          resolve dates that carry no timezone in this
                       IANA zone, e.g. UTC or America/New_York, instead
                       of this machine's
  --format <format>    force a format instead of inferring it from the
                       file name; a name nothing recognises falls back
                       to the shared patterns rather than failing
  --year <year>        the year a syslog line is assumed to be in,
                       since the line does not carry one. Defaults to
                       this one, which makes that answer move
  --values             print only the dates, one per line, for piping
  --strict             exit 2 if any file could not be read, rather than
                       reporting it and carrying on
  --stdin              read one document from stdin
  --hidden             walk hidden files and directories too
  --no-ignore          walk files that .gitignore excludes

--after and --before accept anything this tool can read, so
`--after 2024-01-15` and `--after 'March 5, 2024'` both work.

A date with no timezone resolves against this machine's. Use --tz to
name one instead; the answer genuinely differs by zone, exactly as it
does for the code being read.

A file that is not text — a PNG, a zip — is not read and not reported;
it was never a candidate. It is counted in the summary so the coverage
is still stated. A file that IS text and could not be read, or is not
UTF-8, is named on stderr and carried in the report, and does not by
itself fail the run. --strict turns those back into a failure.

Exit codes follow grep: 0 dates found · 1 none found · 2 malformed
question. Finding none is an answer, not an error.";

/// Every flag the parser accepts. Held equal to the flags named in
/// USAGE by a test, and consulted at runtime so the list is what the
/// parser actually honours.
const FLAGS: [&str; 14] = [
    "--strict",
    "--tz",
    "--after",
    "--before",
    "--sort",
    "--dedupe",
    "--iso",
    "--format",
    "--year",
    "--values",
    "--stdin",
    "--hidden",
    "--no-ignore",
    "--help",
];

#[derive(Debug)]
struct Invocation {
    scan: ScanOptions,
    walk: WalkOptions,
    values: bool,
    strict: bool,
    stdin: bool,
    roots: Vec<PathBuf>,
}

pub fn run(arguments: &[String]) -> ExitCode {
    if arguments.first().map(String::as_str) == Some("mcp") {
        return crate::mcp::serve();
    }
    if arguments.iter().any(|argument| argument == "--version") {
        println!("dates-le {}", env!("CARGO_PKG_VERSION"));
        return ExitCode::SUCCESS;
    }
    if arguments.is_empty() || arguments.iter().any(|argument| argument == "--help") {
        println!("{USAGE}");
        return ExitCode::SUCCESS;
    }

    let invocation = match parse_arguments(arguments) {
        Ok(invocation) => invocation,
        Err(message) => return refuse(&message),
    };

    let scanned = match gather(&invocation) {
        Ok(scanned) => scanned,
        Err(message) => return refuse(&message),
    };

    report(&scanned, invocation.values);
    scan::exit_code(&scanned.reports, invocation.strict)
}

fn refuse(message: &str) -> ExitCode {
    eprintln!("dates-le: {message}");
    eprintln!("try `dates-le --help`");
    ExitCode::from(2)
}

/// `--tz` is honoured before anything else is read, because `--after`
/// and `--before` parse dates too and must land in the same zone as the
/// documents. Order on the command line should not change an answer.
fn apply_zone_first(arguments: &[String]) -> Result<(), String> {
    let Some(index) = arguments.iter().position(|argument| argument == "--tz") else {
        return Ok(());
    };
    let raw = arguments.get(index + 1).ok_or("--tz needs a value")?;
    let zone = crate::extract::time::zone_by_name(raw)
        .ok_or_else(|| format!("{raw:?} is not an IANA timezone name"))?;
    crate::extract::time::set_zone(Some(zone));
    Ok(())
}

fn parse_arguments(arguments: &[String]) -> Result<Invocation, String> {
    apply_zone_first(arguments)?;
    let mut invocation = Invocation {
        scan: ScanOptions::default(),
        walk: WalkOptions::default(),
        values: false,
        strict: false,
        stdin: false,
        roots: Vec::new(),
    };

    let mut index = 0;
    while index < arguments.len() {
        let argument = arguments[index].as_str();
        let value = |name: &str| -> Result<String, String> {
            arguments
                .get(index + 1)
                .cloned()
                .ok_or_else(|| format!("{name} needs a value"))
        };

        match argument {
            "--after" => {
                let raw = value("--after")?;
                invocation.scan.after = Some(instant(&raw)?);
                index += 1;
            }
            "--before" => {
                let raw = value("--before")?;
                invocation.scan.before = Some(instant(&raw)?);
                index += 1;
            }
            "--format" => {
                invocation.scan.format = Some(value("--format")?);
                index += 1;
            }
            // Already applied by `apply_zone_first`; skip its value.
            "--tz" => index += 1,
            "--year" => {
                let raw = value("--year")?;
                invocation.scan.year = raw
                    .parse()
                    .map_err(|_| format!("--year needs a year, not {raw:?}"))?;
                index += 1;
            }
            "--sort" => invocation.scan.sort = true,
            "--dedupe" => invocation.scan.dedupe = true,
            "--iso" => invocation.scan.iso = true,
            "--values" => invocation.values = true,
            "--strict" => invocation.strict = true,
            "--stdin" => invocation.stdin = true,
            "--hidden" => invocation.walk.hidden = true,
            "--no-ignore" => invocation.walk.respect_ignore = false,
            other if other.starts_with("--") => {
                return Err(format!(
                    "unknown option {other:?} — one of: {}",
                    FLAGS.join(", ")
                ));
            }
            path => invocation.roots.push(PathBuf::from(path)),
        }
        index += 1;
    }

    if !invocation.stdin && invocation.roots.is_empty() {
        return Err("name a file or directory, or pass --stdin".into());
    }
    Ok(invocation)
}

/// A boundary for `--after` / `--before`, read by the same parser that
/// reads the documents. A tool that could not read its own output as
/// input would be a strange one.
fn instant(raw: &str) -> Result<i64, String> {
    extended::instant(raw).ok_or_else(|| format!("{raw:?} is not a date this can read"))
}

/// What a run read: a report per text file, and a count of the files
/// that were never text candidates.
///
/// The count is carried rather than dropped because a walk that covered
/// less than the tree has to say so — but a PNG is not a file that
/// failed to be read, so it gets a number in the summary rather than a
/// line in the report and a hold over the exit code.
struct Scanned {
    reports: Vec<FileReport>,
    binary: usize,
}

fn gather(invocation: &Invocation) -> Result<Scanned, String> {
    if invocation.stdin {
        // No file name to infer from, so an unnamed format falls back —
        // the same answer a `.py` file gets, and no special case.
        let language = resolve_format(invocation.scan.format.as_deref(), None);
        let mut content = String::new();
        std::io::stdin()
            .read_to_string(&mut content)
            .map_err(|error| format!("could not read stdin: {error}"))?;
        return Ok(Scanned {
            reports: vec![scan::scan_text(
                "<stdin>",
                scan::without_bom(&content),
                language,
                &invocation.scan,
            )],
            binary: 0,
        });
    }

    for root in &invocation.roots {
        if !root.exists() {
            return Err(format!("{} does not exist", root.display()));
        }
    }
    let files = walk::collect(&invocation.roots, invocation.walk);
    let reports: Vec<FileReport> = files
        .iter()
        .filter_map(|path| scan::scan_file(path, &invocation.scan))
        .collect();
    Ok(Scanned {
        binary: files.len() - reports.len(),
        reports,
    })
}

fn report(scanned: &Scanned, values_only: bool) {
    let reports = &scanned.reports;
    let stdout = std::io::stdout();
    let mut out = stdout.lock();

    if values_only {
        for report in reports {
            for date in &report.dates {
                let _ = writeln!(out, "{}", date.value);
            }
        }
        return;
    }

    for report in reports {
        if let Ok(line) = serde_json::to_string(report) {
            let _ = writeln!(out, "{line}");
        }
    }

    let total: usize = reports.iter().map(|report| report.dates.len()).sum();
    let skipped = reports
        .iter()
        .filter(|report| report.skipped.is_some())
        .count();
    let files = reports.len() - skipped;
    eprintln!(
        "{total} date{} in {files} file{}{}{}",
        plural(total),
        plural(files),
        if skipped == 0 {
            String::new()
        } else {
            format!(", {skipped} skipped")
        },
        // Counted, never named: naming fourteen PNGs is the noise that
        // stops anyone reading the line that matters.
        if scanned.binary == 0 {
            String::new()
        } else {
            format!(
                ", {} binary file{} skipped",
                scanned.binary,
                plural(scanned.binary)
            )
        }
    );
    // Named, every one of them. A tool that quietly reads fewer files
    // than it was pointed at is worse than one that fails.
    for report in reports.iter().filter(|report| report.skipped.is_some()) {
        eprintln!(
            "  skipped {}: {}",
            report.file,
            report.skipped.as_deref().unwrap_or_default()
        );
    }
}

fn plural(count: usize) -> &'static str {
    if count == 1 { "" } else { "s" }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extract::SUPPORTED_FORMATS;
    use crate::extract::format::FALLBACK_FORMAT;

    fn parse(arguments: &[&str]) -> Result<Invocation, String> {
        parse_arguments(
            &arguments
                .iter()
                .map(|argument| (*argument).to_string())
                .collect::<Vec<_>>(),
        )
    }

    #[test]
    fn every_flag_the_parser_honours_is_documented() {
        for flag in FLAGS {
            assert!(USAGE.contains(flag), "{flag} is not in the usage text");
        }
    }

    #[test]
    fn every_flag_the_usage_names_is_honoured() {
        for word in USAGE.split_whitespace() {
            let flag = word.trim_end_matches([',', '.', '·']);
            if flag.starts_with("--") && flag.len() > 2 {
                assert!(
                    FLAGS.contains(&flag) || flag == "--version",
                    "{flag} is documented and not honoured"
                );
            }
        }
    }

    #[test]
    fn every_exit_code_is_documented() {
        for code in ["0", "1", "2"] {
            assert!(USAGE.contains(code), "exit code {code} is undocumented");
        }
    }

    #[test]
    fn a_boundary_is_read_by_the_same_parser_as_a_document() {
        let invocation = parse(&["--after", "2024-01-15", "."]).expect("parses");
        assert_eq!(invocation.scan.after, Some(1_705_276_800_000));
        let written = parse(&["--after", "March 5, 2024", "."]).expect("parses");
        assert!(written.scan.after.is_some());
    }

    #[test]
    fn a_boundary_that_is_not_a_date_is_refused() {
        let error = parse(&["--after", "soon", "."]).expect_err("refuses");
        assert!(error.contains("not a date"), "{error}");
    }

    /// A format nothing recognises is read with the shared patterns,
    /// the same as a file whose name says nothing. Refusing it was the
    /// tool declining to read most of a repository.
    #[test]
    fn an_unknown_format_falls_back_rather_than_failing() {
        let invocation = parse(&["--format", "rust", "."]).expect("parses");
        assert_eq!(invocation.scan.format.as_deref(), Some("rust"));
        assert_eq!(resolve_format(Some("rust"), None), FALLBACK_FORMAT);
    }

    #[test]
    fn every_advertised_format_is_accepted_by_name() {
        for name in SUPPORTED_FORMATS {
            assert!(parse(&["--format", name, "."]).is_ok(), "{name}");
        }
    }

    #[test]
    fn stdin_without_a_format_reads_the_document_anyway() {
        assert!(parse(&["--stdin"]).is_ok());
    }

    #[test]
    fn naming_nothing_at_all_is_refused() {
        let error = parse(&["--sort"]).expect_err("refuses");
        assert!(error.contains("file or directory"), "{error}");
    }

    #[test]
    fn an_unknown_option_is_refused_rather_than_read_as_a_path() {
        let error = parse(&["--nope", "."]).expect_err("refuses");
        assert!(error.contains("--nope"), "{error}");
    }

    #[test]
    fn a_flag_missing_its_value_says_which() {
        assert!(
            parse(&["--after"])
                .expect_err("refuses")
                .contains("--after")
        );
        assert!(parse(&["--year"]).expect_err("refuses").contains("--year"));
    }

    #[test]
    fn a_year_that_is_not_a_number_is_refused() {
        let error = parse(&["--year", "soon", "."]).expect_err("refuses");
        assert!(error.contains("--year"), "{error}");
    }

    #[test]
    fn a_named_zone_is_accepted_and_a_made_up_one_is_not() {
        assert!(parse(&["--tz", "UTC", "."]).is_ok());
        assert!(parse(&["--tz", "America/New_York", "."]).is_ok());
        let error = parse(&["--tz", "Mars/Olympus", "."]).expect_err("refuses");
        assert!(error.contains("IANA"), "{error}");
        crate::extract::time::set_zone(None);
    }

    /// The zone has to apply to the boundaries too, or `--after` would
    /// mean something different depending on where it was typed.
    #[test]
    fn the_zone_applies_before_a_boundary_is_read() {
        let utc = parse(&["--tz", "UTC", "--after", "2024-01-15 00:00:00", "."])
            .expect("parses")
            .scan
            .after;
        let east = parse(&[
            "--tz",
            "America/New_York",
            "--after",
            "2024-01-15 00:00:00",
            ".",
        ])
        .expect("parses")
        .scan
        .after;
        crate::extract::time::set_zone(None);
        assert_ne!(utc, east, "a zone-less boundary is not zone-independent");
        assert_eq!(east.unwrap() - utc.unwrap(), 5 * 3_600_000);
    }

    /// Written after `--tz` was read in argument order and quietly gave
    /// a different answer depending on which flag came first.
    #[test]
    fn the_zone_applies_wherever_it_appears() {
        let first = parse(&["--tz", "UTC", "--after", "2024-01-15 00:00:00", "."])
            .expect("parses")
            .scan
            .after;
        let last = parse(&["--after", "2024-01-15 00:00:00", "--tz", "UTC", "."])
            .expect("parses")
            .scan
            .after;
        crate::extract::time::set_zone(None);
        assert_eq!(first, last);
    }

    #[test]
    fn paths_accumulate() {
        let invocation = parse(&["a.json", "b.log"]).expect("parses");
        assert_eq!(invocation.roots.len(), 2);
    }

    #[test]
    fn the_walk_flags_invert_the_defaults() {
        let invocation = parse(&["--hidden", "--no-ignore", "."]).expect("parses");
        assert!(invocation.walk.hidden);
        assert!(!invocation.walk.respect_ignore);
    }

    #[test]
    fn the_default_year_is_this_one() {
        assert_eq!(
            ScanOptions::default().year,
            crate::extract::time::current_year()
        );
    }
}