tzselect-rs 0.1.0

Rust port of upstream tzselect.ksh — the interactive tzdb timezone selector
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
//! tzselect-rs — a faithful Rust port of upstream `tzselect.ksh` (tzdb).
//!
//! `tzselect.ksh` (Paul Eggert, public domain) is the **interactive** tzdb
//! timezone selector: it asks the user (via stderr/stdin) to identify a location
//! — by continent→country→region, by geographic coordinates (`-c`), by a
//! proleptic POSIX `TZ` string, or by current local time — and prints the chosen
//! `TZ` value to stdout. It reads `iso3166.tab` (country codes→names) and
//! `zone1970.tab` (the zone table), and uses several embedded POSIX-awk programs.
//!
//! This crate ports that behaviour to native Rust (no shell, no awk; the
//! POSIX-`TZ` grammar is hand-parsed, so there are **no runtime dependencies**).
//! Like the upstream it shells out to `date` for the current-time displays.
//!
//! ## Claim boundary
//!
//! tzselect-rs **does not define timezone policy or choose a timezone for the
//! user.** It ports the interactive selection behaviour of upstream
//! `tzselect.ksh` into Rust, using the same tzdb table surfaces, and verifies
//! representative prompt/output paths against the upstream shell oracle. It is
//! the user-selection layer of the Rust tzdb toolchain, beside `zic-rs` and the
//! producer/QA crates; it does **not** enter libc `localtime`/`strftime` runtime
//! territory.
//!
//! ## Parity contract
//!
//! The deterministic oracle is `LC_ALL=C.UTF-8 COLUMNS=1 tzselect` (single-column
//! `select`, raw-UTF-8 names, bytewise sort). The two live-clock lines
//! (`Selected time is now:` / `Universal Time is now:`) and the interactive
//! `time`/`now` menus are **time-dependent** and classified as such. Wide-terminal
//! multi-column `select` layout and non-UTF-8-locale `iconv` transliteration are
//! shell/terminal/locale rendering details, also classified.
#![forbid(unsafe_code)]

/// Host services the port needs from the environment — abstracted so the
/// interactive driver is unit-testable and the `date` shell-out is injectable.
pub trait Host {
    /// Read the next line of user input (stdin), without the trailing newline.
    /// `None` on EOF/error → the program exits like `read … || exit`.
    fn read_line(&mut self) -> Option<String>;
    /// Emit to stderr exactly as given (the caller includes newlines).
    fn err(&mut self, s: &str);
    /// Emit the final `TZ` to stdout (`say "$tz"`).
    fn out(&mut self, s: &str);
    /// Read `$TZDIR/<basename>` (e.g. `iso3166.tab`); `None` if unreadable.
    fn read_table(&self, basename: &str) -> Option<String>;
    /// `LANG=C TZ=<tz> date` → the one output line (no trailing newline).
    fn run_date(&self, tz: &str) -> Option<String>;
    /// `TZ=<tz> date +<fmt>` → the one output line.
    fn run_date_fmt(&self, tz: &str, fmt: &str) -> Option<String>;
    /// Is `$TZDIR/<tz>` a readable file? (`<"$TZ_for_date"` existence check.)
    fn zone_readable(&self, tz: &str) -> bool;
    /// Is stdout a tty? (gates the "make this permanent" hint.)
    fn stdout_is_tty(&self) -> bool;
}

/// Parsed command-line / environment options.
#[derive(Clone, Debug)]
pub struct Options {
    /// `-c COORD` (ISO 6709), or `None` for the menu path.
    pub coord: Option<String>,
    /// `-n LIMIT` (default 10).
    pub location_limit: usize,
    /// `-t TYPE` (undocumented; default `zone1970`).
    pub zonetabtype: String,
    /// `$TZDIR` — where the `.tab` files and compiled zones live (default `.`).
    pub tzdir: String,
    /// `(tzcode) ` — the baked `PKGVERSION`.
    pub pkgversion: String,
    /// e.g. `2026b` — the baked `TZVERSION`.
    pub tzversion: String,
    /// `$0` as used in diagnostics (default `tzselect`).
    pub argv0: String,
}

