| 1 |
package godo |
| 2 |
|
| 3 |
import ( |
| 4 |
"bufio" |
| 5 |
"fmt" |
| 6 |
"os" |
| 7 |
"path/filepath" |
| 8 |
"strconv" |
| 9 |
"strings" |
| 10 |
|
| 11 |
"github.com/howeyc/gopass" |
| 12 |
"github.com/mgutz/str" |
| 13 |
"github.com/nozzle/throttler" |
| 14 |
"gopkg.in/godo.v2/util" |
| 15 |
) |
| 16 |
|
| 17 |
// Bash executes a bash script (string). |
| 18 |
func Bash(script string, options ...map[string]interface{}) (string, error) { |
| 19 |
return bash(script, options) |
| 20 |
} |
| 21 |
|
| 22 |
// BashOutput executes a bash script and returns the output |
| 23 |
func BashOutput(script string, options ...map[string]interface{}) (string, error) { |
| 24 |
if len(options) == 0 { |
| 25 |
options = append(options, M{"$out": CaptureBoth}) |
| 26 |
} else { |
| 27 |
options[0]["$out"] = CaptureBoth |
| 28 |
} |
| 29 |
return bash(script, options) |
| 30 |
} |
| 31 |
|
| 32 |
// Run runs a command. |
| 33 |
func Run(commandstr string, options ...map[string]interface{}) (string, error) { |
| 34 |
return run(commandstr, options) |
| 35 |
} |
| 36 |
|
| 37 |
// RunOutput runs a command and returns output. |
| 38 |
func RunOutput(commandstr string, options ...map[string]interface{}) (string, error) { |
| 39 |
if len(options) == 0 { |
| 40 |
options = append(options, M{"$out": CaptureBoth}) |
| 41 |
} else { |
| 42 |
options[0]["$out"] = CaptureBoth |
| 43 |
} |
| 44 |
return run(commandstr, options) |
| 45 |
} |
| 46 |
|
| 47 |
// Start starts an async command. If executable has suffix ".go" then it will |
| 48 |
// be "go install"ed then executed. Use this for watching a server task. |
| 49 |
// |
| 50 |
// If Start is called with the same command it kills the previous process. |
| 51 |
// |
| 52 |
// The working directory is optional. |
| 53 |
func Start(commandstr string, options ...map[string]interface{}) error { |
| 54 |
return startEx(nil, commandstr, options) |
| 55 |
} |
| 56 |
|
| 57 |
func rebuildPackage(filename string) error { |
| 58 |
_, err := Run("go build", M{"$in": filepath.Dir(filename)}) |
| 59 |
return err |
| 60 |
} |
| 61 |
|
| 62 |
func startEx(context *Context, commandstr string, options []map[string]interface{}) error { |
| 63 |
m, dir, _, err := parseOptions(options) |
| 64 |
if err != nil { |
| 65 |
return err |
| 66 |
} |
| 67 |
if strings.Contains(commandstr, "{{") { |
| 68 |
commandstr, err = util.StrTemplate(commandstr, m) |
| 69 |
if err != nil { |
| 70 |
return err |
| 71 |
} |
| 72 |
} |
| 73 |
executable, argv, env := splitCommand(commandstr) |
| 74 |
if context != nil && context.FileEvent != nil { |
| 75 |
event := context.FileEvent |
| 76 |
absPath, err := filepath.Abs(filepath.Join(dir, executable)) |
| 77 |
if err != nil { |
| 78 |
return err |
| 79 |
} |
| 80 |
if filepath.Ext(event.Path) == ".go" && event.Path != absPath { |
| 81 |
var p string |
| 82 |
wd, err := os.Getwd() |
| 83 |
if err != nil { |
| 84 |
return err |
| 85 |
} |
| 86 |
p, err = filepath.Rel(wd, event.Path) |
| 87 |
if err != nil { |
| 88 |
p = event.Path |
| 89 |
} |
| 90 |
util.Info(context.Task.Name, "rebuilding %s...\n", filepath.Dir(p)) |
| 91 |
rebuildPackage(event.Path) |
| 92 |
} |
| 93 |
} |
| 94 |
isGoFile := strings.HasSuffix(executable, ".go") |
| 95 |
if isGoFile { |
| 96 |
cmdstr := "go install" |
| 97 |
if context == nil || context.FileEvent == nil { |
| 98 |
util.Info(context.Task.Name, "rebuilding with -a to ensure clean build (might take awhile)\n") |
| 99 |
cmdstr += " -a" |
| 100 |
} |
| 101 |
_, err = Run(cmdstr, m) |
| 102 |
if err != nil { |
| 103 |
return err |
| 104 |
} |
| 105 |
executable = filepath.Base(dir) |
| 106 |
} |
| 107 |
cmd := &command{ |
| 108 |
executable: executable, |
| 109 |
wd: dir, |
| 110 |
env: env, |
| 111 |
argv: argv, |
| 112 |
commandstr: commandstr, |
| 113 |
} |
| 114 |
return cmd.runAsync() |
| 115 |
} |
| 116 |
|
| 117 |
func getWorkingDir(m map[string]interface{}) (string, error) { |
| 118 |
pwd, err := os.Getwd() |
| 119 |
if err != nil { |
| 120 |
return "", nil |
| 121 |
} |
| 122 |
|
| 123 |
var wd string |
| 124 |
if m != nil { |
| 125 |
if d, ok := m["$in"].(string); ok { |
| 126 |
wd = d |
| 127 |
} |
| 128 |
} |
| 129 |
if wd != "" { |
| 130 |
var path string |
| 131 |
if filepath.IsAbs(wd) { |
| 132 |
path = wd |
| 133 |
} else { |
| 134 |
path = filepath.Join(pwd, wd) |
| 135 |
} |
| 136 |
_, err := os.Stat(path) |
| 137 |
if err == nil { |
| 138 |
return path, nil |
| 139 |
} |
| 140 |
return "", fmt.Errorf("working dir does not exist: %s", path) |
| 141 |
} |
| 142 |
return pwd, nil |
| 143 |
} |
| 144 |
|
| 145 |
func parseOptions(options []map[string]interface{}) (m map[string]interface{}, dir string, capture int, err error) { |
| 146 |
if options == nil { |
| 147 |
m = map[string]interface{}{} |
| 148 |
} else { |
| 149 |
m = options[0] |
| 150 |
} |
| 151 |
|
| 152 |
dir, err = getWorkingDir(m) |
| 153 |
if err != nil { |
| 154 |
return nil, "", 0, err |
| 155 |
} |
| 156 |
|
| 157 |
if n, ok := m["$out"].(int); ok { |
| 158 |
capture = n |
| 159 |
} |
| 160 |
|
| 161 |
return m, dir, capture, nil |
| 162 |
} |
| 163 |
|
| 164 |
// Bash executes a bash string. Use backticks for multiline. To execute as shell script, |
| 165 |
// use Run("bash script.sh") |
| 166 |
func bash(script string, options []map[string]interface{}) (output string, err error) { |
| 167 |
m, dir, capture, err := parseOptions(options) |
| 168 |
if err != nil { |
| 169 |
return "", err |
| 170 |
} |
| 171 |
|
| 172 |
if strings.Contains(script, "{{") { |
| 173 |
script, err = util.StrTemplate(script, m) |
| 174 |
if err != nil { |
| 175 |
return "", err |
| 176 |
} |
| 177 |
} |
| 178 |
|
| 179 |
gcmd := &command{ |
| 180 |
executable: "bash", |
| 181 |
argv: []string{"-c", script}, |
| 182 |
wd: dir, |
| 183 |
capture: capture, |
| 184 |
commandstr: script, |
| 185 |
} |
| 186 |
|
| 187 |
return gcmd.run() |
| 188 |
} |
| 189 |
|
| 190 |
func run(commandstr string, options []map[string]interface{}) (output string, err error) { |
| 191 |
m, dir, capture, err := parseOptions(options) |
| 192 |
if err != nil { |
| 193 |
return "", err |
| 194 |
} |
| 195 |
|
| 196 |
if strings.Contains(commandstr, "{{") { |
| 197 |
commandstr, err = util.StrTemplate(commandstr, m) |
| 198 |
if err != nil { |
| 199 |
return "", err |
| 200 |
} |
| 201 |
} |
| 202 |
|
| 203 |
lines := strings.Split(commandstr, "\n") |
| 204 |
if len(lines) == 0 { |
| 205 |
return "", fmt.Errorf("Empty command string") |
| 206 |
} |
| 207 |
for i, cmdline := range lines { |
| 208 |
cmdstr := strings.Trim(cmdline, " \t") |
| 209 |
if cmdstr == "" { |
| 210 |
continue |
| 211 |
} |
| 212 |
executable, argv, env := splitCommand(cmdstr) |
| 213 |
|
| 214 |
cmd := &command{ |
| 215 |
executable: executable, |
| 216 |
wd: dir, |
| 217 |
env: env, |
| 218 |
argv: argv, |
| 219 |
capture: capture, |
| 220 |
commandstr: commandstr, |
| 221 |
} |
| 222 |
|
| 223 |
s, err := cmd.run() |
| 224 |
if err != nil { |
| 225 |
err = fmt.Errorf(err.Error()+"\nline=%d", i) |
| 226 |
return s, err |
| 227 |
} |
| 228 |
output += s |
| 229 |
} |
| 230 |
return output, nil |
| 231 |
} |
| 232 |
|
| 233 |
// func getWd(wd []In) (string, error) { |
| 234 |
// if len(wd) == 1 { |
| 235 |
// return wd[0][0], nil |
| 236 |
// } |
| 237 |
// return os.Getwd() |
| 238 |
// } |
| 239 |
|
| 240 |
func splitCommand(command string) (executable string, argv, env []string) { |
| 241 |
argv = str.ToArgv(command) |
| 242 |
for i, item := range argv { |
| 243 |
if strings.Contains(item, "=") { |
| 244 |
if env == nil { |
| 245 |
env = []string{item} |
| 246 |
continue |
| 247 |
} |
| 248 |
env = append(env, item) |
| 249 |
} else { |
| 250 |
executable = item |
| 251 |
argv = argv[i+1:] |
| 252 |
return |
| 253 |
} |
| 254 |
} |
| 255 |
|
| 256 |
executable = argv[0] |
| 257 |
argv = argv[1:] |
| 258 |
return |
| 259 |
} |
| 260 |
|
| 261 |
func toInt(s string) int { |
| 262 |
result, err := strconv.Atoi(s) |
| 263 |
if err != nil { |
| 264 |
return 0 |
| 265 |
} |
| 266 |
return result |
| 267 |
} |
| 268 |
|
| 269 |
// Inside temporarily changes the working directory and restores it when lambda |
| 270 |
// finishes. |
| 271 |
func Inside(dir string, lambda func()) error { |
| 272 |
olddir, err := os.Getwd() |
| 273 |
if err != nil { |
| 274 |
return err |
| 275 |
} |
| 276 |
|
| 277 |
err = os.Chdir(dir) |
| 278 |
if err != nil { |
| 279 |
return err |
| 280 |
} |
| 281 |
|
| 282 |
defer func() { |
| 283 |
os.Chdir(olddir) |
| 284 |
}() |
| 285 |
lambda() |
| 286 |
return nil |
| 287 |
} |
| 288 |
|
| 289 |
// Prompt prompts user for input with default value. |
| 290 |
func Prompt(prompt string) string { |
| 291 |
reader := bufio.NewReader(os.Stdin) |
| 292 |
fmt.Print(prompt) |
| 293 |
text, _ := reader.ReadString('\n') |
| 294 |
return text |
| 295 |
} |
| 296 |
|
| 297 |
// PromptPassword prompts user for password input. |
| 298 |
func PromptPassword(prompt string) string { |
| 299 |
fmt.Printf(prompt) |
| 300 |
b, err := gopass.GetPasswd() |
| 301 |
if err != nil { |
| 302 |
fmt.Println(err.Error()) |
| 303 |
return "" |
| 304 |
} |
| 305 |
return string(b) |
| 306 |
} |
| 307 |
|
| 308 |
// GoThrottle starts to run the given list of fns concurrently, |
| 309 |
// at most n fns at a time. |
| 310 |
func GoThrottle(throttle int, fns ...func() error) error { |
| 311 |
var err error |
| 312 |
|
| 313 |
// Create a new Throttler that will get 2 urls at a time |
| 314 |
t := throttler.New(throttle, len(fns)) |
| 315 |
for _, fn := range fns { |
| 316 |
// Launch a goroutine to fetch the URL. |
| 317 |
go func(f func() error) { |
| 318 |
err2 := f() |
| 319 |
if err2 != nil { |
| 320 |
err = err2 |
| 321 |
} |
| 322 |
|
| 323 |
// Let Throttler know when the goroutine completes |
| 324 |
// so it can dispatch another worker |
| 325 |
t.Done(err) |
| 326 |
}(fn) |
| 327 |
// Pauses until a worker is available or all jobs have been completed |
| 328 |
// Returning the total number of goroutines that have errored |
| 329 |
// lets you choose to break out of the loop without starting any more |
| 330 |
errorCount := t.Throttle() |
| 331 |
if errorCount > 0 { |
| 332 |
break |
| 333 |
} |
| 334 |
} |
| 335 |
return err |
| 336 |
} |