Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(775)

Unified Diff: go/src/infra/libs/clock/duration.go

Issue 1154213012: Add context-aware "time" library wrapper. (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@master
Patch Set: Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: go/src/infra/libs/clock/duration.go
diff --git a/go/src/infra/libs/clock/duration.go b/go/src/infra/libs/clock/duration.go
new file mode 100644
index 0000000000000000000000000000000000000000..265c0e19614a96309c36c41046a23f7e955d442a
--- /dev/null
+++ b/go/src/infra/libs/clock/duration.go
@@ -0,0 +1,59 @@
+// Copyright (c) 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+package clock
iannucci 2015/06/02 06:15:33 maybe this could go in clock/clockflag ? Then
dnj 2015/06/02 17:03:12 Done.
+
+import (
+ "errors"
+ "fmt"
+ "time"
+)
+
+// DurationFlag is a Flag- and JSON-compatible Duration value.
+type DurationFlag time.Duration
+
+// Set implements flag.Value.
+func (d *DurationFlag) Set(value string) error {
+ duration, err := time.ParseDuration(value)
+ if err != nil {
+ return err
+ }
+ *d = DurationFlag(duration)
+ return nil
+}
+
+// String implements flag.Value.
+func (d *DurationFlag) String() string {
+ return time.Duration(*d).String()
+}
+
+// Duration returns the Duration value of the flag.
+func (d DurationFlag) Duration() time.Duration {
+ return time.Duration(d)
+}
+
+// IsZero tests if this DurationFlag is the zero value.
+func (d DurationFlag) IsZero() bool {
+ return time.Duration(d) == time.Duration(0)
+}
+
+// UnmarshalJSON implements json.Unmarshaler.
+//
+// Unmarshals a JSON entry into the underlying type. The entry is expected to contain
+// a string corresponding to one of the enum's keys.
+func (d *DurationFlag) UnmarshalJSON(data []byte) error {
+ // Strip off leading and trailing quotes.
+ s := string(data)
+ if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' {
+ return errors.New("Duration JSON must be a valid JSON string.")
+ }
+ return d.Set(s[1 : len(s)-1])
+}
+
+// MarshalJSON implements json.Marshaler.
+//
+// Marshals a DurationFlag into a duration string.
+func (d DurationFlag) MarshalJSON() ([]byte, error) {
+ return []byte(fmt.Sprintf(`"%s"`, d.Duration().String())), nil
+}

Powered by Google App Engine
This is Rietveld 408576698