-
Notifications
You must be signed in to change notification settings - Fork 11
/
util.go
121 lines (108 loc) · 2.13 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 main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"github.com/gliderlabs/hostctl/providers"
"github.com/mitchellh/go-homedir"
"golang.org/x/crypto/ssh/terminal"
)
func newHost(name string) providers.Host {
return providers.Host{
Name: name,
Flavor: hostFlavor,
Image: hostImage,
Region: hostRegion,
Keyname: hostKeyname,
Userdata: hostUserdata,
}
}
func loadStdinUserdata() {
if !terminal.IsTerminal(int(os.Stdin.Fd())) {
data, err := ioutil.ReadAll(os.Stdin)
fatal(err)
hostUserdata = string(data)
}
}
func parallelWait(items []string, fn func(int, string, *sync.WaitGroup)) {
var wg sync.WaitGroup
for i := 0; i < len(items); i++ {
wg.Add(1)
go fn(i, items[i], &wg)
}
wg.Wait()
}
func fatal(err error) {
if err != nil {
fmt.Println("!!", err)
os.Exit(1)
}
}
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 expandHome(path string) string {
if len(path) > 1 && path[:2] == "~/" {
path, _ = homedir.Expand(path)
}
return path
}
func optArg(args []string, i int, default_ string) string {
if i+1 > len(args) {
return default_
}
return args[i]
}
func progressBar(unit string, interval time.Duration) func() {
finished := make(chan bool)
go func() {
for {
select {
case <-finished:
return
case <-time.After(interval * time.Second):
fmt.Fprint(os.Stderr, unit)
}
}
}()
return func() {
finished <- true
fmt.Fprintln(os.Stderr)
}
}
func source(filepath string) error {
file, err := ioutil.ReadFile(filepath)
if err != nil {
return err
}
cmdStr := fmt.Sprintf("source %s 1>&2; env", filepath)
out, err := exec.Command("bash", "-c", cmdStr).Output()
if err != nil {
return err
}
fileStr := string(file)
outLines := strings.Split(string(out), "\n")
for _, line := range outLines {
lineSplit := strings.SplitN(line, "=", 2)
if len(lineSplit) != 2 {
continue
}
if strings.Contains(fileStr, lineSplit[0]) {
os.Setenv(lineSplit[0], lineSplit[1])
}
}
return nil
}