forked from justjanne/powerline-go
/
segment-duration.go
86 lines (77 loc) · 1.97 KB
/
segment-duration.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
package main
import (
"fmt"
"strings"
"time"
)
const (
micro rune = '\u00B5'
milli rune = 'm'
second rune = 's'
minute rune = 'm'
hour rune = 'h'
)
const (
nanoseconds int64 = 1
microseconds int64 = nanoseconds * 1000
milliseconds int64 = microseconds * 1000
seconds int64 = milliseconds * 1000
minutes int64 = seconds * 60
hours int64 = minutes * 60
)
func segmentDuration(p *powerline) {
if p.args.Duration == nil || *p.args.Duration == "" {
p.appendSegment("duration", segment{
content: "No duration",
foreground: p.theme.DurationFg,
background: p.theme.DurationBg,
})
return
}
durationValue := strings.Trim(*p.args.Duration, "'\"")
hasPrecision := strings.Index(durationValue, ".") != -1
d, err := time.ParseDuration(durationValue + "s")
if err != nil {
p.appendSegment("duration", segment{
content: fmt.Sprintf("Failed to convert '%s' to a number", *p.args.Duration),
foreground: p.theme.DurationFg,
background: p.theme.DurationBg,
})
return
}
if d > 0 {
var content string
ns := d.Nanoseconds()
if ns > hours {
hrs := ns / hours
ns -= hrs * hours
mins := ns / minutes
content = fmt.Sprintf("%dh %dm", hrs, mins)
} else if ns > minutes {
mins := ns / minutes
ns -= mins * minutes
secs := ns / seconds
content = fmt.Sprintf("%dm %ds", mins, secs)
} else if !hasPrecision {
secs := ns / seconds
content = fmt.Sprintf("%ds", secs)
} else if ns > seconds {
secs := ns / seconds
ns -= secs * seconds
millis := ns / milliseconds
content = fmt.Sprintf("%ds %dms", secs, millis)
} else if ns > milliseconds {
millis := ns / milliseconds
ns -= millis * milliseconds
micros := ns / microseconds
content = fmt.Sprintf("%dms %d\u00B5s", millis, micros)
} else {
content = fmt.Sprintf("%d\u00B5s", ns/microseconds)
}
p.appendSegment("duration", segment{
content: content,
foreground: p.theme.DurationFg,
background: p.theme.DurationBg,
})
}
}