pathdate 0.1.2

CLI tool to generate a path-safe ISO8601-like date/datetime/timestamp.
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
use chrono::{DateTime, Local, Utc};
use chrono_tz::Tz;
use clap::Parser;
use std::io::Write;

#[derive(Parser, Debug)]
#[command(
    name = "pathdate",
    author,
    version,
    about = "Generate a path-safe ISO8601-like date/datetime/timestamp.",
    long_about = None
)]
struct Args {
    /// Use UTC instead of local time
    #[arg(long, conflicts_with = "tz")]
    utc: bool,

    /// Use a specific IANA timezone (e.g. America/New_York).
    #[arg(long, value_name = "TIMEZONE", conflicts_with = "utc")]
    tz: Option<String>,

    /// Output date only (no time component)
    #[arg(long = "date", alias = "date-only", conflicts_with_all = ["seconds", "epoch", "epoch_ms"])]
    date_only: bool,

    /// Include seconds in the output
    #[arg(long = "sec", alias = "seconds", conflicts_with_all = ["date_only", "epoch", "epoch_ms"])]
    seconds: bool,

    /// Include milliseconds in the output (implies --sec)
    #[arg(long = "ms", alias = "milliseconds", conflicts_with_all = ["date_only", "seconds", "epoch"])]
    millis: bool,

    /// Use a custom chrono format string (overrides all other format flags)
    #[arg(long, value_name = "FORMAT", conflicts_with_all = ["date_only", "seconds", "millis", "epoch", "epoch_ms", "tight"])]
    format: Option<String>,

    /// Do not print a trailing newline
    #[arg(long = "no-newline")]
    no_newline: bool,

    /// Remove all delimiters (produces e.g. 20260401T1230L)
    #[arg(long, conflicts_with_all = ["format", "epoch"])]
    tight: bool,

    /// Print seconds since the Unix epoch (1970-01-01T00:00:00Z)
    #[arg(long, conflicts_with_all = ["format"])]
    epoch: bool,

    /// Print milliseconds since the Unix epoch
    #[arg(long = "epoch-ms", conflicts_with_all = ["format"])]
    epoch_ms: bool,
}

fn build_format(args: &Args) -> String {
    // Custom format wins outright.
    if let Some(ref fmt) = args.format {
        return fmt.clone();
    }

    let millis = args.millis;
    let secs = args.seconds || millis;
    let tight = args.tight;

    if args.date_only {
        if tight {
            return "%Y%m%d".into();
        }
        return "%Y-%m-%d".into();
    }

    // Determine suffix that indicates timezone awareness.
    // We'll append it manually after formatting so we can keep it out of the
    // chrono format string (avoids confusion with %Z).
    // The suffix is added in `format_datetime`, not here.

    if tight {
        // e.g. 20260401T1230 / 20260401T123045 / 20260401T123045123
        let base = "%Y%m%dT%H%M";
        if millis {
            return format!("{}%S%3f", base);
        }
        if secs {
            return format!("{}%S", base);
        }
        return base.into();
    }

    // Default path-safe format: 2026-04-01T12-30
    // We use hyphens for the time part so the colon (':') never appears — colons
    // are forbidden in Windows paths and ugly in filenames everywhere.
    if millis {
        return "%Y-%m-%d-T%H-%M-%S-%3f".into();
    }
    if secs {
        return "%Y-%m-%d-T%H-%M-%S".into();
    }
    // If not using seconds, use a more compact format without a delimiter
    // between hours and minutes. Arguably very opinionated.
    "%Y-%m-%d-T%H%M".into()
}

fn format_datetime(args: &Args) -> String {
    // ----- epoch shortcuts ------------------------------------------------
    let now_utc: DateTime<Utc> = Utc::now();

    if args.epoch_ms {
        return format!("{}", now_utc.timestamp_millis());
    }
    if args.epoch {
        return format!("{}", now_utc.timestamp());
    }

    // ----- pick timezone & format -----------------------------------------
    let fmt = build_format(args);

    // Named tz overrides everything
    if let Some(ref tz_name) = args.tz {
        let tz: Tz = tz_name
            .parse()
            .unwrap_or_else(|_| panic!("Unknown timezone: {}", tz_name));
        let dt = now_utc.with_timezone(&tz);
        let formatted = dt.format(&fmt).to_string();
        if args.date_only || args.format.is_some() {
            return formatted;
        }
        // Append abbreviated tz name
        let abbr = dt.format("%Z").to_string();
        return format!("{}{}", formatted, abbr);
    }

    if args.utc {
        let formatted = now_utc.format(&fmt).to_string();
        if args.date_only || args.format.is_some() {
            return formatted;
        }
        return format!("{}Z", formatted);
    }

    // Local time
    let dt: DateTime<Local> = Local::now();
    let formatted = dt.format(&fmt).to_string();
    if args.date_only || args.format.is_some() {
        return formatted;
    }
    format!("{}L", formatted)
}

