/
exec.go
129 lines (99 loc) · 2.13 KB
/
exec.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
package hookah
import (
"errors"
"io"
"os"
"os/exec"
"path/filepath"
"time"
"github.com/hashicorp/go-multierror"
)
// HookExec represents a call to a hook
type HookExec struct {
RootDir string
Owner string
Repo string
Event string
Data io.ReadSeeker
HookServer *HookServer
}
// GetPathExecs fetches the executable filenames for the given path
func (h *HookExec) GetPathExecs() ([]string, error) {
path := filepath.Join(h.RootDir, h.Owner, h.Repo, h.Event)
files := []string{}
fs, err := os.Stat(path)
if err != nil {
if os.IsNotExist(err) {
return files, nil
}
return files, err
}
if fs.IsDir() {
d, err := os.Open(path)
defer d.Close()
if err != nil {
return files, err
}
fi, err := d.Readdir(-1)
if err != nil {
return files, err
}
for _, fi := range fi {
if isExecFile(fi) {
// fmt.Println(fi.Name(), fi.Size(), "bytes")
files = append(files, filepath.Join(path, fi.Name()))
}
}
} else if isExecFile(fs) {
// fmt.Println(fs.Name(), fs.Size(), "bytes")
files = append(files, filepath.Join(path, fs.Name()))
} else {
return files, errors.New("bad file mumbo jumbo")
}
return files, nil
}
// Exec triggers the execution of all scripts associated with the given Hook
func (h *HookExec) Exec(timeout time.Duration) error {
files, err := h.GetPathExecs()
if err != nil {
return err
}
var result error
h.HookServer.Lock()
defer h.HookServer.Unlock()
for _, f := range files {
err := execFile(f, h, timeout)
multierror.Append(result, err)
}
return result
}
func execFile(f string, h *HookExec, timeout time.Duration) error {
cmd := exec.Command(f)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
stdin, err := cmd.StdinPipe()
if err != nil {
return err
}
defer stdin.Close()
err = cmd.Start()
if err != nil {
return err
}
h.Data.Seek(0, 0)
io.Copy(stdin, h.Data)
stdin.Close()
timer := time.AfterFunc(timeout, func() {
cmd.Process.Kill()
})
err = cmd.Wait()
timer.Stop()
if err != nil {
return err
}
return nil
}
// todo: base this on OS
func isExecFile(fi os.FileInfo) bool {
return fi.Mode().IsRegular() && fi.Mode()|0111 == fi.Mode()
}