-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoci.go
123 lines (98 loc) · 2.33 KB
/
goci.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
package main
import (
log "github.com/sirupsen/logrus"
"os"
"io/ioutil"
"gopkg.in/urfave/cli.v1"
"gopkg.in/yaml.v2"
"text/template"
"github.com/darrenmce/goci/docker"
)
func check(e error) {
if e != nil {
log.WithError(e).Panic("Fatal Error!")
}
}
func main() {
app := cli.NewApp()
app.Name = "GoCI"
app.Usage = "run some stuff in docker"
app.Description = "A simple CI job runner"
flags := []cli.Flag{
cli.StringFlag{
Name: "buildId, b",
Usage: "Build ID/Number",
},
cli.StringFlag{
Name: "instructions, i",
Usage: "path to YAML instructions",
},
}
app.Flags = flags
app.Action = runner
err := app.Run(os.Args)
check(err)
}
func runner(c *cli.Context) {
instructionFile := c.String("instructions")
buildId := c.String("buildId")
yamlData, err := ioutil.ReadFile(instructionFile)
check(err)
run := JobRun{BuildId: buildId}
err = yaml.Unmarshal([]byte(yamlData), &run)
check(err)
job := run.Job
run.WorkDir = getWorkDir(job.Name)
tmpl, err := getJobRunTemplate()
check(err)
tmpl.Execute(log.StandardLogger().Writer(), run)
err = checkout(job.Git.Repo, run.WorkDir, log.StandardLogger())
check(err)
dkr, err := docker.NewContainerRunner("1.36")
check(err)
buildStatusCode, err := run.RunBuild(dkr, buildId)
check(err)
if buildStatusCode != 0 {
log.Error("DOH!")
}
}
func (run JobRun) RunBuild (dkr docker.ContainerRunner, buildId string) (int, error) {
exitCode := 0
job := run.Job
buildContainer := docker.BuildContainer{
Name: job.Name,
Image: job.Build.Image,
Volumes: []docker.BuildVolume{ {run.WorkDir,"/build"} },
WorkDir: "/build",
BuildId: buildId,
}
for _, step := range job.Build.Steps {
statusCode, err := dkr.RunContainer(buildContainer, step)
if err != nil {
return statusCode, err
}
log.WithFields(log.Fields{
"statusCode": statusCode,
}).Info("CONTAINER exited")
if statusCode != 0 {
exitCode = statusCode
break
}
}
return exitCode, nil
}
func getJobRunTemplate() (*template.Template, error) {
jobTemplate, err := template.New("JobTemplate").Parse(
"Running Job (Build ID: {{.BuildId}})\n" +
"Name: {{.Job.Name}}\n" +
"Repo: {{.Job.Git.Repo}}\n" +
"Working Directory: {{.WorkDir}}",
)
check(err)
return jobTemplate, err
}
func getWorkDir(name string) (dir string) {
dir, err := ioutil.TempDir("", name)
check(err)
return dir
}