wdxtools 0.4.2

Everyday formatting tools for the command line
Documentation
//! Port of Carbon's `CarbonInterface::diffForHumans()`.
//! Original: <https://github.com/briannesbitt/Carbon/blob/master/src/Carbon/Traits/Difference.php>
//! Carbon is created by Brian Nesbitt and licensed under the MIT License.

use std::io::Write;

use clap::Args;
use jiff::{tz::TimeZone, Zoned};
use wdxtools::timediff::{append_diff_for_humans, Config, Formatter, Options, Syntax};

use super::date;
use super::io::{stdin_is_pipe, write_lines, Output};
use super::template::{self, MAX_FIELDS};

#[derive(Args, Debug)]
#[command(
    about = "Human-readable time differences",
    long_about = "Human-readable time differences (port of Carbon diffForHumans).",
    // Lets pre-epoch unix timestamps be passed positionally: `diffh -86400`.
    allow_negative_numbers = true,
    after_help = "\x1b[1mExamples:\x1b[0m
  wdxtools diffh 2024-01-15              # 1 year ago
  wdxtools diffh -s 2024-01-15            # 1y ago
  wdxtools diffh -p 3 2024-01-15          # 1 year, 2 months, and 14 days ago
  wdxtools diffh -a 2024-01-15 2025-01-15 # 1 year
  wdxtools diffh 1774820647               # 4 hours ago (unix timestamp)
  echo 2024-01-15 | wdxtools diffh        # 1 year ago (stdin)
  printf '%s\\n' ts1 ts2 | wdxtools diffh  # one line per input (batch mode)

\x1b[1mTemplate mode (-f):\x1b[0m $1..$N = input fields, $d = time diff
  ... | wdxtools diffh -f '$2 ($d)'       # second field + diff in parens
  ... | wdxtools diffh -f '$1\\t$d'        # first field + tab + diff"
)]
pub struct DiffhArgs {
    /// Use short form (2h, 3d, ...)
    #[arg(short, long)]
    short: bool,

    /// Absolute mode (no ago/from now)
    #[arg(short, long)]
    absolute: bool,

    /// Time units to show (1-7)
    #[arg(short, long, default_value_t = 1)]
    parts: usize,

    /// Show "just now" for zero diffs
    #[arg(short = 'j', long = "just-now")]
    just_now: bool,

    /// Use yesterday/tomorrow for 1-day diffs
    #[arg(long = "one-day")]
    one_day: bool,

    /// Use "before yesterday"/"after tomorrow"
    #[arg(long = "two-day")]
    two_day: bool,

    /// Only show sequential non-zero units
    #[arg(short = 'S', long)]
    sequential: bool,

    /// Show "1 second" instead of "0 seconds"
    #[arg(short = 'n', long = "no-zero")]
    no_zero: bool,

    /// Output template for batch mode ($1..$N=fields, $d=diff)
    #[arg(short, long)]
    format: Option<String>,

    #[arg(value_name = "DATE")]
    dates: Vec<String>,
}

pub fn run(args: DiffhArgs) -> i32 {
    let mut flags = Options::NONE;
    if args.just_now {
        flags |= Options::JUST_NOW;
    }
    if args.one_day {
        flags |= Options::ONE_DAY_WORDS;
    }
    if args.two_day {
        flags |= Options::TWO_DAY_WORDS;
    }
    if args.sequential {
        flags |= Options::SEQUENTIAL_PARTS_ONLY;
    }
    if args.no_zero {
        flags |= Options::NO_ZERO_DIFF;
    }

    let cfg = Config::new()
        .short(args.short)
        .parts(args.parts)
        .options(flags)
        .syntax(if args.absolute {
            Syntax::Absolute
        } else {
            Syntax::RelativeAuto
        });

    let tz = TimeZone::system();
    let mut out = Output::new();
    let mut buf = String::with_capacity(128);

    if !args.dates.is_empty() {
        let from = match date::parse(&args.dates[0], &tz) {
            Ok(t) => t,
            Err(e) => return out.fail(&format!("diffh: {e}")),
        };

        // A second positional argument is the "other" date to compare against.
        let (to, cfg) = match args.dates.get(1) {
            Some(other) => match date::parse(other, &tz) {
                Ok(t) => {
                    let cfg = if cfg.syntax == Syntax::RelativeAuto {
                        cfg.syntax(Syntax::RelativeToOther)
                    } else {
                        cfg
                    };
                    (t, cfg)
                }
                Err(e) => return out.fail(&format!("diffh: {e}")),
            },
            None => (Zoned::now().with_time_zone(tz.clone()), cfg),
        };

        append_diff_for_humans(&mut buf, &from, &to, cfg);
        buf.push('\n');
        let _ = out.write_all(buf.as_bytes());
        return out.finish();
    }

    if !stdin_is_pipe() {
        super::print_help("diffh");
        return 0;
    }

    let fmtr = Formatter::new(Zoned::now().with_time_zone(tz.clone()), cfg);
    let mut failed = None;

    match args.format {
        Some(tpl) => {
            let tpl = template::unescape(&tpl);
            let mut line_out = String::with_capacity(256);
            write_lines(&mut out, |line, out| {
                let mut fields = [""; MAX_FIELDS];
                let nf = template::split_fields(line, &mut fields);
                if nf == 0 {
                    return true;
                }
                let from = match date::parse(fields[0], &tz) {
                    Ok(t) => t,
                    Err(e) => {
                        failed = Some(format!("diffh: {e}"));
                        return false;
                    }
                };
                buf.clear();
                fmtr.append_format(&mut buf, &from);
                line_out.clear();
                template::expand(&mut line_out, &tpl, &fields[..nf], &buf);
                line_out.push('\n');
                let _ = out.write_all(line_out.as_bytes());
                true
            });
        }
        None => {
            write_lines(&mut out, |line, out| {
                let from = match date::parse(line, &tz) {
                    Ok(t) => t,
                    Err(e) => {
                        failed = Some(format!("diffh: {e}"));
                        return false;
                    }
                };
                buf.clear();
                fmtr.append_format(&mut buf, &from);
                buf.push('\n');
                let _ = out.write_all(buf.as_bytes());
                true
            });
        }
    }

    match failed {
        Some(msg) => out.fail(&msg),
        None => out.finish(),
    }
}