From 6622ea0e1cb22687791c26b60381b138cbbb8098 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=99emysl=20Eric=20Janouch?= Date: Thu, 2 Jan 2025 00:35:00 +0100 Subject: [PATCH] Improve formatting of durations Since "m" could stand for both "minute" and "month", and months vary in length, let's stop at days. --- acid.go | 20 ++++++++------------ acid_test.go | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/acid.go b/acid.go index fd6ce76..9fe9fe4 100644 --- a/acid.go +++ b/acid.go @@ -30,7 +30,6 @@ import ( "syscall" ttemplate "text/template" "time" - "unicode" _ "github.com/mattn/go-sqlite3" "github.com/pkg/sftp" @@ -1603,18 +1602,15 @@ func (t *Task) CloneURL() string { } func shortDurationString(d time.Duration) string { - rs := []rune(d.Truncate(time.Second).String()) - for i, r := range rs { - if !unicode.IsLetter(r) { - continue - } - i++ - for i < len(rs) && unicode.IsLetter(rs[i]) { - i++ - } - return string(rs[:i]) + if d.Abs() >= 24*time.Hour { + return strconv.FormatInt(int64(d/time.Hour/24), 10) + "d" + } else if d.Abs() >= time.Hour { + return strconv.FormatInt(int64(d/time.Hour), 10) + "h" + } else if d.Abs() >= time.Minute { + return strconv.FormatInt(int64(d/time.Minute), 10) + "m" + } else { + return strconv.FormatInt(int64(d/time.Second), 10) + "s" } - return string(rs) } func (t *Task) Created() *time.Time { diff --git a/acid_test.go b/acid_test.go index 614fd0a..e8bd5c2 100644 --- a/acid_test.go +++ b/acid_test.go @@ -4,6 +4,7 @@ import ( "bytes" "testing" ttemplate "text/template" + "time" ) func TestTemplateQuote(t *testing.T) { @@ -30,3 +31,19 @@ func TestTemplateQuote(t *testing.T) { } } } + +func TestShortDurationString(t *testing.T) { + for _, test := range []struct { + d time.Duration + expect string + }{ + {72 * time.Hour, "3d"}, + {-3 * time.Hour, "-3h"}, + {12 * time.Minute, "12m"}, + {time.Millisecond, "0s"}, + } { + if sd := shortDurationString(test.d); sd != test.expect { + t.Errorf("%s = %s; want %s\n", test.d, sd, test.expect) + } + } +}