impl Default for Options {
    fn default() -> Self {
        Options {
            coord: None,
            location_limit: 10,
            zonetabtype: "zone1970".to_string(),
            tzdir: ".".to_string(),
            pkgversion: "(tzcode) ".to_string(),
            tzversion: env!("CARGO_PKG_VERSION").to_string(),
            argv0: "tzselect".to_string(),
        }
    }
}

/// The usage text (`tzselect.ksh:54-76`).
pub fn usage(o: &Options) -> String {
    format!(
        "Usage: tzselect [--version] [--help] [-c COORD] [-n LIMIT]
Select a timezone interactively.

Options:

  -c COORD
    Instead of asking for continent and then country and then city,
    ask for selection from time zones whose largest cities
    are closest to the location with geographical coordinates COORD.
    COORD should use ISO 6709 notation, for example, '-c +4852+00220'
    for Paris (in degrees and minutes, North and East), or
    '-c -35-058' for Buenos Aires (in degrees, South and West).

  -n LIMIT
    Display at most LIMIT locations when -c is used (default {}).

  --version
    Output version information.

  --help
    Output this help.

Report bugs to tz@iana.org.",
        o.location_limit
    )
}

/// One iteration's selected state, fed to the common confirmation tail.
struct Selection {
    tz: String,
    time: String,
    country_result: String,
    region: String,
    /// `false` only on the proleptic-`TZ` path (no zoneinfo file to check).
    needs_zone_check: bool,
}

/// `say >&2 "$0: <msg>"`.
fn say_err(h: &mut dyn Host, o: &Options, msg: &str) {
    h.err(&format!("{}: {}\n", o.argv0, msg));
}
/// `say >&2 "<msg>"` (adds the trailing newline).
fn say_err_raw(h: &mut dyn Host, msg: &str) {
    h.err(msg);
    h.err("\n");
}

/// Run the interactive selector. Returns the process exit code; the chosen `TZ`
/// is delivered via [`Host::out`].
pub fn run(o: &Options, h: &mut dyn Host) -> i32 {
    let country_table = match h.read_table(&format!("{}/iso3166.tab", o.tzdir)) {
        Some(s) => s,
        None => {
            say_err(h, o, "time zone files are not set up correctly");
            return 1;
        }
    };
    let zonetabtype_table = match h.read_table(&format!("{}/{}.tab", o.tzdir, o.zonetabtype)) {
        Some(s) => s,
        None => {
            say_err(h, o, "time zone files are not set up correctly");
            return 1;
        }
    };
    let mut zonenow_table: Option<String> = None;
    let mut coord = o.coord.clone();

    loop {
        h.err("Please identify a location so that time zone rules can be set correctly.\n");

        let continent = match &coord {
            Some(c) if !c.is_empty() => "coord".to_string(),
            _ => match ask_continent(o, h, &zonetabtype_table) {
                Some(c) => c,
                None => return 1,
            },
        };

        // `now` switches the working table to zonenow.tab (tzselect.ksh:443-448).
        let mut working_table = zonetabtype_table.clone();
        if o.zonetabtype != "zonenow" && continent == "now" {
            if zonenow_table.is_none() {
                zonenow_table = h.read_table(&format!("{}/zonenow.tab", o.tzdir));
            }
            if let Some(t) = &zonenow_table {
                working_table = t.clone();
            }
        }

        let sel = match dispatch(o, h, &continent, &mut coord, &country_table, &working_table) {
            Dispatch::Exit(code) => return code,
            Dispatch::Sel(s) => s,
        };

        // Make sure the zoneinfo file exists (tzselect.ksh:730-735).
        // TZ_for_date = $TZDIR/$tz for zones; the raw proleptic string otherwise.
        let tz_for_date = if sel.needs_zone_check {
            let path = format!("{}/{}", o.tzdir, sel.tz);
            if !h.zone_readable(&path) {
                say_err(h, o, "time zone files are not set up correctly");
                return 1;
            }
            path
        } else {
            sel.tz.clone()
        };

        finish(h, &sel, &coord, &tz_for_date);

        match doselect(o, h, &["Yes".to_string(), "No".to_string()]) {
            None => return 1,
            Some(ok) if ok == "Yes" => {
                permanent_hint(o, h, &sel.tz);
                h.out(&sel.tz);
                h.out("\n");
                return 0;
            }
            Some(_) => {
                coord = None; // `do coord= done`
                continue;
            }
        }
    }
}

