diff --git a/internal/command/arguments/workspace.go b/internal/command/arguments/workspace.go index 8efbd00403..0864f1f2e7 100644 --- a/internal/command/arguments/workspace.go +++ b/internal/command/arguments/workspace.go @@ -32,6 +32,18 @@ func ParseWorkspace(args []string) (*Workspace, tfdiags.Diagnostics) { )) } + // There should not be any non-flag arguments for the workspace list command. + // In future when other workspace subcommands start using the arguments package + // this code will need to change. + args = cmdFlags.Args() + if len(args) != 0 { + diags = diags.Append(tfdiags.Sourceless( + tfdiags.Error, + "Too many command line arguments", + "Expected no positional arguments.", + )) + } + switch { case jsonOutput: return &Workspace{ViewType: ViewJSON}, diags diff --git a/internal/command/arguments/workspace_test.go b/internal/command/arguments/workspace_test.go new file mode 100644 index 0000000000..cb77f15ece --- /dev/null +++ b/internal/command/arguments/workspace_test.go @@ -0,0 +1,87 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: BUSL-1.1 + +package arguments + +import ( + "testing" + + "github.com/hashicorp/terraform/internal/tfdiags" +) + +func TestParseWorkspace_valid(t *testing.T) { + testCases := map[string]struct { + args []string + want *Workspace + }{ + "defaults": { + nil, + &Workspace{ + ViewType: ViewHuman, + }, + }, + "json": { + []string{"-json"}, + &Workspace{ + ViewType: ViewJSON, + }, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + got, diags := ParseWorkspace(tc.args) + if len(diags) > 0 { + t.Fatalf("unexpected diags: %v", diags) + } + if *got != *tc.want { + t.Fatalf("unexpected result\n got: %#v\nwant: %#v", got, tc.want) + } + }) + } +} + +func TestParseWorkspace_invalid(t *testing.T) { + testCases := map[string]struct { + args []string + want *Workspace + wantDiags tfdiags.Diagnostics + }{ + "unknown flag": { + []string{"-boop"}, + &Workspace{ + ViewType: ViewHuman, + }, + tfdiags.Diagnostics{ + tfdiags.Sourceless( + tfdiags.Error, + "Failed to parse command-line flags", + "flag provided but not defined: -boop", + ), + }, + }, + "too many arguments": { + []string{"-json", "bar", "baz"}, + &Workspace{ + ViewType: ViewJSON, + }, + tfdiags.Diagnostics{ + tfdiags.Sourceless( + tfdiags.Error, + "Too many command line arguments", + "Expected no positional arguments.", + ), + }, + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + got, gotDiags := ParseWorkspace(tc.args) + if *got != *tc.want { + t.Fatalf("unexpected result\n got: %#v\nwant: %#v", got, tc.want) + } + tfdiags.AssertDiagnosticsMatch(t, gotDiags, tc.wantDiags) + }) + } +}