From 7dc9f9ab2ad061b0b8be08e3a27cfe3056f1a76c Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Fri, 7 Apr 2023 14:14:53 +0100 Subject: 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()?? --- util/human/io.lua | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'util') 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; }; -- cgit v1.2.3