-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
87 lines (71 loc) · 1.6 KB
/
main.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
package main
import (
"flag"
"fmt"
"math"
"os"
"strconv"
"strings"
"time"
"github.com/mikemackintosh/chrono/internal/version"
)
var (
flagMilli bool
flagVersion bool
)
func init() {
flag.BoolVar(&flagMilli, "m", false, "Show current milliseconds")
flag.BoolVar(&flagVersion, "v", false, "Show version")
}
func main() {
var duration time.Duration
flag.Parse()
// Show the version info only if it's requested
if flagVersion {
fmt.Printf("%s - %s\n", version.Version, version.CommitHash)
os.Exit(0)
}
var t = time.Now().UnixMilli()
if flagMilli {
fmt.Println(t)
os.Exit(0)
}
var startTime = os.Getenv("START_TIME")
if len(startTime) == 0 {
fmt.Printf("0ms")
os.Exit(0)
}
i, _ := strconv.Atoi(startTime)
if i > 0 {
duration = time.Since(time.UnixMilli(int64(i)))
}
fmt.Printf("%s", humanizeDuration(duration))
}
// https://gist.github.com/harshavardhana/327e0577c4fed9211f65
func humanizeDuration(duration time.Duration) string {
days := int64(duration.Hours() / 24)
hours := int64(math.Mod(duration.Hours(), 24))
minutes := int64(math.Mod(duration.Minutes(), 60))
seconds := int64(math.Mod(duration.Seconds(), 60))
milliseconds := int64(math.Mod(float64(duration.Milliseconds()), 1000))
chunks := []struct {
singularName string
amount int64
}{
{"d", days},
{"h", hours},
{"m", minutes},
{"s", seconds},
{"ms", milliseconds},
}
parts := []string{}
for _, chunk := range chunks {
switch chunk.amount {
case 0:
continue
default:
parts = append(parts, fmt.Sprintf("%d%s", chunk.amount, chunk.singularName))
}
}
return strings.Join(parts, " ")
}