-
Notifications
You must be signed in to change notification settings - Fork 456
/
utils.go
70 lines (64 loc) · 1.4 KB
/
utils.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
package main
import (
"bytes"
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"text/template"
"time"
)
func RandomString(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.URLEncoding.EncodeToString(b)[:n]
}
func Overwrite(filename string, data []byte, perm os.FileMode) error {
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename)+".tmp")
if err != nil {
return err
}
if _, err := f.Write(data); err != nil {
return err
}
if err := f.Sync(); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
if err := os.Chmod(f.Name(), perm); err != nil {
return err
}
return os.Rename(f.Name(), filename)
}
func bash(tmpl string, params interface{}) (string, error) {
preamble := `
set -o nounset
set -o errexit
set -o pipefail
set -o xtrace
`
t, err := template.New("template").Parse(preamble + tmpl)
if err != nil {
return "", err
}
var script bytes.Buffer
err = t.Execute(&script, params)
if err != nil {
return "", err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
output, err := exec.CommandContext(ctx, "/bin/bash", "-c", string(script.Bytes())).CombinedOutput()
if err != nil {
return string(output), fmt.Errorf("command failed: %s\n%s", err, string(output))
}
return string(output), nil
}