1
0
mirror of https://github.com/rancher/steve.git synced 2025-09-24 04:49:53 +00:00
Files
steve/pkg/resources/common/duration.go
Wolfgang Jung 10d0492ae3 Fixes parsing of resources older than 2 year (#784)
- Similar assumption as 24h per day:
  365 days per year, ignoring DST and leap-years

Very old resources (older than 2 years) are printed as `2y15d` instead of using just the number of days.

This leads to parser errors for namespaces in rancher:
```
2025/08/18 14:43:34 [WARNING] convert timestamp value: 2y114d failed with error: strconv.ParseInt: parsing "2y114d": invalid syntax
2025/08/18 14:43:34 [WARNING] convert timestamp value: 3y50d failed with error: strconv.ParseInt: parsing "3y50d": invalid syntax
2025/08/18 14:43:34 [WARNING] convert timestamp value: 2y163d failed with error: strconv.ParseInt: parsing "2y163d": invalid syntax
2025/08/18 14:43:34 [WARNING] convert timestamp value: 3y50d failed with error: strconv.ParseInt: parsing "3y50d": invalid syntax
```

Relates to https://github.com/rancher/steve/pull/684

Co-authored-by: Wolfgang Jung <wolfgang.jung@loewenfels.ch>
2025-08-19 13:11:57 -03:00

47 lines
1.2 KiB
Go

package common
import (
"fmt"
"strings"
"time"
)
// ParseTimestampOrHumanReadableDuration can do one of three things with an incoming string:
// 1. Recognize it's an absolute timestamp and calculate a relative `time.Duration`
// 2. Recognize it's a human-readable duration (like 3m) and convert to a relative `time.Duration`
// 3. Return an error because it doesn't recognize the input
func ParseTimestampOrHumanReadableDuration(s string) (time.Duration, error) {
var total time.Duration
var val int
var unit byte
parsedTime, err := time.Parse(time.RFC3339, s)
if err == nil {
return time.Since(parsedTime), nil
}
r := strings.NewReader(s)
for r.Len() > 0 {
if _, err := fmt.Fscanf(r, "%d%c", &val, &unit); err != nil {
return 0, fmt.Errorf("invalid duration in %s: %w", s, err)
}
switch unit {
case 'y':
total += time.Duration(val) * 365 * 24 * time.Hour
case 'd':
total += time.Duration(val) * 24 * time.Hour
case 'h':
total += time.Duration(val) * time.Hour
case 'm':
total += time.Duration(val) * time.Minute
case 's':
total += time.Duration(val) * time.Second
default:
return 0, fmt.Errorf("invalid duration unit %s in %s", string(unit), s)
}
}
return total, nil
}