github.com/paultyng/terraform@v0.6.11-0.20180227224804-66ff8f8bed40/command/workspace_select.go (about) 1 package command 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/mitchellh/cli" 8 "github.com/posener/complete" 9 ) 10 11 type WorkspaceSelectCommand struct { 12 Meta 13 LegacyName bool 14 } 15 16 func (c *WorkspaceSelectCommand) Run(args []string) int { 17 args, err := c.Meta.process(args, true) 18 if err != nil { 19 return 1 20 } 21 22 envCommandShowWarning(c.Ui, c.LegacyName) 23 24 cmdFlags := c.Meta.flagSet("workspace select") 25 cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } 26 if err := cmdFlags.Parse(args); err != nil { 27 return 1 28 } 29 args = cmdFlags.Args() 30 if len(args) == 0 { 31 c.Ui.Error("Expected a single argument: NAME.\n") 32 return cli.RunResultHelp 33 } 34 35 configPath, err := ModulePath(args[1:]) 36 if err != nil { 37 c.Ui.Error(err.Error()) 38 return 1 39 } 40 41 conf, err := c.Config(configPath) 42 if err != nil { 43 c.Ui.Error(fmt.Sprintf("Failed to load root config module: %s", err)) 44 } 45 46 current, isOverridden := c.WorkspaceOverridden() 47 if isOverridden { 48 c.Ui.Error(envIsOverriddenSelectError) 49 return 1 50 } 51 52 // Load the backend 53 b, err := c.Backend(&BackendOpts{ 54 Config: conf, 55 }) 56 57 if err != nil { 58 c.Ui.Error(fmt.Sprintf("Failed to load backend: %s", err)) 59 return 1 60 } 61 62 name := args[0] 63 if !validWorkspaceName(name) { 64 c.Ui.Error(fmt.Sprintf(envInvalidName, name)) 65 return 1 66 } 67 68 states, err := b.States() 69 if err != nil { 70 c.Ui.Error(err.Error()) 71 return 1 72 } 73 74 if name == current { 75 // already using this workspace 76 return 0 77 } 78 79 found := false 80 for _, s := range states { 81 if name == s { 82 found = true 83 break 84 } 85 } 86 87 if !found { 88 c.Ui.Error(fmt.Sprintf(envDoesNotExist, name)) 89 return 1 90 } 91 92 err = c.SetWorkspace(name) 93 if err != nil { 94 c.Ui.Error(err.Error()) 95 return 1 96 } 97 98 c.Ui.Output( 99 c.Colorize().Color( 100 fmt.Sprintf(envChanged, name), 101 ), 102 ) 103 104 return 0 105 } 106 107 func (c *WorkspaceSelectCommand) AutocompleteArgs() complete.Predictor { 108 return completePredictSequence{ 109 complete.PredictNothing, // the "select" subcommand itself (already matched) 110 c.completePredictWorkspaceName(), 111 complete.PredictDirs(""), 112 } 113 } 114 115 func (c *WorkspaceSelectCommand) AutocompleteFlags() complete.Flags { 116 return nil 117 } 118 119 func (c *WorkspaceSelectCommand) Help() string { 120 helpText := ` 121 Usage: terraform workspace select NAME [DIR] 122 123 Select a different Terraform workspace. 124 ` 125 return strings.TrimSpace(helpText) 126 } 127 128 func (c *WorkspaceSelectCommand) Synopsis() string { 129 return "Select a workspace" 130 }