Improve formatting of durations
All checks were successful
Alpine 3.20 Success

Since "m" could stand for both "minute" and "month",
and months vary in length, let's stop at days.
This commit is contained in:
2025-01-02 00:35:00 +01:00
parent a492b3b668
commit 6622ea0e1c
2 changed files with 25 additions and 12 deletions

20
acid.go
View File

@@ -30,7 +30,6 @@ import (
"syscall" "syscall"
ttemplate "text/template" ttemplate "text/template"
"time" "time"
"unicode"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/pkg/sftp" "github.com/pkg/sftp"
@@ -1603,18 +1602,15 @@ func (t *Task) CloneURL() string {
} }
func shortDurationString(d time.Duration) string { func shortDurationString(d time.Duration) string {
rs := []rune(d.Truncate(time.Second).String()) if d.Abs() >= 24*time.Hour {
for i, r := range rs { return strconv.FormatInt(int64(d/time.Hour/24), 10) + "d"
if !unicode.IsLetter(r) { } else if d.Abs() >= time.Hour {
continue return strconv.FormatInt(int64(d/time.Hour), 10) + "h"
} } else if d.Abs() >= time.Minute {
i++ return strconv.FormatInt(int64(d/time.Minute), 10) + "m"
for i < len(rs) && unicode.IsLetter(rs[i]) { } else {
i++ return strconv.FormatInt(int64(d/time.Second), 10) + "s"
}
return string(rs[:i])
} }
return string(rs)
} }
func (t *Task) Created() *time.Time { func (t *Task) Created() *time.Time {

View File

@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"testing" "testing"
ttemplate "text/template" ttemplate "text/template"
"time"
) )
func TestTemplateQuote(t *testing.T) { 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)
}
}
}