Merge pull request #25277 from hashicorp/alisdair/fix-terraform-version-version

command: Fix bug with -v/-version/--version flags
This commit is contained in:
Alisdair McDiarmid 2020-06-18 10:21:31 -04:00 committed by GitHub
commit c12ad38c5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 44 additions and 3 deletions

View File

@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"sort"
"strings"
)
// VersionCommand is a Command implementation prints the version.
@ -38,7 +39,16 @@ type VersionCheckInfo struct {
}
func (c *VersionCommand) Help() string {
return ""
helpText := `
Usage: terraform version [options]
Displays the version of Terraform and all installed plugins
Options:
-json Output the version information as a JSON object.
`
return strings.TrimSpace(helpText)
}
func (c *VersionCommand) Run(args []string) int {
@ -48,6 +58,13 @@ func (c *VersionCommand) Run(args []string) int {
var jsonOutput bool
cmdFlags := c.Meta.defaultFlagSet("version")
cmdFlags.BoolVar(&jsonOutput, "json", false, "json")
// Enable but ignore the global version flags. In main.go, if any of the
// arguments are -v, -version, or --version, this command will be called
// with the rest of the arguments, so we need to be able to cope with
// those.
cmdFlags.Bool("v", true, "version")
cmdFlags.Bool("version", true, "version")
cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
return 1

View File

@ -33,7 +33,7 @@ func TestVersion(t *testing.T) {
ProviderSource: providerSource,
}
// `terrafrom init`
// `terraform init`
ic := &InitCommand{
Meta: m,
}
@ -61,6 +61,30 @@ func TestVersion(t *testing.T) {
}
func TestVersion_flags(t *testing.T) {
ui := new(cli.MockUi)
m := Meta{
Ui: ui,
}
// `terraform version`
c := &VersionCommand{
Meta: m,
Version: "4.5.6",
VersionPrerelease: "foo",
}
if code := c.Run([]string{"-v", "-version"}); code != 0 {
t.Fatalf("bad: \n%s", ui.ErrorWriter.String())
}
actual := strings.TrimSpace(ui.OutputWriter.String())
expected := "Terraform v4.5.6-foo"
if actual != expected {
t.Fatalf("wrong output\ngot: %#v\nwant: %#v", actual, expected)
}
}
func TestVersion_json(t *testing.T) {
fixtureDir := "testdata/providers-schema/basic"
td := tempDir(t)
@ -81,7 +105,7 @@ func TestVersion_json(t *testing.T) {
ProviderSource: providerSource,
}
// `terrafrom init`
// `terraform init`
ic := &InitCommand{
Meta: m,
}