Skip to content

Commit

Permalink
Loose some detail in human duration
Browse files Browse the repository at this point in the history
Signed-off-by: Jo Vandeginste <[email protected]>
  • Loading branch information
jovandeginste committed Feb 20, 2024
1 parent 6142346 commit c987110
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 17 deletions.
22 changes: 13 additions & 9 deletions pkg/templatehelpers/duration.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,16 @@ func (d *duration) String() string {
components = append(components, fmt.Sprintf("%dh", d.Hours))
}

if d.Minutes > 0 {
components = append(components, fmt.Sprintf("%dm", d.Minutes))
}

if d.Seconds > 0 {
components = append(components, fmt.Sprintf("%ds", d.Seconds))
if d.Days == 0 {
if d.Minutes > 0 {
components = append(components, fmt.Sprintf("%dm", d.Minutes))
}

if d.Hours == 0 {
if d.Seconds > 0 {
components = append(components, fmt.Sprintf("%ds", d.Seconds))
}
}
}

return strings.Join(components, " ")
Expand All @@ -64,7 +68,7 @@ func (d *duration) calculate() {
return
}

if d.duration < 60 {
if d.duration < 80 {
d.Seconds = d.duration
return
}
Expand All @@ -74,7 +78,7 @@ func (d *duration) calculate() {
}

func (d *duration) calculateMinutes(minutes int) {
if d.duration < 60 {
if minutes < 80 {
d.Minutes = minutes
return
}
Expand All @@ -84,7 +88,7 @@ func (d *duration) calculateMinutes(minutes int) {
}

func (d *duration) calculateHours(hours int) {
if d.duration < 24 {
if hours < 30 {
d.Hours = hours
return
}
Expand Down
24 changes: 16 additions & 8 deletions pkg/templatehelpers/duration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,26 @@ import (

func TestHumanDuration(t *testing.T) {
tests := map[time.Duration]string{
0: "0s",
1 * time.Second: "1s",
1 * time.Minute: "1m",
1 * time.Hour: "1h",
1*time.Hour + 1*time.Minute: "1h 1m",
0: "0s",
1 * time.Second: "1s",
1 * time.Minute: "60s",
1 * time.Hour: "60m",
24 * time.Hour: "24h",

1*time.Hour + 1*time.Minute + 1*time.Second: "1h 1m 1s",
72*time.Hour + 30*time.Minute + 5*time.Second: "3d 30m 5s",
100*time.Hour + 100*time.Second: "4d 4h 1m 40s",
2 * time.Second: "2s",
2 * time.Minute: "2m",
2 * time.Hour: "2h",
48 * time.Hour: "2d",

1*time.Hour + 1*time.Minute: "61m",
1*time.Hour + 1*time.Minute + 1*time.Second: "61m 1s",
25*time.Hour + 1*time.Minute + 1*time.Second: "25h 1m",
72*time.Hour + 30*time.Minute + 5*time.Second: "3d",
100*time.Hour + 100*time.Second: "4d 4h",
}

for d, expected := range tests {
assert.Equal(t, expected, HumanDuration(d))
assert.Equal(t, expected, HumanDuration(-d))
}
}

0 comments on commit c987110

Please sign in to comment.