X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/c900f416c36cd74675c5bf4c33ad1dbe5d1e78fa..b417e845a53ffe207314108b3d1c813fe09e32a9:/sdk/go/arvados/duration.go diff --git a/sdk/go/arvados/duration.go b/sdk/go/arvados/duration.go index 1639c5852a..c922f0a30d 100644 --- a/sdk/go/arvados/duration.go +++ b/sdk/go/arvados/duration.go @@ -1,8 +1,13 @@ +// Copyright (C) The Arvados Authors. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 + package arvados import ( "encoding/json" "fmt" + "strings" "time" ) @@ -10,22 +15,38 @@ import ( // a number of nanoseconds. type Duration time.Duration -// UnmarshalJSON implements json.Unmarshaler +// UnmarshalJSON implements json.Unmarshaler. func (d *Duration) UnmarshalJSON(data []byte) error { if data[0] == '"' { - dur, err := time.ParseDuration(string(data[1 : len(data)-1])) - *d = Duration(dur) - return err + 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 -func (d *Duration) MarshalJSON() ([]byte, error) { +// MarshalJSON implements json.Marshaler. +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. +func (d Duration) Duration() time.Duration { + return time.Duration(d) +} + +// Set implements the flag.Value interface and sets the duration value by using time.ParseDuration to parse the string. +func (d *Duration) Set(s string) error { + dur, err := time.ParseDuration(s) + *d = Duration(dur) + return err }