/// Per-continent dispatch result.
enum Dispatch {
    Sel(Selection),
    Exit(i32),
}

fn dispatch(
    o: &Options,
    h: &mut dyn Host,
    continent: &str,
    coord: &mut Option<String>,
    country_table: &str,
    zone_table: &str,
) -> Dispatch {
    match continent {
        "TZ" => dispatch_tz(o, h),
        "coord" => dispatch_coord(o, h, coord, country_table, zone_table),
        "now" | "time" => dispatch_time(o, h, country_table, zone_table),
        _ => dispatch_normal(o, h, continent, country_table, zone_table),
    }
}

/// Proleptic POSIX `TZ` string (tzselect.ksh:453-487).
fn dispatch_tz(o: &Options, h: &mut dyn Host) -> Dispatch {
    let tz = loop {
        h.err("Please enter the desired value of the TZ environment variable.\n");
        h.err("For example, AEST-10 is abbreviated AEST and is 10 hours\n");
        h.err("ahead (east) of Greenwich, with no daylight saving time.\n");
        let entered = match h.read_line() {
            Some(s) => s,
            None => return Dispatch::Exit(1),
        };
        if posix_tz_valid(&entered) {
            break entered;
        }
        say_err_raw(
            h,
            &format!("'{entered}' is not a conforming POSIX proleptic TZ string."),
        );
    };
    let _ = o;
    Dispatch::Sel(Selection {
        tz,
        time: String::new(),
        country_result: String::new(),
        region: String::new(),
        needs_zone_check: false,
    })
}

/// Coordinate path (tzselect.ksh:490-538).
fn dispatch_coord(
    o: &Options,
    h: &mut dyn Host,
    coord: &mut Option<String>,
    country_table: &str,
    zone_table: &str,
) -> Dispatch {
    let c = match coord {
        Some(c) if !c.is_empty() => c.clone(),
        _ => {
            h.err("Please enter coordinates in ISO 6709 notation.\n");
            h.err("For example, +4042-07403 stands for\n");
            h.err("40 degrees 42 minutes north, 74 degrees 3 minutes west.\n");
            // The script uses a plain `read coord` (no `|| exit`): on EOF it
            // proceeds with an empty coord, and the following region `select`
            // handles the EOF (emitting the stdout newline + exit).
            match h.read_line() {
                Some(s) => {
                    *coord = Some(s.clone());
                    s
                }
                None => String::new(),
            }
        }
    };
    let mut rows = output_distances(&c, country_table, zone_table);
    rows.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
    rows.truncate(o.location_limit);
    let distance_table: Vec<String> = rows
        .iter()
        .map(|(d, line)| format!("{}\t{}", fmt_g(*d), line))
        .collect();
    let regions: Vec<String> = distance_table
        .iter()
        .map(|l| l.rsplit('\t').next().unwrap_or("").to_string())
        .collect();
    h.err("Please select one of the following timezones,\n");
    say_err_raw(
        h,
        &format!("listed roughly in increasing order of distance from {c}."),
    );
    let region = match doselect(o, h, &regions) {
        Some(s) => s,
        None => return Dispatch::Exit(1),
    };
    let mut tz = String::new();
    for l in &distance_table {
        let f: Vec<&str> = l.split('\t').collect();
        if f.last().copied().unwrap_or("") == region {
            tz = f.get(3).copied().unwrap_or("").to_string();
            break;
        }
    }
    Dispatch::Sel(Selection {
        tz,
        time: String::new(),
        country_result: String::new(),
        region,
        needs_zone_check: true,
    })
}

