forked from adampointer/cali
-
Notifications
You must be signed in to change notification settings - Fork 7
/
task.go
93 lines (80 loc) · 2.45 KB
/
task.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
package cali
import (
"fmt"
"os/user"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
)
// TaskFunc is a function executed by a Task when the command the Task belongs to is run
type TaskFunc func(t *Task, args []string)
// defaultTaskFunc is the TaskFunc which is executed unless a custom TaskFunc is
// attached to the Task
var defaultTaskFunc TaskFunc = func(t *Task, args []string) {
if err := t.SetDefaults(args); err != nil {
log.Fatalf("Error setting container defaults: %s", err)
}
if _, err := t.StartContainer(true, ""); err != nil {
log.Fatalf("Error executing task: %s", err)
}
}
// Task is the action performed when it's parent command is run
type Task struct {
f, init TaskFunc
*DockerClient
}
// SetFunc sets the TaskFunc which is run when the parent command is run
// if this is left unset, the defaultTaskFunc will be executed instead
func (t *Task) SetFunc(f TaskFunc) {
t.f = f
}
// SetInitFunc sets the TaskFunc which is executed before the main TaskFunc. It's
// pupose is to do any setup of the DockerClient which depends on command line args
// for example
func (t *Task) SetInitFunc(f TaskFunc) {
t.init = f
}
// SetDefaults sets the default host config for a task container
// Mounts the PWD to /tmp/workspace (Unless task WorkingDir config is set)
// Mounts your ~/.aws directory to /root - change this if your image runs as a non-root user
// Sets /tmp/workspace as the workdir
// Configures git
func (t *Task) SetDefaults(args []string) error {
if len(t.Conf.WorkingDir) == 0 {
t.SetWorkDir(workdir)
}
err := t.BindFromGit(gitCfg, func() error {
pwd, err := t.Bind("./", workdir)
if err != nil {
return err
}
t.AddBinds([]string{pwd})
return nil
})
if err != nil {
return err
}
t.SetCmd(args)
return nil
}
// Bind is a utility function which will return the correctly formatted string when given a source
// and destination directory
//
// The ~ symbol and relative paths will be correctly expanded depending on the host OS
func (t *Task) Bind(src, dst string) (string, error) {
var expanded string
if strings.HasPrefix(src, "~") {
usr, err := user.Current()
if err != nil {
return expanded, fmt.Errorf("Error expanding bind path: %s", err)
}
expanded = filepath.Join(usr.HomeDir, src[2:])
} else {
expanded = src
}
expanded, err := filepath.Abs(expanded)
if err != nil {
return expanded, fmt.Errorf("Error expanding bind path: %s", err)
}
return fmt.Sprintf("%s:%s", expanded, dst), nil
}