X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/8fc29fafb91cf64ce4ededbdd85ef9507c51f216..8fbe20476e2d10b1fc8dac848b2a0ffdf488a082:/sdk/go/arvados/duration.go diff --git a/sdk/go/arvados/duration.go b/sdk/go/arvados/duration.go index d3e11c7a5e..9df210ccb0 100644 --- a/sdk/go/arvados/duration.go +++ b/sdk/go/arvados/duration.go @@ -5,8 +5,10 @@ package arvados import ( + "bytes" "encoding/json" "fmt" + "strings" "time" ) @@ -16,10 +18,19 @@ type Duration time.Duration // UnmarshalJSON implements json.Unmarshaler. func (d *Duration) UnmarshalJSON(data []byte) error { + if bytes.Equal(data, []byte(`"0"`)) || bytes.Equal(data, []byte(`0`)) { + // Unitless 0 is not accepted by ParseDuration, but we + // accept it as a reasonable spelling of 0 + // nanoseconds. + *d = 0 + return nil + } if data[0] == '"' { return d.Set(string(data[1 : len(data)-1])) } - return fmt.Errorf("duration must be given as a string like \"600s\" or \"1h30m\"") + // Mimic error message returned by ParseDuration for a number + // without units. + return fmt.Errorf("missing unit in duration %q", data) } // MarshalJSON implements json.Marshaler. @@ -27,9 +38,13 @@ func (d Duration) MarshalJSON() ([]byte, error) { return json.Marshal(d.String()) } -// String implements fmt.Stringer. +// String returns a format similar to (time.Duration)String() but with +// "0m" and "0s" removed: e.g., "1h" instead of "1h0m0s". func (d Duration) String() string { - return time.Duration(d).String() + s := time.Duration(d).String() + s = strings.Replace(s, "m0s", "m", 1) + s = strings.Replace(s, "h0m", "h", 1) + return s } // Duration returns a time.Duration.