-
Notifications
You must be signed in to change notification settings - Fork 5
/
glu.go
138 lines (120 loc) · 2.5 KB
/
glu.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/progrium/go-shell"
"github.com/spf13/cobra"
)
var (
sh = shell.Run
q = shell.Quote
Version string
)
var Glu = &cobra.Command{
Use: "glu",
Short: "glu is a collection of utility commands for Glider Labs projects",
Run: func(cmd *cobra.Command, args []string) {
cmd.Help()
},
}
var versionCmd = &cobra.Command{
Use: "version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(Version)
},
}
func main() {
Glu.AddCommand(versionCmd)
Glu.Execute()
}
func fatal(err error) {
if err != nil {
fmt.Println("!!", err)
os.Exit(1)
}
}
func fatalMsg(err error, msg string) {
if err != nil {
fmt.Println("!!", msg)
os.Exit(1)
}
}
func optArg(args []string, i int, default_ string) string {
if i+1 > len(args) {
return default_
}
return args[i]
}
func exists(path ...string) bool {
_, err := os.Stat(filepath.Join(path...))
if err == nil {
return true
}
if os.IsNotExist(err) {
return false
}
fatal(err)
return true
}
func readFile(path string) string {
data, err := ioutil.ReadFile(path)
if err != nil {
return ""
}
return strings.Trim(string(data), "\n ")
}
func writeFile(path, data string) {
fatal(ioutil.WriteFile(path, []byte(strings.Trim(data, "\n")+"\n"), 0644))
}
func mkdirAll(path ...string) {
fatal(os.MkdirAll(filepath.Join(path...), 0777))
}
func shellOutput(cmd string) string {
args := strings.Split(cmd, " ")
out, _ := exec.Command(args[0], args[1:]...).Output()
return strings.Trim(string(out), " \n")
}
func repoLocation() string {
if insideContainer() {
os.Chdir("/project")
}
repo := shellOutput("git config --get remote.origin.url")
repo = strings.TrimPrefix(repo, "http://")
repo = strings.TrimPrefix(repo, "https://")
repo = strings.TrimPrefix(repo, "git@")
repo = strings.TrimSuffix(repo, ".git")
return strings.Replace(repo, ":", "/", -1)
}
func normalizeVersion(v string) string {
return strings.TrimLeft(v, "v")
}
func findVersion() string {
if insideContainer() {
os.Chdir("/project")
}
if exists("VERSION") {
return normalizeVersion(readFile("VERSION"))
}
if exists("Makefile") {
f, err := os.Open("Makefile")
if err != nil {
return ""
}
defer f.Close()
scanner := bufio.NewScanner(f)
re := regexp.MustCompile("VERSION=(.+)")
for scanner.Scan() {
matches := re.FindAllStringSubmatch(scanner.Text(), 1)
if len(matches) > 0 {
return normalizeVersion(matches[0][1])
}
}
}
return ""
}