github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/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/names"
    12  	"launchpad.net/gnuflag"
    13  )
    14  
    15  // RenameCommand calls the API to rename an existing network space.
    16  type RenameCommand struct {
    17  	SpaceCommandBase
    18  	Name    string
    19  	NewName string
    20  }
    21  
    22  const RenameCommandDoc = `
    23  Renames an existing space from "old-name" to "new-name". Does not change the
    24  associated subnets and "new-name" must not match another existing space.
    25  `
    26  
    27  func (c *RenameCommand) SetFlags(f *gnuflag.FlagSet) {
    28  	c.SpaceCommandBase.SetFlags(f)
    29  	f.StringVar(&c.NewName, "rename", "", "the new name for the network space")
    30  }
    31  
    32  // Info is defined on the cmd.Command interface.
    33  func (c *RenameCommand) Info() *cmd.Info {
    34  	return &cmd.Info{
    35  		Name:    "rename",
    36  		Args:    "<old-name> <new-name>",
    37  		Purpose: "rename a network space",
    38  		Doc:     strings.TrimSpace(RenameCommandDoc),
    39  	}
    40  }
    41  
    42  // Init is defined on the cmd.Command interface. It checks the
    43  // arguments for sanity and sets up the command to run.
    44  func (c *RenameCommand) Init(args []string) (err error) {
    45  	defer errors.DeferredAnnotatef(&err, "invalid arguments specified")
    46  
    47  	switch len(args) {
    48  	case 0:
    49  		return errors.New("old-name is required")
    50  	case 1:
    51  		return errors.New("new-name is required")
    52  	}
    53  	for _, name := range args {
    54  		if !names.IsValidSpace(name) {
    55  			return errors.Errorf("%q is not a valid space name", name)
    56  		}
    57  	}
    58  	c.Name = args[0]
    59  	c.NewName = args[1]
    60  
    61  	if c.Name == c.NewName {
    62  		return errors.New("old-name and new-name are the same")
    63  	}
    64  
    65  	return cmd.CheckEmpty(args[2:])
    66  }
    67  
    68  // Run implements Command.Run.
    69  func (c *RenameCommand) Run(ctx *cmd.Context) error {
    70  	return c.RunWithAPI(ctx, func(api SpaceAPI, ctx *cmd.Context) error {
    71  		err := api.RenameSpace(c.Name, c.NewName)
    72  		if err != nil {
    73  			return errors.Annotatef(err, "cannot rename space %q", c.Name)
    74  		}
    75  
    76  		ctx.Infof("renamed space %q to %q", c.Name, c.NewName)
    77  		return nil
    78  	})
    79  }