Files
aitrade/pkg/config/duration.go
T
kaedwen ea141eb012
Build and Push Docker Image / build-and-push (push) Failing after 1m41s
initial
2026-07-02 20:09:44 +02:00

56 lines
1.4 KiB
Go

package config
import (
"fmt"
"strconv"
"strings"
"time"
)
// Duration wraps time.Duration to support YAML unmarshaling from seconds
type Duration struct {
time.Duration
}
// UnmarshalYAML implements yaml.Unmarshaler interface
// Accepts either:
// - Integer: interpreted as seconds (e.g., 300)
// - String: Go duration format (e.g., "5m", "1h30m")
func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
// Try unmarshaling as integer (seconds)
var seconds int
if err := unmarshal(&seconds); err == nil {
d.Duration = time.Duration(seconds) * time.Second
return nil
}
// Try unmarshaling as string (Go duration format)
var str string
if err := unmarshal(&str); err != nil {
return err
}
// Parse as Go duration ("5m", "1h30m", etc.)
parsed, err := time.ParseDuration(str)
if err != nil {
// If not a valid Go duration, try parsing as number + "s" suffix
if strings.HasSuffix(str, "s") {
numStr := strings.TrimSuffix(str, "s")
if sec, err := strconv.Atoi(numStr); err == nil {
d.Duration = time.Duration(sec) * time.Second
return nil
}
}
return fmt.Errorf("invalid duration format: %s (use seconds or Go duration like '5m')", str)
}
d.Duration = parsed
return nil
}
// MarshalYAML implements yaml.Marshaler interface
func (d Duration) MarshalYAML() (interface{}, error) {
// Always marshal as seconds for consistency
return int(d.Duration.Seconds()), nil
}