fn main() {
    let args = Args::parse();
    let output = format_datetime(&args);
    print!("{}", output);
    if !args.no_newline {
        println!();
    } else {
        std::io::stdout().flush().ok();
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    // Helper: build Args with all defaults (local time, to-minutes, no newline)
    fn default_args() -> Args {
        Args {
            utc: false,
            tz: None,
            date_only: false,
            seconds: false,
            millis: false,
            format: None,
            no_newline: false,
            tight: false,
            epoch: false,
            epoch_ms: false,
        }
    }

    // -----------------------------------------------------------------------
    // build_format tests
    // -----------------------------------------------------------------------

    #[test]
    fn format_default_is_to_minutes() {
        let args = default_args();
        assert_eq!(build_format(&args), "%Y-%m-%d-T%H%M");
    }

    #[test]
    fn format_seconds_flag() {
        let args = Args {
            seconds: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y-%m-%d-T%H-%M-%S");
    }

    #[test]
    fn format_millis_flag_implies_seconds() {
        let args = Args {
            millis: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y-%m-%d-T%H-%M-%S-%3f");
    }

    #[test]
    fn format_date_only() {
        let args = Args {
            date_only: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y-%m-%d");
    }

    #[test]
    fn format_date_only_tight() {
        let args = Args {
            date_only: true,
            tight: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y%m%d");
    }

    #[test]
    fn format_tight_default() {
        let args = Args {
            tight: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y%m%dT%H%M");
    }

    #[test]
    fn format_tight_with_seconds() {
        let args = Args {
            tight: true,
            seconds: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y%m%dT%H%M%S");
    }

    #[test]
    fn format_tight_with_millis() {
        let args = Args {
            tight: true,
            millis: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%Y%m%dT%H%M%S%3f");
    }

    #[test]
    fn format_custom_overrides_everything() {
        let args = Args {
            format: Some("%d/%m/%Y".into()),
            tight: true,
            seconds: true,
            millis: true,
            ..default_args()
        };
        assert_eq!(build_format(&args), "%d/%m/%Y");
    }

    // -----------------------------------------------------------------------
    // format_datetime output shape tests
    // -----------------------------------------------------------------------

    #[test]
    fn output_utc_ends_with_z() {
        let args = Args {
            utc: true,
            ..default_args()
        };
        let out = format_datetime(&args);
        assert!(out.ends_with('Z'), "UTC output should end with Z: {}", out);
    }

    #[test]
    fn output_local_ends_with_l() {
        let args = default_args();
        let out = format_datetime(&args);
        assert!(
            out.ends_with('L'),
            "Local output should end with L: {}",
            out
        );
    }

    #[test]
    fn output_date_only_no_suffix() {
        let args = Args {
            date_only: true,
            utc: true,
            ..default_args()
        };
        let out = format_datetime(&args);
        // Should look like YYYY-MM-DD
        assert_eq!(out.len(), 10, "Date-only output length: {}", out);
        assert!(
            !out.ends_with('Z'),
            "Date-only should have no suffix: {}",
            out
        );
    }

    #[test]
    fn output_epoch_is_numeric() {
        let args = Args {
            epoch: true,
            ..default_args()
        };
        let out = format_datetime(&args);
        assert!(
            out.parse::<i64>().is_ok(),
            "Epoch output should be numeric: {}",
            out
        );
        // Rough sanity: should be close to 2026-01-01
        let ts = out.parse::<i64>().unwrap();
        assert!(ts > 1_700_000_000, "Epoch too small: {}", ts);
    }

    #[test]
    fn output_epoch_ms_is_larger_than_epoch() {
        let args_ms = Args {
            epoch_ms: true,
            ..default_args()
        };
        let args_s = Args {
            epoch: true,
            ..default_args()
        };
        let ms: i64 = format_datetime(&args_ms).parse().unwrap();
        let s: i64 = format_datetime(&args_s).parse().unwrap();
        assert!(ms > s * 100, "epoch-ms should be ~1000x epoch-s");
    }

    #[test]
    fn output_with_seconds_has_extra_segment() {
        let args_min = Args {
            utc: true,
            ..default_args()
        };
        let args_sec = Args {
            utc: true,
            seconds: true,
            ..default_args()
        };
        let out_min = format_datetime(&args_min);
        let out_sec = format_datetime(&args_sec);
        // seconds output should be longer (extra "-%S" = 3 chars)
        assert!(
            out_sec.len() > out_min.len(),
            "seconds output should be longer"
        );
    }

    #[test]
    fn output_with_millis_has_extra_segment() {
        let args_sec = Args {
            utc: true,
            seconds: true,
            ..default_args()
        };
        let args_ms = Args {
            utc: true,
            millis: true,
            ..default_args()
        };
        let out_sec = format_datetime(&args_sec);
        let out_ms = format_datetime(&args_ms);
        assert!(
            out_ms.len() > out_sec.len(),
            "millis output should be longer than seconds"
        );
    }

    #[test]
    fn output_tight_has_no_hyphens_in_time() {
        let args = Args {
            utc: true,
            tight: true,
            ..default_args()
        };
        let out = format_datetime(&args);
        // Remove the trailing 'Z' and check no hyphen in the time portion
        let body = &out[..out.len() - 1];
        // Body: YYYYMMDDTHHmm — no hyphens at all
        assert!(
            !body.contains('-'),
            "Tight output should have no hyphens: {}",
            out
        );
    }

    #[test]
    fn output_tight_date_only_compact() {
        let args = Args {
            date_only: true,
            tight: true,
            utc: true,
            ..default_args()
        };
        let out = format_datetime(&args);
        assert_eq!(out.len(), 8, "Tight date-only should be 8 chars: {}", out);
        assert!(!out.contains('-'));
    }

    #[test]
    fn output_custom_format() {
        let args = Args {
            utc: true,
            format: Some("%Y/%m/%d".into()),
            ..default_args()
        };
        let out = format_datetime(&args);
        assert!(out.contains('/'), "Custom format output: {}", out);
        assert!(
            !out.ends_with('Z'),
            "Custom format should not add Z: {}",
            out
        );
    }

    #[test]
    fn output_named_tz_appends_abbreviation() {
        let args = Args {
            tz: Some("UTC".into()),
            ..default_args()
        };
        let out = format_datetime(&args);
        assert!(
            out.ends_with("UTC"),
            "Named UTC tz should end with 'UTC': {}",
            out
        );
    }

    #[test]
    fn output_named_tz_new_york() {
        let args = Args {
            tz: Some("America/New_York".into()),
            ..default_args()
        };
        let out = format_datetime(&args);
        // Should end with EST or EDT depending on DST
        assert!(
            out.ends_with("EST") || out.ends_with("EDT"),
            "New York tz suffix unexpected: {}",
            out
        );
    }

    // -----------------------------------------------------------------------
    // Alias / flag interaction edge cases
    // -----------------------------------------------------------------------

    #[test]
    fn millis_without_explicit_seconds_still_includes_seconds() {
        // --ms implies --sec at the format level
        let args = Args {
            utc: true,
            millis: true,
            ..default_args()
        };
        let fmt = build_format(&args);
        assert!(fmt.contains("%S"), "millis format should contain %S");
    }

    #[test]
    fn tight_millis_no_colons_or_hyphens_in_body() {
        let args = Args {
            utc: true,
            tight: true,
            millis: true,
            ..default_args()
        };
        let out = format_datetime(&args);
        let body = out.trim_end_matches('Z');
        assert!(!body.contains(':'), "tight output should have no colons");
        assert!(
            !body.contains('-'),
            "tight output should have no hyphens: {}",
            body
        );
    }

    #[test]
    fn epoch_ms_flag_ignores_date_and_format_flags() {
        let args = Args {
            epoch_ms: true,
            date_only: true,
            utc: true,
            format: Some("%Y".into()),
            ..default_args()
        };
        let out = format_datetime(&args);
        assert!(
            out.parse::<i64>().is_ok(),
            "epoch-ms should still be numeric: {}",
            out
        );
    }
}