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

     1  package commands
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"github.com/chenbh/concourse/v6/atc"
     7  	"github.com/chenbh/concourse/v6/fly/commands/internal/displayhelpers"
     8  	"github.com/chenbh/concourse/v6/fly/commands/internal/flaghelpers"
     9  	"github.com/chenbh/concourse/v6/fly/rc"
    10  )
    11  
    12  type PinResourceCommand struct {
    13  	Resource flaghelpers.ResourceFlag `short:"r" long:"resource" required:"true" value-name:"PIPELINE/RESOURCE" description:"Name of the resource"`
    14  	Version  *atc.Version             `short:"v" long:"version" description:"Version of the resource to pin. The given key value pair(s) has to be an exact match but not all fields are needed. In the case of multiple resource versions matched, it will pin the latest one."`
    15  	Comment  string                   `short:"c" long:"comment" description:"Message to be saved to the pinned resource. Resource has to be pinned otherwise --version should be specified to pin the resource first."`
    16  }
    17  
    18  func (command *PinResourceCommand) Execute([]string) error {
    19  	target, err := rc.LoadTarget(Fly.Target, Fly.Verbose)
    20  	if err != nil {
    21  		return err
    22  	}
    23  
    24  	err = target.Validate()
    25  	if err != nil {
    26  		return err
    27  	}
    28  
    29  	team := target.Team()
    30  
    31  	if command.Version != nil {
    32  		latestResourceVersion, err := GetLatestResourceVersion(team, command.Resource, *command.Version)
    33  		if err != nil {
    34  			return err
    35  		}
    36  
    37  		pinned, err := team.PinResourceVersion(command.Resource.PipelineName, command.Resource.ResourceName, latestResourceVersion.ID)
    38  
    39  		if err != nil {
    40  			return err
    41  		}
    42  
    43  		if pinned {
    44  			versionBytes, err := json.Marshal(latestResourceVersion.Version)
    45  			if err != nil {
    46  				return err
    47  			}
    48  
    49  			fmt.Printf("pinned '%s/%s' with version %s\n", command.Resource.PipelineName, command.Resource.ResourceName, string(versionBytes))
    50  		} else {
    51  			displayhelpers.Failf("could not pin '%s/%s', make sure the resource exists\n", command.Resource.PipelineName, command.Resource.ResourceName)
    52  		}
    53  	}
    54  
    55  	if command.Comment != "" {
    56  		saved, err := team.SetPinComment(command.Resource.PipelineName, command.Resource.ResourceName, command.Comment)
    57  
    58  		if err != nil {
    59  			return err
    60  		}
    61  
    62  		if saved {
    63  			fmt.Printf("pin comment '%s' is saved\n", command.Comment)
    64  		} else {
    65  			displayhelpers.Failf("could not save comment, make sure '%s/%s' is pinned\n", command.Resource.PipelineName, command.Resource.ResourceName)
    66  		}
    67  	}
    68  
    69  	return nil
    70  }