feat: Detect unexpected arguments and flags using the arguments package.

This commit is contained in:
Sarah French 2026-04-08 15:03:18 +01:00
parent cf622b13d7
commit f61324a3e3
2 changed files with 99 additions and 0 deletions

View file

@ -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

View file

@ -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)
})
}
}