github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/cmd/juju/backups/list.go (about)

     1  // Copyright 2014 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package backups
     5  
     6  import (
     7  	"fmt"
     8  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"github.com/juju/gnuflag"
    12  
    13  	jujucmd "github.com/juju/juju/cmd"
    14  	"github.com/juju/juju/cmd/modelcmd"
    15  )
    16  
    17  const listDoc = `
    18  backups provides the metadata associated with all backups.
    19  `
    20  
    21  // NewListCommand returns a command used to list metadata for backups.
    22  func NewListCommand() cmd.Command {
    23  	return modelcmd.Wrap(&listCommand{})
    24  }
    25  
    26  // listCommand is the sub-command for listing all available backups.
    27  type listCommand struct {
    28  	CommandBase
    29  }
    30  
    31  // Info implements Command.Info.
    32  func (c *listCommand) Info() *cmd.Info {
    33  	return jujucmd.Info(&cmd.Info{
    34  		Name:    "backups",
    35  		Args:    "",
    36  		Purpose: "Displays information about all backups.",
    37  		Doc:     listDoc,
    38  		Aliases: []string{"list-backups"},
    39  	})
    40  }
    41  
    42  // SetFlags implements Command.SetFlags.
    43  func (c *listCommand) SetFlags(f *gnuflag.FlagSet) {
    44  	c.CommandBase.SetFlags(f)
    45  }
    46  
    47  // Init implements Command.Init.
    48  func (c *listCommand) Init(args []string) error {
    49  	if err := cmd.CheckEmpty(args); err != nil {
    50  		return errors.Trace(err)
    51  	}
    52  	return nil
    53  }
    54  
    55  // Run implements Command.Run.
    56  func (c *listCommand) Run(ctx *cmd.Context) error {
    57  	if c.Log != nil {
    58  		if err := c.Log.Start(ctx); err != nil {
    59  			return err
    60  		}
    61  	}
    62  	client, err := c.NewAPIClient()
    63  	if err != nil {
    64  		return errors.Trace(err)
    65  	}
    66  	defer client.Close()
    67  
    68  	result, err := client.List()
    69  	if err != nil {
    70  		return errors.Trace(err)
    71  	}
    72  
    73  	if len(result.List) == 0 {
    74  		ctx.Infof("No backups to display.")
    75  		return nil
    76  	}
    77  
    78  	verbose := c.Log != nil && c.Log.Verbose
    79  	if verbose {
    80  		c.dumpMetadata(ctx, &result.List[0])
    81  	} else {
    82  		fmt.Fprintln(ctx.Stdout, result.List[0].ID)
    83  	}
    84  	for _, resultItem := range result.List[1:] {
    85  		if verbose {
    86  			fmt.Fprintln(ctx.Stdout)
    87  			c.dumpMetadata(ctx, &resultItem)
    88  		} else {
    89  			fmt.Fprintln(ctx.Stdout, resultItem.ID)
    90  		}
    91  	}
    92  	return nil
    93  }