github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/cmd/juju/space/rename.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package space
     5  
     6  import (
     7  	"strings"
     8  
     9  	"github.com/juju/cmd"
    10  	"github.com/juju/errors"
    11  	"github.com/juju/gnuflag"
    12  	"gopkg.in/juju/names.v2"
    13  
    14  	"github.com/juju/juju/cmd/modelcmd"
    15  )
    16  
    17  // NewRenameCommand returns a command used to rename an existing space.
    18  func NewRenameCommand() cmd.Command {
    19  	return modelcmd.Wrap(&renameCommand{})
    20  }
    21  
    22  // renameCommand calls the API to rename an existing network space.
    23  type renameCommand struct {
    24  	SpaceCommandBase
    25  	Name    string
    26  	NewName string
    27  }
    28  
    29  const renameCommandDoc = `
    30  Renames an existing space from "old-name" to "new-name". Does not change the
    31  associated subnets and "new-name" must not match another existing space.
    32  `
    33  
    34  func (c *renameCommand) SetFlags(f *gnuflag.FlagSet) {
    35  	c.SpaceCommandBase.SetFlags(f)
    36  	f.StringVar(&c.NewName, "rename", "", "the new name for the network space")
    37  }
    38  
    39  // Info is defined on the cmd.Command interface.
    40  func (c *renameCommand) Info() *cmd.Info {
    41  	return &cmd.Info{
    42  		Name:    "rename-space",
    43  		Args:    "<old-name> <new-name>",
    44  		Purpose: "Rename a network space",
    45  		Doc:     strings.TrimSpace(renameCommandDoc),
    46  	}
    47  }
    48  
    49  // Init is defined on the cmd.Command interface. It checks the
    50  // arguments for sanity and sets up the command to run.
    51  func (c *renameCommand) Init(args []string) (err error) {
    52  	defer errors.DeferredAnnotatef(&err, "invalid arguments specified")
    53  
    54  	switch len(args) {
    55  	case 0:
    56  		return errors.New("old-name is required")
    57  	case 1:
    58  		return errors.New("new-name is required")
    59  	}
    60  	for _, name := range args {
    61  		if !names.IsValidSpace(name) {
    62  			return errors.Errorf("%q is not a valid space name", name)
    63  		}
    64  	}
    65  	c.Name = args[0]
    66  	c.NewName = args[1]
    67  
    68  	if c.Name == c.NewName {
    69  		return errors.New("old-name and new-name are the same")
    70  	}
    71  
    72  	return cmd.CheckEmpty(args[2:])
    73  }
    74  
    75  // Run implements Command.Run.
    76  func (c *renameCommand) Run(ctx *cmd.Context) error {
    77  	return c.RunWithAPI(ctx, func(api SpaceAPI, ctx *cmd.Context) error {
    78  		err := api.RenameSpace(c.Name, c.NewName)
    79  		if err != nil {
    80  			return errors.Annotatef(err, "cannot rename space %q", c.Name)
    81  		}
    82  
    83  		ctx.Infof("renamed space %q to %q", c.Name, c.NewName)
    84  		return nil
    85  	})
    86  }