github.com/fastly/cli@v1.7.2-0.20240304164155-9d0f1d77c3bf/pkg/commands/authtoken/describe.go (about)

     1  package authtoken
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"strings"
     7  
     8  	"github.com/fastly/go-fastly/v9/fastly"
     9  
    10  	"github.com/fastly/cli/pkg/argparser"
    11  	fsterr "github.com/fastly/cli/pkg/errors"
    12  	"github.com/fastly/cli/pkg/global"
    13  )
    14  
    15  // NewDescribeCommand returns a usable command registered under the parent.
    16  func NewDescribeCommand(parent argparser.Registerer, g *global.Data) *DescribeCommand {
    17  	c := DescribeCommand{
    18  		Base: argparser.Base{
    19  			Globals: g,
    20  		},
    21  	}
    22  	c.CmdClause = parent.Command("describe", "Get the current API token").Alias("get")
    23  
    24  	c.RegisterFlagBool(c.JSONFlag()) // --json
    25  	return &c
    26  }
    27  
    28  // DescribeCommand calls the Fastly API to describe an appropriate resource.
    29  type DescribeCommand struct {
    30  	argparser.Base
    31  	argparser.JSONOutput
    32  }
    33  
    34  // Exec invokes the application logic for the command.
    35  func (c *DescribeCommand) Exec(_ io.Reader, out io.Writer) error {
    36  	if c.Globals.Verbose() && c.JSONOutput.Enabled {
    37  		return fsterr.ErrInvalidVerboseJSONCombo
    38  	}
    39  
    40  	o, err := c.Globals.APIClient.GetTokenSelf()
    41  	if err != nil {
    42  		c.Globals.ErrLog.Add(err)
    43  		return err
    44  	}
    45  
    46  	if ok, err := c.WriteJSON(out, o); ok {
    47  		return err
    48  	}
    49  
    50  	return c.print(out, o)
    51  }
    52  
    53  // print displays the information returned from the API.
    54  func (c *DescribeCommand) print(out io.Writer, t *fastly.Token) error {
    55  	fmt.Fprintf(out, "\nID: %s\n", fastly.ToValue(t.TokenID))
    56  	fmt.Fprintf(out, "Name: %s\n", fastly.ToValue(t.Name))
    57  	fmt.Fprintf(out, "User ID: %s\n", fastly.ToValue(t.UserID))
    58  	fmt.Fprintf(out, "Services: %s\n", strings.Join(t.Services, ", "))
    59  	fmt.Fprintf(out, "Scope: %s\n", fastly.ToValue(t.Scope))
    60  	fmt.Fprintf(out, "IP: %s\n\n", fastly.ToValue(t.IP))
    61  
    62  	if t.CreatedAt != nil {
    63  		fmt.Fprintf(out, "Created at: %s\n", t.CreatedAt)
    64  	}
    65  	if t.LastUsedAt != nil {
    66  		fmt.Fprintf(out, "Last used at: %s\n", t.LastUsedAt)
    67  	}
    68  	if t.ExpiresAt != nil {
    69  		fmt.Fprintf(out, "Expires at: %s\n", t.ExpiresAt)
    70  	}
    71  	return nil
    72  }