aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Wild <mwild1@gmail.com>2023-04-07 14:14:53 +0100
committerMatthew Wild <mwild1@gmail.com>2023-04-07 14:14:53 +0100
commit7dc9f9ab2ad061b0b8be08e3a27cfe3056f1a76c (patch)
treedcd4943b166a7b8060b3bcefd483f26b0c3e09dc
parent2fa6a010180e8879e1eaab6612d86ff74cbed182 (diff)
downloadprosody-7dc9f9ab2ad061b0b8be08e3a27cfe3056f1a76c.tar.gz
prosody-7dc9f9ab2ad061b0b8be08e3a27cfe3056f1a76c.zip
util.human.io: Add parse_duration() method to parse a duration string
Similar logic occurs throughout various modules in the codebase. We might even want a module:get_option_duration()??
-rw-r--r--spec/util_human_io_spec.lua18
-rw-r--r--util/human/io.lua12
2 files changed, 30 insertions, 0 deletions
diff --git a/spec/util_human_io_spec.lua b/spec/util_human_io_spec.lua
index f1b28883..c143d028 100644
--- a/spec/util_human_io_spec.lua
+++ b/spec/util_human_io_spec.lua
@@ -42,6 +42,24 @@ describe("util.human.io", function ()
assert.equal("räksmörgås", human_io.ellipsis("räksmörgås", 10));
end);
end);
+
+ describe("parse_duration", function ()
+ local function test(expected, duration)
+ assert.equal(expected, human_io.parse_duration(duration));
+ end
+ it("works", function ()
+ test(1, "1s");
+ test(60, "1mi");
+ test(60, "1min");
+ test(60, "1 min");
+ test(60, "1 minute");
+ test(120, "2min");
+ test(86400, "1d");
+ test(2678400, "1m");
+ test(2678400, "1month");
+ test(2678400, "1 month");
+ end);
+ end);
end);
diff --git a/util/human/io.lua b/util/human/io.lua
index 8a903d38..c2ed4904 100644
--- a/util/human/io.lua
+++ b/util/human/io.lua
@@ -197,6 +197,17 @@ local function new_table(col_specs, max_width)
end, max_width;
end
+local day = 86400;
+local multipliers = {
+ d = day, w = day * 7, m = 31 * day, mo = 31 * day, y = 365.2425 * day;
+ s = 1, mi = 60, h = 3600
+};
+local function parse_duration(duration_string)
+ local n, m = duration_string:lower():match("(%d+)%s*([dwmy]?.?)");
+ if not n then return nil; end
+ return tonumber(n) * ( multipliers[m] or 1 );
+end
+
return {
getchar = getchar;
getline = getline;
@@ -210,4 +221,5 @@ return {
term_width = term_width;
ellipsis = ellipsis;
table = new_table;
+ parse_duration = parse_duration;
};