-
Notifications
You must be signed in to change notification settings - Fork 42
/
timespan.go
97 lines (83 loc) · 1.97 KB
/
timespan.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package testrail
import (
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
)
// Timespan field type.
// e.g. "1m" or "2m 30s" -- similar to time.Duration
//
// For a description, see:
// http://docs.gurock.com/testrail-api2/reference-results
type timespan struct {
time.Duration
}
// TimespanFromDuration converts a standard Go time duration into a testrail compatible timespan.
func TimespanFromDuration(duration time.Duration) *timespan {
if duration == 0 {
return nil
}
return ×pan{duration}
}
// Unmarshal TestRail timespan into a time.Duration.
// Transform TestRail-specific formats into something time.ParseDuration understands:
// "4h 5m 6s" => "4h5m6s"
// "1d" => "8h"
// "1w" => "40h"
// "1d 2h" => "8h2h"
// "1w 2d 3h" => "40h16h3h"
func (tsp *timespan) UnmarshalJSON(data []byte) error {
const (
// These are hardcoded in TestRail.
// https://discuss.gurock.com/t/estimate-fields/900
daysPerWeek = 5
hoursPerDay = 8
)
var (
err error
span string
)
if err = json.Unmarshal(data, &span); err != nil {
return err
}
if span == "" {
return nil
}
var parts []string
for _, p := range strings.Fields(span) {
if len(p) < 2 {
return fmt.Errorf("%q: sequence is too short", p)
}
amount, err := strconv.Atoi(p[:len(p)-1])
if err != nil {
return fmt.Errorf("%q: cannot convert to int: %v", amount, err)
}
unit := p[len(p)-1]
switch unit {
case 'd':
unit = 'h'
amount *= hoursPerDay
case 'w':
unit = 'h'
amount *= daysPerWeek * hoursPerDay
}
parts = append(parts, fmt.Sprintf("%v%c", amount, unit))
}
tsp.Duration, err = time.ParseDuration(strings.Join(parts, ""))
if err != nil {
return fmt.Errorf("%q: %v", span, err)
}
return nil
}
func (tsp timespan) MarshalJSON() ([]byte, error) {
d := tsp.Duration
if d == 0 {
return []byte(`null`), nil
}
h, d := d/time.Hour, d%time.Hour
m, d := d/time.Minute, d%time.Minute
s := d / time.Second
return []byte(fmt.Sprintf(`"%dh %dm %ds"`, h, m, s)), nil
}