forked from imjerrybao/apex
/
hooks.go
74 lines (59 loc) · 1.41 KB
/
hooks.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
// Package hooks implements hook script support.
package hooks
import (
"fmt"
"os"
"os/exec"
"github.com/apex/log"
"github.com/jpillora/archive"
"github.com/apex/apex/function"
)
func init() {
function.RegisterPlugin("hooks", &Plugin{})
}
// HookError represents a failed hook command.
type HookError struct {
Hook string
Command string
Output string
}
// Error string.
func (e *HookError) Error() string {
return fmt.Sprintf("%s hook: %s", e.Hook, e.Output)
}
// Plugin implementation.
type Plugin struct{}
// Build runs the "build" hook commands.
func (p *Plugin) Build(fn *function.Function, zip *archive.Archive) error {
return p.run("build", fn.Hooks.Build, fn)
}
// Clean runs the "clean" hook commands.
func (p *Plugin) Clean(fn *function.Function) error {
return p.run("clean", fn.Hooks.Clean, fn)
}
// Deploy runs the "deploy" hook commands.
func (p *Plugin) Deploy(fn *function.Function) error {
return p.run("deploy", fn.Hooks.Deploy, fn)
}
// run a hook command.
func (p *Plugin) run(hook, command string, fn *function.Function) error {
if command == "" {
return nil
}
fn.Log.WithFields(log.Fields{
"hook": hook,
"command": command,
}).Debug("hook")
cmd := exec.Command("sh", "-c", command)
cmd.Env = os.Environ()
cmd.Dir = fn.Path
b, err := cmd.CombinedOutput()
if err != nil {
return &HookError{
Hook: hook,
Command: command,
Output: string(b),
}
}
return nil
}