forked from jessfraz/junk
/
utilities.go
98 lines (82 loc) · 2.06 KB
/
utilities.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
98
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"text/tabwriter"
"time"
"github.com/docker/go-units"
"github.com/mitchellh/colorstring"
)
func stringTimeToHuman(ts string) (ds string) {
tt, err := time.Parse("2006-01-02T15:04:05Z07:00", ts)
if err != nil {
return ts
}
d := time.Since(tt)
return units.HumanDuration(d)
}
func printPrettyJSON(v interface{}, printRaw bool) {
b, _ := json.MarshalIndent(v, "", " ")
code := string(b)
if printRaw {
fmt.Println(code)
} else {
// look for Pygments to highlight code
var pygmentsBin = "pygmentize"
if _, err := exec.LookPath(pygmentsBin); err != nil {
printWarning(errors.New("Could not find `Pygments` installed on your system. To pretty print the json please pip install `Pygments` and make sure it is in your path"))
fmt.Println(code)
return
}
var out bytes.Buffer
var stderr bytes.Buffer
cmd := exec.Command(pygmentsBin, "-fterminal256", "-Ofull,style=native", "-ljson")
cmd.Stdin = strings.NewReader(code)
cmd.Stdout = &out
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
printError(fmt.Errorf("Error running pygmentize: %s", stderr.String()), false)
fmt.Println(code)
return
}
fmt.Println(out.String())
}
return
}
func stripColon(s string) string {
colI := strings.Index(s, ":")
if colI > -1 && colI < len(s)-1 {
return s[colI+1:]
}
return s
}
func printTotals(totals map[string]string) {
if len(totals) > 0 {
header := []string{"Totals"}
row := []string{"-"}
fmt.Println("")
w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0)
for k, v := range totals {
header = append(header, stripColon(k))
row = append(row, v)
}
fmt.Fprintln(w, colorstring.Color("[cyan]"+strings.Join(header, "\t")))
fmt.Fprintln(w, colorstring.Color("[blue]"+strings.Join(row, "\t")))
w.Flush()
}
return
}
func printWarning(err error) {
fmt.Println(colorstring.Color("[yellow]" + err.Error()))
}
func printError(err error, exit bool) {
fmt.Println(colorstring.Color("[red]" + err.Error()))
if exit {
os.Exit(1)
}
}