Skip to content

Commit

Permalink
Add parsing for workspace already exists error
Browse files Browse the repository at this point in the history
When calling `terraform workspace new <name>` to create a workspace that already exists, an error is returned.
  • Loading branch information
lornasong authored and paultyng committed Sep 1, 2020
1 parent 05e87e9 commit 769254b
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
16 changes: 16 additions & 0 deletions tfexec/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ var (
noConfigErrRegexp = regexp.MustCompile(`Error: No configuration files`)

workspaceDoesNotExistRegexp = regexp.MustCompile(`Workspace "(.+)" doesn't exist.`)

workspaceAlreadyExistsRegexp = regexp.MustCompile(`Workspace "(.+)" already exists`)
)

func parseError(err error, stderr string) error {
Expand Down Expand Up @@ -51,6 +53,11 @@ func parseError(err error, stderr string) error {
if len(submatches) == 2 {
return &ErrNoWorkspace{submatches[1]}
}
case workspaceAlreadyExistsRegexp.MatchString(stderr):
submatches := workspaceAlreadyExistsRegexp.FindStringSubmatch(stderr)
if len(submatches) == 2 {
return &ErrWorkspaceExists{submatches[1]}
}
}
return errors.New(stderr)
}
Expand Down Expand Up @@ -132,3 +139,12 @@ type ErrNoWorkspace struct {
func (err *ErrNoWorkspace) Error() string {
return fmt.Sprintf("workspace %q does not exist", err.Name)
}

// ErrWorkspaceExists is returned when creating a workspace that already exists
type ErrWorkspaceExists struct {
Name string
}

func (err *ErrWorkspaceExists) Error() string {
return fmt.Sprintf("workspace %q already exists", err.Name)
}
26 changes: 26 additions & 0 deletions tfexec/internal/e2etest/workspace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,32 @@ func TestWorkspace_does_not_exist(t *testing.T) {
})
}

func TestWorkspace_already_exists(t *testing.T) {
runTest(t, "basic", func(t *testing.T, tfv *version.Version, tf *tfexec.Terraform) {
const newWorkspace = "existing-workspace"
t.Run("create new workspace", func(t *testing.T) {
err := tf.WorkspaceNew(context.Background(), newWorkspace)
if err != nil {
t.Fatalf("got error creating new workspace: %s", err)
}

assertWorkspaceList(t, tf, newWorkspace, newWorkspace)
})

t.Run("create existing workspace", func(t *testing.T) {
err := tf.WorkspaceNew(context.Background(), newWorkspace)

var wsErr *tfexec.ErrWorkspaceExists
if !errors.As(err, &wsErr) {
t.Fatalf("expected ErrWorkspaceExists, %T returned: %s", err, err)
}
if wsErr.Name != newWorkspace {
t.Fatalf("expected %q, got %q", newWorkspace, wsErr.Name)
}
})
})
}

func TestWorkspace_multiple(t *testing.T) {
runTest(t, "workspaces", func(t *testing.T, tfv *version.Version, tf *tfexec.Terraform) {
assertWorkspaceList(t, tf, "foo", "foo")
Expand Down

0 comments on commit 769254b

Please sign in to comment.