forked from progrium/pluginhook
/
pluginhook.go
55 lines (53 loc) · 1.17 KB
/
pluginhook.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
package main
import (
"os"
"fmt"
"os/exec"
"syscall"
"path/filepath"
"log"
"code.google.com/p/go.crypto/ssh/terminal"
)
func main() {
pluginPath := os.Getenv("PLUGIN_PATH")
if pluginPath == "" {
log.Fatal("[ERROR] Unable to locate plugins: set $PLUGIN_PATH\n")
os.Exit(1)
}
if len(os.Args) < 2 {
log.Fatal("[ERROR] Hook name argument is required\n")
os.Exit(1)
}
cmds := make([]exec.Cmd, 0)
var matches, _ = filepath.Glob(fmt.Sprintf("%s/*/%s", pluginPath, os.Args[1]))
for _, hook := range matches {
cmd := exec.Command(hook, os.Args[2:]...)
cmds = append(cmds, *cmd)
}
done := make(chan bool, len(cmds))
for i := len(cmds)-1; i >= 0; i-- {
if i == len(cmds)-1 {
cmds[i].Stdout = os.Stdout
}
if i > 0 {
stdout, err := cmds[i-1].StdoutPipe()
if err != nil {
log.Fatal(err)
}
cmds[i].Stdin = stdout
}
if i == 0 && !terminal.IsTerminal(syscall.Stdin) {
cmds[i].Stdin = os.Stdin
}
go func(cmd exec.Cmd) {
err := cmd.Run()
if msg, ok := err.(*exec.ExitError); ok { // there is error code
os.Exit(msg.Sys().(syscall.WaitStatus).ExitStatus())
}
done <- true
}(cmds[i])
}
for i := 0; i < len(cmds); i++ {
<-done
}
}