forked from remind101/empire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
307 lines (266 loc) · 6.17 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/chzyer/readline"
"github.com/mgutz/ansi"
"github.com/remind101/empire/cmd/emp/hkclient"
"github.com/remind101/empire/pkg/heroku"
)
var nrc *hkclient.NetRc
func hkHome() string {
return filepath.Join(hkclient.HomePath(), ".hk")
}
func netrcPath() string {
if s := os.Getenv("NETRC_PATH"); s != "" {
return s
}
return filepath.Join(hkclient.HomePath(), netrcFilename)
}
func loadNetrc() {
var err error
if nrc == nil {
if nrc, err = hkclient.LoadNetRc(); err != nil {
if os.IsNotExist(err) {
nrc = &hkclient.NetRc{}
return
}
printFatal("loading netrc: " + err.Error())
}
}
}
func getCreds(u string) (user, pass string) {
loadNetrc()
if nrc == nil {
return "", ""
}
apiURL, err := url.Parse(u)
if err != nil {
printFatal("invalid API URL: %s", err)
}
user, pass, err = nrc.GetCreds(apiURL)
if err != nil {
printError(err.Error())
}
return user, pass
}
func saveCreds(host, user, pass string) error {
loadNetrc()
m := nrc.FindMachine(host)
if m == nil || m.IsDefault() {
m = nrc.NewMachine(host, user, pass, "")
}
m.UpdateLogin(user)
m.UpdatePassword(pass)
body, err := nrc.MarshalText()
if err != nil {
return err
}
return ioutil.WriteFile(netrcPath(), body, 0600)
}
func removeCreds(host string) error {
loadNetrc()
nrc.RemoveMachine(host)
body, err := nrc.MarshalText()
if err != nil {
return err
}
return ioutil.WriteFile(netrcPath(), body, 0600)
}
// exists returns whether the given file or directory exists or not
func fileExists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
func must(err error) {
if err != nil {
if herror, ok := err.(heroku.Error); ok {
switch herror.Id {
case "two_factor":
printError(err.Error() + " Authorize with `emp authorize`.")
os.Exit(79)
case "unauthorized":
printFatal(err.Error() + " Log in with `emp login`.")
}
}
printFatal(err.Error())
}
}
func printError(message string, args ...interface{}) {
log.Println(colorizeMessage("red", "error:", message, args...))
}
func printFatal(message string, args ...interface{}) {
log.Fatal(colorizeMessage("red", "error:", message, args...))
}
func printWarning(message string, args ...interface{}) {
log.Println(colorizeMessage("yellow", "warning:", message, args...))
}
func mustConfirm(warning, desired string) {
if isTerminalIn {
printWarning(warning)
fmt.Printf("> ")
}
var confirm string
if _, err := fmt.Scanln(&confirm); err != nil {
printFatal(err.Error())
}
if confirm != desired {
printFatal("Confirmation did not match %q.", desired)
}
}
func askForMessage() (string, error) {
if !isTerminalIn {
return "", errors.New("Can't ask for message")
}
fmt.Println("A commit message is required, enter one below:")
reader, err := readline.New("> ")
if err != nil {
return "", err
}
message, err := reader.Readline()
return strings.Trim(message, " \n"), err
}
func colorizeMessage(color, prefix, message string, args ...interface{}) string {
prefResult := ""
if prefix != "" {
prefResult = ansi.Color(prefix, color+"+b") + " " + ansi.ColorCode("reset")
}
return prefResult + ansi.Color(fmt.Sprintf(message, args...), color) + ansi.ColorCode("reset")
}
func listRec(w io.Writer, a ...interface{}) {
for i, x := range a {
fmt.Fprint(w, x)
if i+1 < len(a) {
w.Write([]byte{'\t'})
} else {
w.Write([]byte{'\n'})
}
}
}
type prettyTime struct {
time.Time
}
func (s prettyTime) String() string {
if time.Now().Sub(s.Time) < 12*30*24*time.Hour {
return s.Local().Format("Jan _2 15:04")
}
return s.Local().Format("Jan _2 2006")
}
type prettyDuration struct {
time.Duration
}
func (a prettyDuration) String() string {
switch d := a.Duration; {
case d > 2*24*time.Hour:
return a.Unit(24*time.Hour, "d")
case d > 2*time.Hour:
return a.Unit(time.Hour, "h")
case d > 2*time.Minute:
return a.Unit(time.Minute, "m")
}
return a.Unit(time.Second, "s")
}
func (a prettyDuration) Unit(u time.Duration, s string) string {
return fmt.Sprintf("%2d", roundDur(a.Duration, u)) + s
}
func roundDur(d, k time.Duration) int {
return int((d + k/2 - 1) / k)
}
func abbrev(s string, n int) string {
if len(s) > n {
return s[:n-1] + "…"
}
return s
}
func ensurePrefix(val, prefix string) string {
if !strings.HasPrefix(val, prefix) {
return prefix + val
}
return val
}
func ensureSuffix(val, suffix string) string {
if !strings.HasSuffix(val, suffix) {
return val + suffix
}
return val
}
func openURL(url string) error {
var command string
var args []string
switch runtime.GOOS {
case "darwin":
command = "open"
args = []string{command, url}
case "windows":
command = "cmd"
args = []string{"/c", "start " + strings.Replace(url, "&", "^&", -1)}
default:
if _, err := exec.LookPath("xdg-open"); err != nil {
log.Println("xdg-open is required to open web pages on " + runtime.GOOS)
os.Exit(2)
}
command = "xdg-open"
args = []string{command, url}
}
return runCommand(command, args, os.Environ())
}
func runCommand(command string, args, env []string) error {
if runtime.GOOS != "windows" {
p, err := exec.LookPath(command)
if err != nil {
log.Printf("Error finding path to %q: %s\n", command, err)
os.Exit(2)
}
command = p
}
return sysExec(command, args, env)
}
func stringsIndex(s []string, item string) int {
for i := range s {
if s[i] == item {
return i
}
}
return -1
}
func retryMessageRequired(retry func(), cleanup func()) {
if r := recover(); r != nil {
e := r.(heroku.Error)
if e.Id == "message_required" {
message, err := askForMessage()
if message == "" || err != nil {
printFatal("A message is required for this action, please run again with '-m'.")
}
flagMessage = message
retry()
}
}
if cleanup != nil {
cleanup()
}
}
func maybeMessage(action func(cmd *Command, args []string)) func(cmd *Command, args []string) {
return func(cmd *Command, args []string) {
retry := func() {
action(cmd, args)
}
defer retryMessageRequired(retry, nil)
action(cmd, args)
}
}