-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
wet_runner.go
101 lines (91 loc) · 1.87 KB
/
wet_runner.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
package genny
import (
"context"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/gobuffalo/logger"
)
// WetRunner will execute commands and write files
// it is DESTRUCTIVE
func WetRunner(ctx context.Context) *Runner {
r := DryRunner(ctx)
l := logger.New(DefaultLogLvl)
r.Logger = l
r.ExecFn = wetExecFn
r.FileFn = func(f File) (File, error) {
return wetFileFn(r, f)
}
r.DeleteFn = os.RemoveAll
r.RequestFn = wetRequestFn
r.ChdirFn = func(path string, fn func() error) error {
pwd, _ := os.Getwd()
defer os.Chdir(pwd)
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
if err := os.Chdir(path); err != nil {
return err
}
return fn()
}
r.LookPathFn = exec.LookPath
return r
}
func wetRequestFn(req *http.Request, c *http.Client) (*http.Response, error) {
if c == nil {
c = &http.Client{}
}
ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)
defer cancel()
req = req.WithContext(ctx)
res, err := c.Do(req)
if err != nil {
return res, err
}
if res.StatusCode >= 400 {
return res, fmt.Errorf("response returned non-success code: %d", res.StatusCode)
}
return res, nil
}
func wetExecFn(cmd *exec.Cmd) error {
if cmd.Stdin == nil {
cmd.Stdin = os.Stdin
}
if cmd.Stdout == nil {
cmd.Stdout = os.Stdout
}
if cmd.Stderr == nil {
cmd.Stderr = os.Stderr
}
return cmd.Run()
}
func wetFileFn(r *Runner, f File) (File, error) {
if d, ok := f.(Dir); ok {
if err := os.MkdirAll(d.Name(), d.Perm); err != nil {
return f, err
}
return d, nil
}
name := f.Name()
if !filepath.IsAbs(name) {
name = filepath.Join(r.Root, name)
}
dir := filepath.Dir(name)
if err := os.MkdirAll(dir, 0755); err != nil {
return f, err
}
ff, err := os.Create(name)
if err != nil {
return f, err
}
defer ff.Close()
if _, err := io.Copy(ff, f); err != nil {
return f, err
}
return f, nil
}