github.com/dnephin/dobi@v0.15.0/tasks/compose/compose.go (about)

     1  package compose
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/exec"
     7  	"strings"
     8  
     9  	"github.com/dnephin/dobi/config"
    10  	"github.com/dnephin/dobi/logging"
    11  	"github.com/dnephin/dobi/tasks/context"
    12  	"github.com/dnephin/dobi/tasks/task"
    13  	log "github.com/sirupsen/logrus"
    14  )
    15  
    16  // Task runs a Docker Compose project
    17  type Task struct {
    18  	name   task.Name
    19  	config *config.ComposeConfig
    20  	run    actionFunc
    21  	stop   actionFunc
    22  }
    23  
    24  // Name returns the name of the task
    25  func (t *Task) Name() task.Name {
    26  	return t.name
    27  }
    28  
    29  func (t *Task) logger() *log.Entry {
    30  	return logging.ForTask(t)
    31  }
    32  
    33  // Repr formats the task for logging
    34  func (t *Task) Repr() string {
    35  	return fmt.Sprintf("[compose:%s %s] %s",
    36  		t.name.Action(), t.name.Resource(), strings.Join(t.config.Files, ","))
    37  }
    38  
    39  // Run runs the action
    40  func (t *Task) Run(ctx *context.ExecuteContext, _ bool) (bool, error) {
    41  	return false, t.run(ctx, t)
    42  }
    43  
    44  // Stop the task
    45  func (t *Task) Stop(ctx *context.ExecuteContext) error {
    46  	t.logger().Debug("Stop")
    47  	return t.stop(ctx, t)
    48  }
    49  
    50  // StopNothing implements the Stop interface but does nothing
    51  func StopNothing(_ *context.ExecuteContext, _ *Task) error {
    52  	return nil
    53  }
    54  
    55  func buildCommandArgs(conf *config.ComposeConfig) []string {
    56  	args := []string{}
    57  	for _, filename := range conf.Files {
    58  		args = append(args, "-f", filename)
    59  	}
    60  	return append(args, "-p", conf.Project)
    61  }
    62  
    63  func (t *Task) execCompose(args ...string) error {
    64  	if err := t.buildCommand(args...).Run(); err != nil {
    65  		return err
    66  	}
    67  	t.logger().Info("Done")
    68  	return nil
    69  }
    70  
    71  func (t *Task) buildCommand(args ...string) *exec.Cmd {
    72  	args = append(buildCommandArgs(t.config), args...)
    73  	cmd := exec.Command("docker-compose", args...)
    74  	t.logger().Debugf("Args: %s", args)
    75  	cmd.Stdout = os.Stdout
    76  	cmd.Stderr = os.Stderr
    77  	return cmd
    78  }