epochs-cli 0.7.0

Check strings given on the command line against different epochs.
#[macro_use]
extern crate maplit;

use clap::{Parser, ValueEnum};
use clap::builder::styling::{AnsiColor, Effects, Style, Styles};
use itertools::Itertools;
use jiff::Timestamp;
use jiff::civil::Date;
use regex::Regex;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::LazyLock;

const HEADER: Style = AnsiColor::Green.on_default().effects(Effects::BOLD);
const USAGE: Style = AnsiColor::Green.on_default().effects(Effects::BOLD);
const LITERAL: Style = AnsiColor::Cyan.on_default().effects(Effects::BOLD);
const PLACEHOLDER: Style = AnsiColor::Cyan.on_default();
const ERROR: Style = AnsiColor::Red.on_default().effects(Effects::BOLD);
const VALID: Style = AnsiColor::Cyan.on_default().effects(Effects::BOLD);
const INVALID: Style = AnsiColor::Yellow.on_default().effects(Effects::BOLD);
const CARGO_STYLING: Styles = Styles::styled()
    .header(HEADER)
    .usage(USAGE)
    .literal(LITERAL)
    .placeholder(PLACEHOLDER)
    .error(ERROR)
    .valid(VALID)
    .invalid(INVALID);

/// Command line options for epochs.
#[derive(Debug, Parser)]
#[command(author, version, about, long_about = None, styles = CARGO_STYLING)]
struct Args {
    /// Strings to test for epochness.
    candidates: Vec<String>,

    /// Activate debug mode
    #[arg(short, long)]
    debug: bool,

    /// Don't report dates after this.
    #[arg(long, value_parser = parse_date, default_value = "2100-12-31")]
    max: Date,

    /// Don't report dates before this.
    #[arg(long, value_parser = parse_date, default_value = "2000-01-01")]
    min: Date,

    /// Desired format for output.
    #[arg(short, long, value_enum, default_value_t = OutputFormat::Text)]
    output_format: OutputFormat,

    /// Verbose mode (-v, -vv, -vvv, etc.)
    #[arg(short, long, action = clap::ArgAction::Count)]
    verbose: u8,
}

#[derive(Debug, Clone, ValueEnum)]
enum OutputFormat {
    Json,
    JsonPretty,
    Text,
}

#[derive(Debug, Serialize)]
struct Datelike {
    source: String,
    viewed_as: View,
    epochs: HashMap<String, Timestamp>,
}

#[derive(Debug, Serialize)]
enum View {
    Decimal,
    Float,
    Hexadecimal,
    Ulid,
    Uuid,
}

#[derive(Debug, Serialize)]
enum Uuid {
    V1(Timestamp),
    V6(Timestamp),
    V7(Timestamp),
}

fn main() {
    let args = Args::parse();
    if args.debug {
        println!("{args:?}");
    }

    let mut dates = vec![];

    for c in args.candidates {
        if args.debug {
            println!("{c:?}");
        }

        if let Ok(int) = c.parse::<i64>() {
            if args.verbose > 1 {
                println!("  As decimal integer: {int}");
            }
            dates.push(Datelike {
                source: c.to_string(),
                viewed_as: View::Decimal,
                epochs: get_epochs(int, args.min, args.max),
            });
        }
        if let Ok(int) = i64::from_str_radix(&c, 16) {
            if args.verbose > 1 {
                println!("  As hexadecimal integer: {int}");
            }
            dates.push(Datelike {
                source: c.to_string(),
                viewed_as: View::Hexadecimal,
                epochs: get_epochs(int, args.min, args.max),
            });
        }

        if let Ok(float) = c.parse::<f64>() {
            if args.verbose > 1 {
                println!("  As a float! {float:?}");
            }

            if let Some(ts) = epochs::icq(float) {
                dates.push(Datelike {
                    source: c.to_string(),
                    viewed_as: View::Float,
                    epochs: hashmap! {"icq".to_string() => ts},
                });
            }
        }

        if let Some(ts) = get_ulid(&c) {
            dates.push(Datelike {
                source: c.to_string(),
                viewed_as: View::Ulid,
                epochs: hashmap! {"ulid".to_string() => ts},
            });
        }

        if let Some(uuid) = get_uuid(&c) {
            let epochs = match uuid {
                Uuid::V1(ts) => hashmap! {"uuid_v1".to_string() => ts},
                Uuid::V6(ts) => hashmap! {"uuid_v6".to_string() => ts},
                Uuid::V7(ts) => hashmap! {"uuid_v7".to_string() => ts},
            };
            dates.push(Datelike {
                source: c.to_string(),
                viewed_as: View::Uuid,
                epochs,
            });
        }
    }

    if args.debug {
        println!("{dates:?}");
    }

    match args.output_format {
        OutputFormat::Text => {
            for date in &dates {
                if !date.epochs.is_empty() {
                    println!("\n{} {:?}", date.source, date.viewed_as);
                }
                for epoch in date.epochs.iter().sorted() {
                    println!("  {} => {:?}", epoch.0, epoch.1);
                }
            }
        }
        OutputFormat::Json => {
            let json = serde_json::to_string(&dates).unwrap();
            println!("{json}");
        }
        OutputFormat::JsonPretty => {
            let json = serde_json::to_string_pretty(&dates).unwrap();
            println!("{json}");
        }
    }
}

