Skip to content

Commit

Permalink
New Terraform Workspace select flag:
Browse files Browse the repository at this point in the history
  • Loading branch information
brittandeyoung committed Aug 31, 2022
1 parent 2aff678 commit 5932540
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
28 changes: 28 additions & 0 deletions internal/command/workspace_command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -435,3 +435,31 @@ func TestWorkspace_deleteWithState(t *testing.T) {
t.Fatal("env 'test' still exists!")
}
}

func TestWorkspace_selectWithOrCreate(t *testing.T) {
// Create a temporary working directory that is empty
td := t.TempDir()
os.MkdirAll(td, 0755)
defer testChdir(t, td)()

selectCmd := &WorkspaceSelectCommand{}

current, _ := selectCmd.Workspace()
if current != backend.DefaultStateName {
t.Fatal("current workspace should be 'default'")
}

args := []string{"-or-create", "test"}
ui := new(cli.MockUi)
view, _ := testView(t)
selectCmd.Meta = Meta{Ui: ui, View: view}
if code := selectCmd.Run(args); code != 0 {
t.Fatalf("bad: %d\n\n%s", code, ui.ErrorWriter)
}

current, _ = selectCmd.Workspace()
if current != "test" {
t.Fatalf("current workspace should be 'test', got %q", current)
}

}
14 changes: 12 additions & 2 deletions internal/command/workspace_select.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ func (c *WorkspaceSelectCommand) Run(args []string) int {
args = c.Meta.process(args)
envCommandShowWarning(c.Ui, c.LegacyName)

var orCreate bool
cmdFlags := c.Meta.defaultFlagSet("workspace select")
cmdFlags.BoolVar(&orCreate, "or-create", false, "create workspace if it doesnt exist")
cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
Expand Down Expand Up @@ -96,8 +98,16 @@ func (c *WorkspaceSelectCommand) Run(args []string) int {
}

if !found {
c.Ui.Error(fmt.Sprintf(envDoesNotExist, name))
return 1
if orCreate {
_, err = b.StateMgr(name)
if err != nil {
c.Ui.Error(err.Error())
return 1
}
} else {
c.Ui.Error(fmt.Sprintf(envDoesNotExist, name))
return 1
}
}

err = c.SetWorkspace(name)
Expand Down

0 comments on commit 5932540

Please sign in to comment.