github.com/dnephin/dobi@v0.15.0/tasks/compose/actions.go (about) 1 package compose 2 3 import ( 4 "fmt" 5 6 "github.com/dnephin/dobi/config" 7 "github.com/dnephin/dobi/tasks/context" 8 "github.com/dnephin/dobi/tasks/task" 9 "github.com/dnephin/dobi/tasks/types" 10 ) 11 12 // GetTaskConfig returns a new task for the action 13 func GetTaskConfig(name, action string, conf *config.ComposeConfig) (types.TaskConfig, error) { 14 act, err := getAction(action, name, conf) 15 if err != nil { 16 return nil, err 17 } 18 return types.NewTaskConfig(act.name, conf, act.deps, NewTask(act.Run, act.Stop)), nil 19 } 20 21 type actionFunc func(*context.ExecuteContext, *Task) error 22 23 type action struct { 24 name task.Name 25 Run actionFunc 26 Stop actionFunc 27 deps func() []string 28 } 29 30 func newAction( 31 name task.Name, 32 run actionFunc, 33 stop actionFunc, 34 deps func() []string, 35 ) (action, error) { 36 if stop == nil { 37 stop = StopNothing 38 } 39 return action{name: name, Run: run, Stop: stop, deps: deps}, nil 40 } 41 42 func getAction(name string, resname string, conf *config.ComposeConfig) (action, error) { 43 switch name { 44 case "", "up": 45 return newAction( 46 task.NewDefaultName(resname, "up"), RunUp, StopUp, deps(conf)) 47 case "remove", "rm", "down": 48 return newAction(task.NewName(resname, "down"), RunDown, nil, noDeps) 49 case "attach": 50 return newAction( 51 task.NewName(resname, "attach"), RunUpAttached, nil, deps(conf)) 52 case "detach": 53 return newAction( 54 task.NewDefaultName(resname, "detach"), RunUp, nil, deps(conf)) 55 default: 56 return action{}, fmt.Errorf("invalid compose action %q for task %q", name, resname) 57 } 58 } 59 60 // NewTask creates a new Task object 61 func NewTask(run actionFunc, stop actionFunc) func(task.Name, config.Resource) types.Task { 62 return func(name task.Name, res config.Resource) types.Task { 63 return &Task{ 64 name: name, 65 config: res.(*config.ComposeConfig), 66 run: run, 67 stop: stop, 68 } 69 } 70 } 71 72 // RunUp starts the Compose project 73 func RunUp(_ *context.ExecuteContext, t *Task) error { 74 t.logger().Info("project up") 75 return t.execCompose("up", "-d") 76 } 77 78 // StopUp stops the project 79 func StopUp(_ *context.ExecuteContext, t *Task) error { 80 t.logger().Info("project stop") 81 return t.execCompose("stop", "-t", t.config.StopGraceString()) 82 } 83 84 // RunDown removes all the project resources 85 func RunDown(_ *context.ExecuteContext, t *Task) error { 86 t.logger().Info("project down") 87 return t.execCompose("down") 88 } 89 90 func deps(conf *config.ComposeConfig) func() []string { 91 return func() []string { 92 return conf.Dependencies() 93 } 94 } 95 96 func noDeps() []string { 97 return []string{} 98 }