github.com/chenbh/concourse/v6@v6.4.2/fly/commands/trigger_job.go (about)

     1  package commands
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"os/signal"
     7  	"syscall"
     8  
     9  	"github.com/chenbh/concourse/v6/atc"
    10  	"github.com/chenbh/concourse/v6/fly/commands/internal/flaghelpers"
    11  	"github.com/chenbh/concourse/v6/fly/eventstream"
    12  	"github.com/chenbh/concourse/v6/fly/rc"
    13  	"github.com/chenbh/concourse/v6/fly/ui"
    14  	"github.com/chenbh/concourse/v6/go-concourse/concourse"
    15  )
    16  
    17  type TriggerJobCommand struct {
    18  	Job   flaghelpers.JobFlag `short:"j" long:"job" required:"true" value-name:"PIPELINE/JOB" description:"Name of a job to trigger"`
    19  	Watch bool                `short:"w" long:"watch" description:"Start watching the build output"`
    20  	Team  string              `long:"team" description:"Name of the team to which the job belongs, if different from the target default"`
    21  }
    22  
    23  func (command *TriggerJobCommand) Execute(args []string) error {
    24  	pipelineName, jobName := command.Job.PipelineName, command.Job.JobName
    25  
    26  	target, err := rc.LoadTarget(Fly.Target, Fly.Verbose)
    27  	if err != nil {
    28  		return err
    29  	}
    30  
    31  	err = target.Validate()
    32  	if err != nil {
    33  		return err
    34  	}
    35  
    36  	var (
    37  		build atc.Build
    38  		team  concourse.Team
    39  	)
    40  	if command.Team != "" {
    41  		team, err = target.FindTeam(command.Team)
    42  		if err != nil {
    43  			return err
    44  		}
    45  	} else {
    46  		team = target.Team()
    47  	}
    48  
    49  	build, err = team.CreateJobBuild(pipelineName, jobName)
    50  	if err != nil {
    51  		return err
    52  	} else {
    53  		fmt.Printf("started %s/%s #%s\n", pipelineName, jobName, build.Name)
    54  	}
    55  
    56  	if command.Watch {
    57  		terminate := make(chan os.Signal, 1)
    58  
    59  		go func(terminate <-chan os.Signal) {
    60  			<-terminate
    61  			fmt.Fprintf(ui.Stderr, "\ndetached, build is still running...\n")
    62  			fmt.Fprintf(ui.Stderr, "re-attach to it with:\n\n")
    63  			fmt.Fprintf(ui.Stderr, "    "+ui.Embolden(fmt.Sprintf("fly -t %s watch -j %s/%s -b %s\n\n", Fly.Target, pipelineName, jobName, build.Name)))
    64  			os.Exit(2)
    65  		}(terminate)
    66  
    67  		signal.Notify(terminate, syscall.SIGINT, syscall.SIGTERM)
    68  
    69  		fmt.Println("")
    70  		eventSource, err := target.Client().BuildEvents(fmt.Sprintf("%d", build.ID))
    71  		if err != nil {
    72  			return err
    73  		}
    74  
    75  		renderOptions := eventstream.RenderOptions{}
    76  
    77  		exitCode := eventstream.Render(os.Stdout, eventSource, renderOptions)
    78  
    79  		eventSource.Close()
    80  
    81  		os.Exit(exitCode)
    82  	}
    83  
    84  	return nil
    85  }