@@ -4,33 +4,72 @@ import (
44 "fmt"
55 "strconv"
66 "strings"
7+ "time"
78)
89
9- type Duration string
10+ type Duration time. Duration
1011
11- var defaultDuration = "00:00:00:10"
12+ var (
13+ defaultDuration = 10 * time .Second
14+ day = 24 * time .Hour
15+ unitPosition = map [int ]time.Duration {
16+ 0 : 24 * time .Hour ,
17+ 1 : time .Hour ,
18+ 2 : time .Minute ,
19+ 3 : time .Second ,
20+ }
21+ )
1222
1323func (d * Duration ) String () string {
14- return string (* d )
24+ m := time .Duration (* d )
25+ days := m / day
26+ m -= days * day
27+ hours := m / time .Hour
28+ m -= hours * time .Hour
29+ minutes := m / time .Minute
30+ m -= minutes * time .Minute
31+ seconds := m / time .Second
32+ return fmt .Sprintf (
33+ "%02d:%02d:%02d:%02d" ,
34+ days , hours , minutes , seconds ,
35+ )
1536}
1637
1738func (d * Duration ) Set (str string ) error {
39+ if strings .TrimSpace (str ) == "" {
40+ return fmt .Errorf ("empty duration passed" )
41+ }
42+ m , err := time .ParseDuration (str )
43+ if err == nil {
44+ * d = Duration (m )
45+ return d .checkDuration ()
46+ }
47+
1848 split := strings .Split (str , ":" )
1949 if len (split ) != 4 {
2050 return fmt .Errorf (
2151 "wrong duration format provided \" %s\" , should be \" dd:hh:mm:ss\" " ,
2252 str ,
2353 )
2454 }
25- for _ , s := range split {
26- if _ , err := strconv .Atoi (s ); err != nil {
55+ for i := range split {
56+ n , err := strconv .Atoi (split [i ])
57+ if err != nil {
2758 return fmt .Errorf (
28- "wrong duration format provided \" %s \" , should be \" dd:hh:mm:ss \" " ,
59+ "not a number value provided for duration: \" %s \" " ,
2960 str ,
3061 )
3162 }
63+ m += time .Duration (n ) * unitPosition [i ]
64+ }
65+ * d = Duration (m )
66+ return d .checkDuration ()
67+ }
68+
69+ func (d * Duration ) checkDuration () error {
70+ if time .Duration (* d ) < (1 * time .Second ) {
71+ return fmt .Errorf ("provided duration is to low, minimum 1 second" )
3272 }
33- * d = Duration (str )
3473 return nil
3574}
3675
@@ -39,5 +78,10 @@ func (d *Duration) Type() string {
3978}
4079
4180func (d * Duration ) Description () string {
42- return "Trace for the given timespan and then automatically stop the trace. Provided in the form of dd:hh:mm:ss"
81+ return "Trace for the given timespan and then automatically stop the trace." +
82+ fmt .Sprintf (
83+ "Provided in the form of dd:hh:mm:ss or " +
84+ "corresponding time unit representation (e.g. 1s, 2m, 3h) (default %s)" ,
85+ defaultDuration ,
86+ )
4387}
0 commit comments