-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathcountdown.go
58 lines (47 loc) · 1.07 KB
/
countdown.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
package main
import (
"errors"
"fmt"
"time"
"github.com/muesli/coral"
)
var countdownCmd = &coral.Command{
Use: "countdown",
Short: "Triggers a countdown and continuously updates a label with the remaining time",
RunE: func(cmd *coral.Command, args []string) error {
if len(args) < 2 {
return errors.New("countdown requires a label and the countdown in seconds")
}
d, err := time.ParseDuration(args[1])
if err != nil {
return err
}
return countdown(args[0], d)
},
}
func countdown(label string, duration time.Duration) error {
until := time.Now().Add(duration).Add(time.Second)
c := time.Tick(time.Second)
for range c {
rem := time.Until(until)
if rem < 0 {
rem = 0
}
if err := changeLabel(label, fmtDuration(rem)); err != nil {
return err
}
if time.Now().After(until) {
break
}
}
return nil
}
func fmtDuration(d time.Duration) string {
d = d.Round(time.Second)
m := d % time.Hour / time.Minute
s := d % time.Minute / time.Second
return fmt.Sprintf("%02d:%02d", m, s)
}
func init() {
labelCmd.AddCommand(countdownCmd)
}