Make short duration formatter re-useable

This commit is contained in:
Kovid Goyal
2023-07-25 09:32:25 +05:30
parent 9694bd03d8
commit b60d15fe75
4 changed files with 85 additions and 70 deletions

View File

@@ -2,8 +2,10 @@ package humanize
import (
"fmt"
"kitty/tools/wcswidth"
"math"
"sort"
"strings"
"time"
)
@@ -115,3 +117,49 @@ func CustomRelTime(a, b time.Time, albl, blbl string, magnitudes []RelTimeMagnit
}
return fmt.Sprintf(mag.Format, args...)
}
func optional_cut(x string, sep string) (string, string) {
a, b, found := strings.Cut(x, sep)
if found {
return a, b
}
return "00", a
}
func zero_pad(x string) string {
if len(x) < 2 {
x = strings.Repeat("0", 2-len(x)) + x
}
return x
}
// Render the duration in exactly 8 chars
func ShortDuration(val time.Duration) (ans string) {
if val >= time.Second {
if val > Day {
days := int(val.Hours() / 24)
if days > 99 {
ans = ``
} else {
if days == 1 {
ans = ">1 day"
} else {
ans = fmt.Sprintf(">%d days", int(days))
}
}
} else {
ans = val.String()
hr, rest := optional_cut(ans, `h`)
min, rest := optional_cut(rest, `m`)
secs, _, _ := strings.Cut(rest, ".")
secs = strings.Replace(secs, `s`, ``, 1)
ans = zero_pad(hr) + `:` + zero_pad(min) + `:` + zero_pad(secs)
}
} else {
ans = "<1 sec"
}
if w := wcswidth.Stringwidth(ans); w < 8 {
ans = strings.Repeat(" ", 8-w) + ans
}
return
}

View File

@@ -0,0 +1,35 @@
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
package humanize
import (
"fmt"
"testing"
"time"
"github.com/google/go-cmp/cmp"
)
var _ = fmt.Print
func TestShortDuration(t *testing.T) {
q := func(i float64, e string) {
d := time.Duration(i * float64(time.Second))
if diff := cmp.Diff(e, ShortDuration(d)); diff != "" {
t.Fatalf("Failed for %f (%s): %s", i, d, diff)
}
}
q(0.1, " <1 sec")
q(1, `00:00:01`)
q(1.1234567, `00:00:01`)
q(60.1234567, `00:01:00`)
q(61.1234567, `00:01:01`)
q(3600, `01:00:00`)
q(3601.1234567, `01:00:01`)
day := 24. * 3600.
q(day, "24:00:00")
q(day+1, " >1 day")
q(day*2, " >2 days")
q(day*23, ">23 days")
q(day*999, " ∞")
}