fn get_epochs(int: i64, min: Date, max: Date) -> HashMap<String, Timestamp> {
    let mut timestamps = HashMap::new();

    if let Some(ts) = epochs::apfs(int) {
        maybe_insert(ts, "apfs", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::chrome(int) {
        maybe_insert(ts, "chrome", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::cocoa(int) {
        maybe_insert(ts, "cocoa", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::google_calendar(int) {
        maybe_insert(ts, "google calendar", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::java(int) {
        maybe_insert(ts, "java", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::mozilla(int) {
        maybe_insert(ts, "mozilla", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::symbian(int) {
        maybe_insert(ts, "symbian", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::unix(int) {
        maybe_insert(ts, "unix", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::uuid_v1(int) {
        maybe_insert(ts, "uuid v1", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::windows_date(int) {
        maybe_insert(ts, "windows date", min, max, &mut timestamps);
    }

    if let Some(ts) = epochs::windows_file(int) {
        maybe_insert(ts, "windows file", min, max, &mut timestamps);
    }

    timestamps
}

// See if the given `Timestamp` can be viewed as a `Date` between the
// given min and max. If so, insert it into the given `HashMap` with
// the given key.
fn maybe_insert(
    ts: Timestamp,
    key: &str,
    min: Date,
    max: Date,
    timestamps: &mut HashMap<String, Timestamp>,
) {
    if let Ok(zdt) = ts.in_tz("UTC") {
        let d = zdt.date();
        if d >= min && d <= max {
            timestamps.insert(key.to_string(), ts);
        }
    }
}

/// See if the given string contains a ULID. If it does, extract the
/// timestamp. <https://github.com/ulid/spec>
///
fn get_ulid(text: &str) -> Option<Timestamp> {
    static RE: LazyLock<Regex> =
        LazyLock::new(|| Regex::new(r"^[0123456789ABCDEFGHJKMNPQRSTVWXYZ]{26}$").unwrap());

    if RE.is_match(text) {
        // The first ten characters of the ULID contain the timestamp.
        let ts_ms = crockford::decode(&text[..10]).unwrap();
        let secs = (ts_ms / 1000) as i64;
        let nsecs = (ts_ms % 1000) as i32 * 1_000_000;
        Timestamp::new(secs, nsecs).ok()
    } else {
        None
    }
}

/// See if the given string contains a UUID string. If it does,
/// extract the version and the date-time if it has it.
///
fn get_uuid(text: &str) -> Option<Uuid> {
    static RE: LazyLock<Regex> = LazyLock::new(|| {
        Regex::new(
            r"(?x)
            ([0-9A-Fa-f]{8})  -?
            ([0-9A-Fa-f]{4})  -?
            ([0-9]{1})
            ([0-9A-Fa-f]{3})  -?
            [0-9A-Fa-f]{4}    -?
            [0-9A-Fa-f]{12}
            ",
        )
        .unwrap()
    });

    if let Some(cap) = RE.captures(text) {
        let version = cap.get(3).unwrap().as_str();
        match version {
            "1" => {
                let hex = format!("{}{}{}", &cap[4], &cap[2], &cap[1]);
                if let Ok(int) = i64::from_str_radix(&hex, 16) {
                    if let Some(ts) = epochs::uuid_v1(int) {
                        return Some(Uuid::V1(ts));
                    }
                }
            }
            "6" => {
                let hex = format!("{}{}{}", &cap[1], &cap[2], &cap[4]);
                if let Ok(int) = i64::from_str_radix(&hex, 16) {
                    if let Some(ts) = epochs::uuid_v1(int) {
                        return Some(Uuid::V6(ts));
                    }
                }
            }
            "7" => {
                let hex = format!("{}{}", &cap[1], &cap[2]);
                if let Ok(int) = i64::from_str_radix(&hex, 16) {
                    if let Some(ts) = epochs::java(int) {
                        return Some(Uuid::V7(ts));
                    }
                }
            }
            _ => (),
        }
    }
    None
}

/// Try to parse the given string as a `jiff::Date`.
fn parse_date(src: &str) -> Result<Date, jiff::Error> {
    src.parse()
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn get_ulid_tests() {
        let ulid = get_ulid("01FWHE4YDGFK1SHH6W1G60EECF");
        if let Some(ts) = ulid {
            assert_eq!(ts.to_string(), "2022-02-22T19:22:22Z");
        } else {
            panic!();
        }
    }

    #[test]
    fn get_uuid_tests() {
        let uuid = get_uuid("33c41a44-6cea-11e7-907b-a6006ad3dba0");
        if let Some(Uuid::V1(ts)) = uuid {
            assert_eq!(ts.to_string(), "2017-07-20T01:24:40.472634Z");
        } else {
            panic!();
        }

        let uuid = get_uuid("33c41a44-6cea-21e7-907b-a6006ad3dba0");
        assert!(uuid.is_none());

        let uuid = get_uuid("1EC9414C-232A-6B00-B3C8-9E6BDECED846");
        if let Some(Uuid::V6(ts)) = uuid {
            assert_eq!(ts.to_string(), "2022-02-22T19:22:22Z");
        } else {
            panic!();
        }

        let uuid = get_uuid("017F22E2-79B0-7CC3-98C4-DC0C0C07398F");
        if let Some(Uuid::V7(ts)) = uuid {
            assert_eq!(ts.to_string(), "2022-02-22T19:22:22Z");
        } else {
            panic!();
        }
    }
}