/// Current-local-time path (tzselect.ksh:541-608) — time-dependent.
fn dispatch_time(o: &Options, h: &mut dyn Host, country_table: &str, zone_table: &str) -> Dispatch {
    let time_table = build_time_table(h, zone_table);
    let new_minute = h.run_date_fmt("UTC0", "%a %b %d %H:%M").unwrap_or_default();
    say_err_raw(
        h,
        &format!("The system says Universal Time is {new_minute}."),
    );
    h.err("Assuming that's correct, what is the local time?\n");
    let sorted = sort_time_table(&time_table);
    let mut menu: Vec<String> = Vec::new();
    let mut last = String::new();
    for l in &sorted {
        let key = time_key(l);
        if key != last {
            menu.push(key.clone());
            last = key;
        }
    }
    let time = match doselect(o, h, &menu) {
        Some(s) => s,
        None => return Dispatch::Exit(1),
    };
    // zone_table = rows whose key == time, first tab field stripped.
    let mut zt = String::new();
    for l in &time_table {
        if time_key(l) == time {
            if let Some(pos) = l.find('\t') {
                zt.push_str(&l[pos + 1..]);
                zt.push('\n');
            }
        }
    }
    let countries = country_menu(o, h, "^", country_table, &zt);
    let (cr, country) = match pick_country(o, h, &countries) {
        Some(v) => v,
        None => return Dispatch::Exit(1),
    };
    let regions = regions_for_country(&country, country_table, &zt);
    let mut region = String::new();
    if regions.len() > 1 {
        h.err("Please select one of the following timezones.\n");
        match doselect(o, h, &regions) {
            Some(s) => region = s,
            None => return Dispatch::Exit(1),
        }
    }
    let tz = derive_tz(&country, &region, country_table, &zt);
    Dispatch::Sel(Selection {
        tz,
        time,
        country_result: cr.unwrap_or_default(),
        region,
        needs_zone_check: true,
    })
}

/// Normal continent → country → region path (tzselect.ksh:609-727).
fn dispatch_normal(
    o: &Options,
    h: &mut dyn Host,
    continent: &str,
    country_table: &str,
    zone_table: &str,
) -> Dispatch {
    let continent_re = format!("^{continent}/");
    let countries = country_menu(o, h, &continent_re, country_table, zone_table);
    let (cr, country) = match pick_country(o, h, &countries) {
        Some(v) => v,
        None => return Dispatch::Exit(1),
    };
    let regions = regions_for_country(&country, country_table, zone_table);
    let mut region = String::new();
    if regions.len() > 1 {
        h.err("Please select one of the following timezones.\n");
        match doselect(o, h, &regions) {
            Some(s) => region = s,
            None => return Dispatch::Exit(1),
        }
    }
    let tz = derive_tz(&country, &region, country_table, zone_table);
    Dispatch::Sel(Selection {
        tz,
        time: String::new(),
        country_result: cr.unwrap_or_default(),
        region,
        needs_zone_check: true,
    })
}

/// The extra-info date loop (tzselect.ksh:743-757) + the confirmation summary
/// (tzselect.ksh:760-778), up to (not including) the Yes/No menu.
fn finish(h: &mut dyn Host, sel: &Selection, coord: &Option<String>, tz_for_date: &str) {
    let mut extra_info = String::new();
    for _ in 0..8 {
        let tzdate = h.run_date(tz_for_date).unwrap_or_default();
        let utdate = h.run_date("UTC0").unwrap_or_default();
        if secs_match(&tzdate, &utdate) {
            extra_info =
                format!("\nSelected time is now:\t{tzdate}.\nUniversal Time is now:\t{utdate}.");
            break;
        }
    }

    h.err("\n");
    h.err("Based on the following information:\n");
    h.err("\n");

    let coord_s = coord.clone().unwrap_or_default();
    let nz = |s: &str| !s.is_empty();
    let summary = match (
        nz(&sel.time),
        nz(&sel.country_result),
        nz(&sel.region),
        nz(&coord_s),
    ) {
        (true, true, true, false) => {
            format!("\t{}\n\t{}\n\t{}", sel.time, sel.country_result, sel.region)
        }
        (true, true, false, false) | (true, false, true, false) => {
            format!("\t{}\n\t{}{}", sel.time, sel.country_result, sel.region)
        }
        (true, false, false, false) => format!("\t{}", sel.time),
        (false, true, true, false) => format!("\t{}\n\t{}", sel.country_result, sel.region),
        (false, true, false, false) => format!("\t{}", sel.country_result),
        (false, false, true, true) => format!("\tcoord {}\n\t{}", coord_s, sel.region),
        (false, false, false, true) => format!("\tcoord {coord_s}"),
        _ => format!("\tTZ='{}'", sel.tz),
    };
    say_err_raw(h, &summary);
    h.err("\n");
    say_err_raw(h, &format!("TZ='{}' will be used.{extra_info}", sel.tz));
    h.err("Is the above information OK?\n");
}

