refactor state-pull command argument parsing

This commit is contained in:
Daniel Schmidt 2026-02-13 14:43:54 +01:00
parent acb6ed3f22
commit 52bbc57c62
No known key found for this signature in database
GPG key ID: 377C3A4D62FBBBE2
3 changed files with 99 additions and 4 deletions

View file

@ -0,0 +1,32 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package arguments
import (
"github.com/hashicorp/terraform/internal/tfdiags"
)
// StatePull represents the command-line arguments for the state pull command.
type StatePull struct {
}
// ParseStatePull processes CLI arguments, returning a StatePull value and
// diagnostics. If errors are encountered, a StatePull value is still returned
// representing the best effort interpretation of the arguments.
func ParseStatePull(args []string) (*StatePull, tfdiags.Diagnostics) {
var diags tfdiags.Diagnostics
pull := &StatePull{}
cmdFlags := defaultFlagSet("state pull")
if err := cmdFlags.Parse(args); err != nil {
diags = diags.Append(tfdiags.Sourceless(
tfdiags.Error,
"Failed to parse command-line flags",
err.Error(),
))
}
return pull, diags
}

View file

@ -0,0 +1,64 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package arguments
import (
"testing"
"github.com/hashicorp/terraform/internal/tfdiags"
)
func TestParseStatePull_valid(t *testing.T) {
testCases := map[string]struct {
args []string
want *StatePull
}{
"defaults": {
nil,
&StatePull{},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, diags := ParseStatePull(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 TestParseStatePull_invalid(t *testing.T) {
testCases := map[string]struct {
args []string
want *StatePull
wantDiags tfdiags.Diagnostics
}{
"unknown flag": {
[]string{"-boop"},
&StatePull{},
tfdiags.Diagnostics{
tfdiags.Sourceless(
tfdiags.Error,
"Failed to parse command-line flags",
"flag provided but not defined: -boop",
),
},
},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got, gotDiags := ParseStatePull(tc.args)
if *got != *tc.want {
t.Fatalf("unexpected result\n got: %#v\nwant: %#v", got, tc.want)
}
tfdiags.AssertDiagnosticsMatch(t, gotDiags, tc.wantDiags)
})
}
}

View file

@ -21,10 +21,9 @@ type StatePullCommand struct {
}
func (c *StatePullCommand) Run(args []string) int {
args = c.Meta.process(args)
cmdFlags := c.Meta.defaultFlagSet("state pull")
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
_, diags := arguments.ParseStatePull(c.Meta.process(args))
if diags.HasErrors() {
c.showDiagnostics(diags)
return 1
}