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