github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/tls/custom/certificate/update.go (about)

     1  package certificate
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/fastly/go-fastly/v9/fastly"
     7  
     8  	"github.com/fastly/cli/pkg/argparser"
     9  	"github.com/fastly/cli/pkg/global"
    10  	"github.com/fastly/cli/pkg/text"
    11  )
    12  
    13  // NewUpdateCommand returns a usable command registered under the parent.
    14  func NewUpdateCommand(parent argparser.Registerer, g *global.Data) *UpdateCommand {
    15  	var c UpdateCommand
    16  	c.CmdClause = parent.Command("update", "Replace a TLS certificate with a newly reissued TLS certificate, or update a TLS certificate's name")
    17  	c.Globals = g
    18  
    19  	// Required.
    20  	c.CmdClause.Flag("cert-blob", "The PEM-formatted certificate blob").Required().StringVar(&c.certBlob)
    21  	c.CmdClause.Flag("id", "Alphanumeric string identifying a TLS certificate").Required().StringVar(&c.id)
    22  
    23  	// Optional.
    24  	c.CmdClause.Flag("name", "A customizable name for your certificate. Defaults to the certificate's Common Name or first Subject Alternative Names (SAN) entry").StringVar(&c.name)
    25  	return &c
    26  }
    27  
    28  // UpdateCommand calls the Fastly API to update an appropriate resource.
    29  type UpdateCommand struct {
    30  	argparser.Base
    31  
    32  	certBlob string
    33  	id       string
    34  	name     string
    35  }
    36  
    37  // Exec invokes the application logic for the command.
    38  func (c *UpdateCommand) Exec(_ io.Reader, out io.Writer) error {
    39  	input := c.constructInput()
    40  
    41  	r, err := c.Globals.APIClient.UpdateCustomTLSCertificate(input)
    42  	if err != nil {
    43  		c.Globals.ErrLog.AddWithContext(err, map[string]any{
    44  			"TLS Certificate ID":   c.id,
    45  			"TLS Certificate Name": c.name,
    46  		})
    47  		return err
    48  	}
    49  
    50  	if c.name != "" {
    51  		text.Success(out, "Updated TLS Certificate '%s' (previously: '%s')", r.Name, input.Name)
    52  	} else {
    53  		text.Success(out, "Updated TLS Certificate '%s'", r.ID)
    54  	}
    55  	return nil
    56  }
    57  
    58  // constructInput transforms values parsed from CLI flags into an object to be used by the API client library.
    59  func (c *UpdateCommand) constructInput() *fastly.UpdateCustomTLSCertificateInput {
    60  	var input fastly.UpdateCustomTLSCertificateInput
    61  
    62  	input.ID = c.id
    63  	input.CertBlob = c.certBlob
    64  
    65  	if c.name != "" {
    66  		input.Name = c.name
    67  	}
    68  
    69  	return &input
    70  }