From 08bdfa9a0e93b953de6872ec95cea7ac0b81c360 Mon Sep 17 00:00:00 2001 From: Lorna Song Date: Mon, 31 Aug 2020 21:45:35 -0400 Subject: [PATCH] Add parsing for workspace already exists error When calling `terraform workspace new ` to create a workspace that already exists, an error is returned. --- tfexec/errors.go | 16 ++++++++++++++ tfexec/internal/e2etest/workspace_test.go | 26 +++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/tfexec/errors.go b/tfexec/errors.go index 1a14fa10..f4010985 100644 --- a/tfexec/errors.go +++ b/tfexec/errors.go @@ -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 { @@ -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) } @@ -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) +} diff --git a/tfexec/internal/e2etest/workspace_test.go b/tfexec/internal/e2etest/workspace_test.go index d358ffad..d5ff3b6c 100644 --- a/tfexec/internal/e2etest/workspace_test.go +++ b/tfexec/internal/e2etest/workspace_test.go @@ -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")