From 0e8f660d6d6c50359843808594ad2b63f1e62b35 Mon Sep 17 00:00:00 2001 From: Casey Rodarmor Date: Fri, 14 Jun 2024 22:48:34 -0700 Subject: [PATCH] Add `datetime()` and `datetime_utc()` functions (#2167) --- README.md | 10 ++++++++++ src/function.rs | 10 ++++++++++ tests/datetime.rs | 27 +++++++++++++++++++++++++++ tests/lib.rs | 1 + 4 files changed, 48 insertions(+) create mode 100644 tests/datetime.rs diff --git a/README.md b/README.md index de792ba..f4d7363 100644 --- a/README.md +++ b/README.md @@ -1642,6 +1642,16 @@ which will halt execution. characters. For example, `choose('64', HEX)` will generate a random 64-character lowercase hex string. +#### Datetime + +- `datetime(format)`master - Return local time with `format`. +- `datetime_utc(format)`master - Return UTC time with `format`. + +The arguments to `datetime` and `datetime_utc` are `strftime`-style format +strings, see the +[`chrono` library docs](https://docs.rs/chrono/latest/chrono/format/strftime/index.html) +for details. + #### Semantic Versions - `semver_matches(version, requirement)`1.16.0 - Check whether a diff --git a/src/function.rs b/src/function.rs index 9226762..dbce934 100644 --- a/src/function.rs +++ b/src/function.rs @@ -47,6 +47,8 @@ pub(crate) fn get(name: &str) -> Option { "config_local_directory" => Nullary(|_| dir("local config", dirs::config_local_dir)), "data_directory" => Nullary(|_| dir("data", dirs::data_dir)), "data_local_directory" => Nullary(|_| dir("local data", dirs::data_local_dir)), + "datetime" => Unary(datetime), + "datetime_utc" => Unary(datetime_utc), "encode_uri_component" => Unary(encode_uri_component), "env" => UnaryOpt(env), "env_var" => Unary(env_var), @@ -235,6 +237,14 @@ fn dir(name: &'static str, f: fn() -> Option) -> FunctionResult { } } +fn datetime(_context: Context, format: &str) -> FunctionResult { + Ok(chrono::Local::now().format(format).to_string()) +} + +fn datetime_utc(_context: Context, format: &str) -> FunctionResult { + Ok(chrono::Utc::now().format(format).to_string()) +} + fn encode_uri_component(_context: Context, s: &str) -> FunctionResult { static PERCENT_ENCODE: percent_encoding::AsciiSet = percent_encoding::NON_ALPHANUMERIC .remove(b'-') diff --git a/tests/datetime.rs b/tests/datetime.rs new file mode 100644 index 0000000..5092cbe --- /dev/null +++ b/tests/datetime.rs @@ -0,0 +1,27 @@ +use super::*; + +#[test] +fn datetime() { + Test::new() + .justfile( + " + x := datetime('%Y-%m-%d %z') + ", + ) + .args(["--eval", "x"]) + .stdout_regex(r"\d\d\d\d-\d\d-\d\d [+-]\d\d\d\d") + .run(); +} + +#[test] +fn datetime_utc() { + Test::new() + .justfile( + " + x := datetime_utc('%Y-%m-%d %Z') + ", + ) + .args(["--eval", "x"]) + .stdout_regex(r"\d\d\d\d-\d\d-\d\d UTC") + .run(); +} diff --git a/tests/lib.rs b/tests/lib.rs index 42b3aff..292482f 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -47,6 +47,7 @@ mod completions; mod conditional; mod confirm; mod constants; +mod datetime; mod delimiters; mod directories; mod dotenv;