This repository has been archived by the owner on May 29, 2018. It is now read-only.
/
util.go
121 lines (106 loc) · 2.41 KB
/
util.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package cli
import (
"encoding/json"
"errors"
"fmt"
"log"
"math"
"os"
"os/exec"
"strings"
"github.com/alexsaveliev/go-colorable-wrapper"
"golang.org/x/tools/godoc/vfs"
)
type nopWriteCloser struct{}
func (w nopWriteCloser) Write(p []byte) (n int, err error) {
return len(p), nil
}
func (w nopWriteCloser) Close() error {
return nil
}
func isDir(dir string) bool {
di, err := os.Stat(dir)
return err == nil && di.IsDir()
}
func execCmdInDir(cwd, prog string, arg ...string) error {
cmd := exec.Command(prog, arg...)
cmd.Dir = cwd
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stderr
log.Println("Running", cmd.Args, "in", cwd)
if err := cmd.Run(); err != nil {
return fmt.Errorf("command %q failed: %s", cmd.Args, err)
}
return nil
}
func PrintJSON(v interface{}, prefix string) {
data, err := json.MarshalIndent(v, prefix, " ")
if err != nil {
log.Fatal(err)
}
colorable.Println(string(data))
}
var errEmptyJSONFile = errors.New("empty JSON file")
func readJSONFile(file string, v interface{}) error {
fi, err := os.Stat(file)
if err != nil {
return err
}
if fi.Size() < 1 {
return errEmptyJSONFile
}
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
return json.NewDecoder(f).Decode(v)
}
func readJSONFileFS(fs vfs.FileSystem, file string, v interface{}) (err error) {
fi, err := fs.Stat(file)
if err != nil {
return err
}
if fi.Size() < 1 {
return errEmptyJSONFile
}
f, err := fs.Open(file)
if err != nil {
return err
}
defer func() {
err2 := f.Close()
if err == nil {
err = err2
}
}()
return json.NewDecoder(f).Decode(v)
}
func bytesString(s uint64) string {
sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
if s < 10 {
return fmt.Sprintf("%dB", s)
}
logn := func(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}
e := math.Floor(logn(float64(s), 1000))
suffix := sizes[int(e)]
val := math.Floor(float64(s)/math.Pow(1000, math.Floor(e))*10+0.5) / 10
f := "%.0f"
if val < 10 {
f = "%.1f"
}
return fmt.Sprintf(f+"%s", val, suffix)
}
func percent(num, denom int) float64 {
return 100 * float64(num) / float64(denom)
}
// parseRepoAndCommitID parses strings like "example.com/repo" and
// "example.com/repo@myrev".
func parseRepoAndCommitID(repoAndCommitID string) (uri, commitID string) {
if i := strings.Index(repoAndCommitID, "@"); i != -1 {
return repoAndCommitID[:i], repoAndCommitID[i+1:]
}
return repoAndCommitID, ""
}