fix(executiontime): round values logically

This commit is contained in:
Jan De Dobbeleer 2021-05-21 08:14:02 +02:00 committed by Jan De Dobbeleer
parent 8642b7bfd9
commit 5f045431cf
3 changed files with 39 additions and 5 deletions

View file

@ -47,6 +47,6 @@ Style specifies the format in which the time will be displayed. The table below
| galveston | `00:00:00` | `00:00:02` | `00:03:02` | `04:03:02` |
| houston | `00:00:00.001` | `00:00:02.1` | `00:03:02.1` | `04:03:02.1` |
| amarillo | `0.001s` | `2.1s` | `182.1s` | `14,582.1s` |
| round | `1ms` | `2s` | `3m` | `4h` |
| round | `1ms` | `2s` | `3m 2s` | `4h 3m` |
[install]: /docs/installation

View file

@ -181,17 +181,26 @@ func (t *executiontime) formatDurationAmarillo(ms int64) string {
}
func (t *executiontime) formatDurationRound(ms int64) string {
toRoundString := func(one, two int64, oneText, twoText string) string {
if two == 0 {
return fmt.Sprintf("%d%s", one, oneText)
}
return fmt.Sprintf("%d%s %d%s", one, oneText, two, twoText)
}
hours := ms / hour % hoursPerDay
if ms >= day {
return fmt.Sprintf("%dd", ms/day)
return toRoundString(ms/day, hours, "d", "h")
}
minutes := ms / minute % secondsPerMinute
if ms >= hour {
return fmt.Sprintf("%dh", ms/hour%hoursPerDay)
return toRoundString(hours, minutes, "h", "m")
}
seconds := (ms % minute) / second
if ms >= minute {
return fmt.Sprintf("%dm", ms/minute%secondsPerMinute)
return toRoundString(minutes, seconds, "m", "s")
}
if ms >= second {
return fmt.Sprintf("%ds", (ms%minute)/second)
return fmt.Sprintf("%ds", seconds)
}
return fmt.Sprintf("%dms", ms%second)
}

View file

@ -228,3 +228,28 @@ func TestExecutionTimeFormatAmarillo(t *testing.T) {
assert.Equal(t, tc.Expected, output)
}
}
func TestExecutionTimeFormatDurationRound(t *testing.T) {
cases := []struct {
Input string
Expected string
}{
{Input: "0.001s", Expected: "1ms"},
{Input: "0.1s", Expected: "100ms"},
{Input: "1s", Expected: "1s"},
{Input: "2.1s", Expected: "2s"},
{Input: "1m", Expected: "1m"},
{Input: "3m2.1s", Expected: "3m 2s"},
{Input: "1h", Expected: "1h"},
{Input: "4h3m2.1s", Expected: "4h 3m"},
{Input: "124h3m2.1s", Expected: "5d 4h"},
{Input: "124h3m2.0s", Expected: "5d 4h"},
}
for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{}
output := executionTime.formatDurationRound(duration.Milliseconds())
assert.Equal(t, tc.Expected, output)
}
}