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

     1  package job
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"os"
     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  	"github.com/dnephin/dobi/tasks/types"
    14  )
    15  
    16  func newCaptureTask(variable string) types.TaskBuilder {
    17  	return func(name task.Name, conf config.Resource) types.Task {
    18  		buffer := bytes.NewBufferString("")
    19  		return &captureTask{
    20  			runTask: &Task{
    21  				name:      name,
    22  				config:    conf.(*config.JobConfig),
    23  				outStream: buffer,
    24  			},
    25  			variable: variable,
    26  			buffer:   buffer,
    27  		}
    28  	}
    29  }
    30  
    31  type captureTask struct {
    32  	types.NoStop
    33  	runTask  *Task
    34  	variable string
    35  	buffer   *bytes.Buffer
    36  }
    37  
    38  // Name returns the name of the task
    39  func (t *captureTask) Name() task.Name {
    40  	return t.runTask.name
    41  }
    42  
    43  // Repr formats the task for logging
    44  func (t *captureTask) Repr() string {
    45  	return fmt.Sprintf("%s capture %s", t.runTask.name.Format("job"), t.variable)
    46  }
    47  
    48  // Run the job to capture the output in a variable
    49  func (t *captureTask) Run(ctx *context.ExecuteContext, depsModified bool) (bool, error) {
    50  	modified, err := t.runTask.Run(ctx, depsModified)
    51  	if err != nil {
    52  		return modified, err
    53  	}
    54  
    55  	out := strings.TrimSpace(t.buffer.String())
    56  	if current, ok := os.LookupEnv(t.variable); ok && current == out {
    57  		return false, nil
    58  	}
    59  
    60  	logging.ForTask(t).Debugf("Setting %q to: %s", t.variable, out)
    61  	return true, os.Setenv(t.variable, out)
    62  }