forked from pkallberg/cx
/
util.go
483 lines (431 loc) · 10.3 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
package main
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"os/exec"
"os/user"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/cloud66/cloud66"
"github.com/cloud66/cx/term"
"github.com/mgutz/ansi"
)
func cxHome() string {
return filepath.Join(homePath(), ".cloud66")
}
// 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 expandPath(filePath string) string {
if filePath[:2] == "~/" {
usr, _ := user.Current()
dir := usr.HomeDir
return strings.Replace(filePath, "~", dir, 1)
} else {
return filePath
}
}
// concatenates the file content and returns a new one
func appendFiles(files []string, filename string) error {
if debugMode {
log.Printf("Concatenating to %s\n", filename)
}
d, err := os.Create(filename)
defer func() {
cerr := d.Close()
if err == nil {
err = cerr
}
}()
if err != nil {
return err
}
for _, fn := range files {
f, err := os.Open(fn)
defer f.Close()
if debugMode {
log.Printf("Adding %s to %s\n", fn, filename)
}
if _, err = io.Copy(d, f); err != nil {
return err
}
err = d.Sync()
if err != nil {
return err
}
}
return nil
}
func must(err error) {
if err != nil {
if debugMode {
log.Fatal(err)
}
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...))
}
// potentially needs refactor --> genericresponse type?
func printGenericResponse(genericRes cloud66.GenericResponse) {
var result string
if genericRes.Status == true {
result = "Success"
if genericRes.Message != "" {
result = result + ": " + genericRes.Message
} else {
result = result + "!"
}
log.Println(result)
} else {
result = "Failed"
if genericRes.Message != "" {
result = result + ": " + genericRes.Message
} else {
result = result + "!"
}
printFatal(result)
}
}
func mustConfirm(warning, desired string) {
if term.IsTerminal(os.Stdin) {
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 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")
}
func HealthText(c cloud66.Container) string {
switch c.HealthState {
case cloud66.CNT_HEALTH_UNVERIFIED:
return "Unverified"
case cloud66.CNT_HEALTH_UP:
return fmt.Sprintf("Up (reported by %s)", c.HealthSource)
case cloud66.CNT_HEALTH_DOWN:
return fmt.Sprintf("Down (reported by %s)", c.HealthSource)
default:
return "Unknown health state"
}
}
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 downloadFile(source string, output string) error {
out, err := os.Create(output)
defer out.Close()
if err != nil {
return err
}
resp, err := http.Get(source)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}
// runs the command using OS specific commands
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
}
if debugMode {
fmt.Printf("Running Command %s with (%s)\n", command, args)
}
return sysExec(command, args, env)
}
func startProgram(command string, args []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
}
if debugMode {
fmt.Printf("Running Command %s with (%s)\n", command, args)
}
cmd := exec.Command(command, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
return err
}
return nil
}
func prepareLocalSshKey(server cloud66.Server) (string, error) {
var sshFile string
if server.PersonalKey {
oldFile := filepath.Join(homePath(), ".ssh", "cx_"+server.StackUid)
if b, _ := fileExists(sshFile); !b {
os.Remove(oldFile)
}
sshFile = filepath.Join(homePath(), ".ssh", "cx_"+server.StackUid+"_pkey")
// remove the old sshkey
} else {
sshFile = filepath.Join(homePath(), ".ssh", "cx_"+server.StackUid)
}
// do we have the key?
if b, _ := fileExists(sshFile); !b {
// get the content and write the file
fmt.Println("Fetching SSH key...")
sshKey, err := client.ServerKeyInformation(server.StackUid, server.Uid)
if err != nil {
return "", err
}
if err = writeSshFile(sshFile, sshKey); err != nil {
return "", err
}
} else {
if debugMode {
fmt.Println("Found an existing SSH key for this server")
}
}
return sshFile, nil
}
func writeSshFile(filename string, content string) error {
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
defer file.Close()
if err != nil {
return err
}
if _, err := file.WriteString(content); err != nil {
return err
}
return nil
}
func writeFile(filename, content string) error {
file, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600)
defer file.Close()
if err != nil {
return err
}
if _, err := file.WriteString(content); err != nil {
return err
}
return nil
}
// finds the item in the list without case sensitivity, and returns the index
// of the item that matches or begins with the given item
// if more than one match is found, it returns an error
func fuzzyFind(s []string, item string, matchFirstIfMany bool) (int, error) {
var results []int
for i := range s {
// look for identical matches first
if strings.ToLower(s[i]) == strings.ToLower(item) {
if matchFirstIfMany {
return i, nil
} else {
results = append(results, i)
}
}
}
if len(results) == 1 {
return results[0], nil
}
if len(results) > 1 {
return 0, errors.New("More than one match found for " + item + " you might get better results by passing the environment with -e")
}
for i := range s {
if strings.HasPrefix(strings.ToLower(s[i]), strings.ToLower(item)) {
if matchFirstIfMany {
return i, nil
} else {
results = append(results, i)
}
}
}
if len(results) == 0 {
return 0, errors.New("No match found for " + item)
}
if len(results) > 1 {
return 0, errors.New("More than one match found for " + item)
}
return results[0], nil
}
func stringsIndex(s []string, item string) int {
for i := range s {
if s[i] == item {
return i
}
}
return -1
}
func findServer(servers []cloud66.Server, serverName string) (*cloud66.Server, error) {
// what is provided? IP, name or role?
// is it an IP?
ip := net.ParseIP(serverName)
if ip != nil {
// it is an IP
for _, server := range servers {
if server.Address == serverName {
// found it.
return &server, nil
}
}
} else {
var names []string
var mappedServers []cloud66.Server
// collect the server names first
for _, server := range servers {
// if its an exact server name match then return the server
if server.Name == serverName {
return &server, nil
}
names = append(names, server.Name)
mappedServers = append(mappedServers, server)
}
// collect the server roles second
for _, server := range servers {
for _, role := range server.Roles {
names = append(names, role)
mappedServers = append(mappedServers, server)
}
}
idx, err := fuzzyFind(names, serverName, true)
if err != nil {
return nil, err
}
return &mappedServers[idx], nil
}
return nil, nil
}
var camelingRegex = regexp.MustCompile("[0-9A-Za-z]+")
func camelCase(src string, sep string) string {
byteSrc := []byte(src)
chunks := camelingRegex.FindAll(byteSrc, -1)
for idx, val := range chunks {
if idx > 0 {
chunks[idx] = bytes.Title(val)
}
}
return string(bytes.Join(chunks, []byte(sep)))
}
func pascalCase(src string, sep string) string {
byteSrc := []byte(src)
chunks := camelingRegex.FindAll(byteSrc, -1)
for idx, val := range chunks {
chunks[idx] = bytes.Title(val)
}
return string(bytes.Join(chunks, []byte(sep)))
}