/// The permanent-change hint (tzselect.ksh:788-799), only when stdout is a tty.
fn permanent_hint(o: &Options, h: &mut dyn Host, tz: &str) {
    if !h.stdout_is_tty() {
        return;
    }
    let line = format!("export TZ='{tz}'");
    h.err(&format!(
        "\nYou can make this change permanent for yourself by appending the line\n\t{line}\nto the file '.profile' in your home directory; then log out and log in again.\n\nHere is that TZ value again, this time on standard output so that you\ncan use the {} command in shell scripts:\n",
        o.argv0
    ));
}

include!("logic.rs");

/// Fuzzing-only entry points (behind the `fuzzing` feature).
#[cfg(feature = "fuzzing")]
#[doc(hidden)]
pub mod fuzz {
    use super::*;

    /// A scripted in-memory host: input lines from a queue, output discarded,
    /// fixed `date`, all zones "present". Drives `run` without panicking.
    struct FuzzHost {
        lines: std::vec::IntoIter<String>,
        tables: std::collections::HashMap<String, String>,
    }
    impl Host for FuzzHost {
        fn read_line(&mut self) -> Option<String> {
            self.lines.next()
        }
        fn err(&mut self, _s: &str) {}
        fn out(&mut self, _s: &str) {}
        fn read_table(&self, path: &str) -> Option<String> {
            let base = path.rsplit('/').next().unwrap_or(path);
            self.tables.get(base).cloned()
        }
        fn run_date(&self, _tz: &str) -> Option<String> {
            Some("Mon Jan  1 00:00:00 UTC 2024".to_string())
        }
        fn run_date_fmt(&self, _tz: &str, _fmt: &str) -> Option<String> {
            Some("2024 01 01 00:00 Mon Jan".to_string())
        }
        fn zone_readable(&self, _path: &str) -> bool {
            true
        }
        fn stdout_is_tty(&self) -> bool {
            false
        }
    }

    /// Drive `run` over arbitrary input + arbitrary `iso3166`/`zone1970` tables.
    pub fn __fuzz_run(input: &str, iso3166: &str, zone1970: &str) {
        let mut tables = std::collections::HashMap::new();
        tables.insert("iso3166.tab".to_string(), iso3166.to_string());
        tables.insert("zone1970.tab".to_string(), zone1970.to_string());
        tables.insert("zonenow.tab".to_string(), zone1970.to_string());
        let mut h = FuzzHost {
            lines: input
                .lines()
                .map(|s| s.to_string())
                .collect::<Vec<_>>()
                .into_iter(),
            tables,
        };
        let _ = run(&Options::default(), &mut h);
    }

    /// Exercise the hand-written POSIX-`TZ` grammar validator.
    pub fn __fuzz_posix_tz(s: &str) {
        let _ = posix_tz_valid(s);
    }
}

#[cfg(kani)]
mod kani_harness {
    /// `doselect` returns `items[n - 1]` only inside `(1..=items.len())`. The
    /// range guard implies `n >= 1` (so `n - 1` never underflows) and
    /// `n - 1 < len` (so the index is in bounds) for any menu size — no panic.
    /// This is the only index arithmetic in the interactive driver.
    #[kani::proof]
    fn menu_index_guard_is_sound() {
        let len: usize = kani::any();
        let n: usize = kani::any();
        kani::assume(len <= 4096);
        if (1..=len).contains(&n) {
            assert!(n >= 1);
            assert!(n - 1 < len);
        }
    }
}