mirror of https://github.com/hashicorp/terraform
parent
c6278bbe37
commit
dd380d0b58
@ -0,0 +1,59 @@
|
||||
package arguments
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/terraform/tfdiags"
|
||||
)
|
||||
|
||||
// Validate represents the command-line arguments for the validate command.
|
||||
type Validate struct {
|
||||
// Path is the directory containing the configuration to be validated. If
|
||||
// unspecified, validate will use the current directory.
|
||||
Path string
|
||||
|
||||
// ViewType specifies which output format to use: human, JSON, or "raw".
|
||||
ViewType ViewType
|
||||
}
|
||||
|
||||
// ParseValidate processes CLI arguments, returning a Validate value and errors.
|
||||
// If errors are encountered, a Validate value is still returned representing
|
||||
// the best effort interpretation of the arguments.
|
||||
func ParseValidate(args []string) (*Validate, tfdiags.Diagnostics) {
|
||||
var diags tfdiags.Diagnostics
|
||||
validate := &Validate{
|
||||
Path: ".",
|
||||
}
|
||||
|
||||
var jsonOutput bool
|
||||
cmdFlags := defaultFlagSet("validate")
|
||||
cmdFlags.BoolVar(&jsonOutput, "json", false, "json")
|
||||
|
||||
if err := cmdFlags.Parse(args); err != nil {
|
||||
diags = diags.Append(tfdiags.Sourceless(
|
||||
tfdiags.Error,
|
||||
"Failed to parse command-line flags",
|
||||
err.Error(),
|
||||
))
|
||||
}
|
||||
|
||||
args = cmdFlags.Args()
|
||||
if len(args) > 1 {
|
||||
diags = diags.Append(tfdiags.Sourceless(
|
||||
tfdiags.Error,
|
||||
"Too many command line arguments",
|
||||
"Expected at most one positional argument.",
|
||||
))
|
||||
}
|
||||
|
||||
if len(args) > 0 {
|
||||
validate.Path = args[0]
|
||||
}
|
||||
|
||||
switch {
|
||||
case jsonOutput:
|
||||
validate.ViewType = ViewJSON
|
||||
default:
|
||||
validate.ViewType = ViewHuman
|
||||
}
|
||||
|
||||
return validate, diags
|
||||
}
|
||||
@ -0,0 +1,99 @@
|
||||
package arguments
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/hashicorp/terraform/tfdiags"
|
||||
)
|
||||
|
||||
func TestParseValidate_valid(t *testing.T) {
|
||||
testCases := map[string]struct {
|
||||
args []string
|
||||
want *Validate
|
||||
}{
|
||||
"defaults": {
|
||||
nil,
|
||||
&Validate{
|
||||
Path: ".",
|
||||
ViewType: ViewHuman,
|
||||
},
|
||||
},
|
||||
"json": {
|
||||
[]string{"-json"},
|
||||
&Validate{
|
||||
Path: ".",
|
||||
ViewType: ViewJSON,
|
||||
},
|
||||
},
|
||||
"path": {
|
||||
[]string{"-json", "foo"},
|
||||
&Validate{
|
||||
Path: "foo",
|
||||
ViewType: ViewJSON,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for name, tc := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
got, diags := ParseValidate(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 TestParseValidate_invalid(t *testing.T) {
|
||||
testCases := map[string]struct {
|
||||
args []string
|
||||
want *Validate
|
||||
wantDiags tfdiags.Diagnostics
|
||||
}{
|
||||
"unknown flag": {
|
||||
[]string{"-boop"},
|
||||
&Validate{
|
||||
Path: ".",
|
||||
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"},
|
||||
&Validate{
|
||||
Path: "bar",
|
||||
ViewType: ViewJSON,
|
||||
},
|
||||
tfdiags.Diagnostics{
|
||||
tfdiags.Sourceless(
|
||||
tfdiags.Error,
|
||||
"Too many command line arguments",
|
||||
"Expected at most one positional argument.",
|
||||
),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for name, tc := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
got, gotDiags := ParseValidate(tc.args)
|
||||
if *got != *tc.want {
|
||||
t.Fatalf("unexpected result\n got: %#v\nwant: %#v", got, tc.want)
|
||||
}
|
||||
if !reflect.DeepEqual(gotDiags, tc.wantDiags) {
|
||||
t.Errorf("wrong result\ngot: %s\nwant: %s", spew.Sdump(gotDiags), spew.Sdump(tc.wantDiags))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,138 @@
|
||||
package views
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/hashicorp/terraform/command/arguments"
|
||||
"github.com/hashicorp/terraform/command/format"
|
||||
viewsjson "github.com/hashicorp/terraform/command/views/json"
|
||||
"github.com/hashicorp/terraform/tfdiags"
|
||||
)
|
||||
|
||||
// The Validate is used for the validate command.
|
||||
type Validate interface {
|
||||
// Results renders the diagnostics returned from a validation walk, and
|
||||
// returns a CLI exit code: 0 if there are no errors, 1 otherwise
|
||||
Results(diags tfdiags.Diagnostics) int
|
||||
|
||||
// Diagnostics renders early diagnostics, resulting from argument parsing.
|
||||
Diagnostics(diags tfdiags.Diagnostics)
|
||||
}
|
||||
|
||||
// NewValidate returns an initialized Validate implementation for the given ViewType.
|
||||
func NewValidate(vt arguments.ViewType, view *View) Validate {
|
||||
switch vt {
|
||||
case arguments.ViewJSON:
|
||||
return &ValidateJSON{view: view}
|
||||
case arguments.ViewHuman:
|
||||
return &ValidateHuman{view: view}
|
||||
default:
|
||||
panic(fmt.Sprintf("unknown view type %v", vt))
|
||||
}
|
||||
}
|
||||
|
||||
// The ValidateHuman implementation renders diagnostics in a human-readable form,
|
||||
// along with a success/failure message if Terraform is able to execute the
|
||||
// validation walk.
|
||||
type ValidateHuman struct {
|
||||
view *View
|
||||
}
|
||||
|
||||
var _ Validate = (*ValidateHuman)(nil)
|
||||
|
||||
func (v *ValidateHuman) Results(diags tfdiags.Diagnostics) int {
|
||||
columns := v.view.outputColumns()
|
||||
|
||||
if len(diags) == 0 {
|
||||
v.view.streams.Println(format.WordWrap(v.view.colorize.Color(validateSuccess), columns))
|
||||
} else {
|
||||
v.Diagnostics(diags)
|
||||
|
||||
if !diags.HasErrors() {
|
||||
v.view.streams.Println(format.WordWrap(v.view.colorize.Color(validateWarnings), columns))
|
||||
}
|
||||
}
|
||||
|
||||
if diags.HasErrors() {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
const validateSuccess = "[green][bold]Success![reset] The configuration is valid.\n"
|
||||
|
||||
const validateWarnings = "[green][bold]Success![reset] The configuration is valid, but there were some validation warnings as shown above.\n"
|
||||
|
||||
func (v *ValidateHuman) Diagnostics(diags tfdiags.Diagnostics) {
|
||||
v.view.Diagnostics(diags)
|
||||
}
|
||||
|
||||
// The ValidateJSON implementation renders validation results as a JSON object.
|
||||
// This object includes top-level fields summarizing the result, and an array
|
||||
// of JSON diagnostic objects.
|
||||
type ValidateJSON struct {
|
||||
view *View
|
||||
}
|
||||
|
||||
var _ Validate = (*ValidateJSON)(nil)
|
||||
|
||||
func (v *ValidateJSON) Results(diags tfdiags.Diagnostics) int {
|
||||
// FormatVersion represents the version of the json format and will be
|
||||
// incremented for any change to this format that requires changes to a
|
||||
// consuming parser.
|
||||
const FormatVersion = "0.1"
|
||||
|
||||
type Output struct {
|
||||
FormatVersion string `json:"format_version"`
|
||||
|
||||
// We include some summary information that is actually redundant
|
||||
// with the detailed diagnostics, but avoids the need for callers
|
||||
// to re-implement our logic for deciding these.
|
||||
Valid bool `json:"valid"`
|
||||
ErrorCount int `json:"error_count"`
|
||||
WarningCount int `json:"warning_count"`
|
||||
Diagnostics []*viewsjson.Diagnostic `json:"diagnostics"`
|
||||
}
|
||||
|
||||
output := Output{
|
||||
FormatVersion: FormatVersion,
|
||||
Valid: true, // until proven otherwise
|
||||
}
|
||||
configSources := v.view.configSources()
|
||||
for _, diag := range diags {
|
||||
output.Diagnostics = append(output.Diagnostics, viewsjson.NewDiagnostic(diag, configSources))
|
||||
|
||||
switch diag.Severity() {
|
||||
case tfdiags.Error:
|
||||
output.ErrorCount++
|
||||
output.Valid = false
|
||||
case tfdiags.Warning:
|
||||
output.WarningCount++
|
||||
}
|
||||
}
|
||||
if output.Diagnostics == nil {
|
||||
// Make sure this always appears as an array in our output, since
|
||||
// this is easier to consume for dynamically-typed languages.
|
||||
output.Diagnostics = []*viewsjson.Diagnostic{}
|
||||
}
|
||||
|
||||
j, err := json.MarshalIndent(&output, "", " ")
|
||||
if err != nil {
|
||||
// Should never happen because we fully-control the input here
|
||||
panic(err)
|
||||
}
|
||||
v.view.streams.Println(string(j))
|
||||
|
||||
if diags.HasErrors() {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Diagnostics should only be called if the validation walk cannot be executed.
|
||||
// In this case, we choose to render human-readable diagnostic output,
|
||||
// primarily for backwards compatibility.
|
||||
func (v *ValidateJSON) Diagnostics(diags tfdiags.Diagnostics) {
|
||||
v.view.Diagnostics(diags)
|
||||
}
|
||||
@ -0,0 +1,133 @@
|
||||
package views
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/hashicorp/terraform/command/arguments"
|
||||
"github.com/hashicorp/terraform/internal/terminal"
|
||||
"github.com/hashicorp/terraform/tfdiags"
|
||||
)
|
||||
|
||||
func TestValidateHuman(t *testing.T) {
|
||||
testCases := map[string]struct {
|
||||
diag tfdiags.Diagnostic
|
||||
wantSuccess bool
|
||||
wantSubstring string
|
||||
}{
|
||||
"success": {
|
||||
nil,
|
||||
true,
|
||||
"The configuration is valid.",
|
||||
},
|
||||
"warning": {
|
||||
tfdiags.Sourceless(
|
||||
tfdiags.Warning,
|
||||
"Your shoelaces are untied",
|
||||
"Watch out, or you'll trip!",
|
||||
),
|
||||
true,
|
||||
"The configuration is valid, but there were some validation warnings",
|
||||
},
|
||||
"error": {
|
||||
tfdiags.Sourceless(
|
||||
tfdiags.Error,
|
||||
"Configuration is missing random_pet",
|
||||
"Every configuration should have a random_pet.",
|
||||
),
|
||||
false,
|
||||
"Error: Configuration is missing random_pet",
|
||||
},
|
||||
}
|
||||
for name, tc := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
streams, done := terminal.StreamsForTesting(t)
|
||||
view := NewView(streams)
|
||||
view.Configure(&arguments.View{NoColor: true})
|
||||
v := NewValidate(arguments.ViewHuman, view)
|
||||
|
||||
var diags tfdiags.Diagnostics
|
||||
|
||||
if tc.diag != nil {
|
||||
diags = diags.Append(tc.diag)
|
||||
}
|
||||
|
||||
ret := v.Results(diags)
|
||||
|
||||
if tc.wantSuccess && ret != 0 {
|
||||
t.Errorf("expected 0 return code, got %d", ret)
|
||||
} else if !tc.wantSuccess && ret != 1 {
|
||||
t.Errorf("expected 1 return code, got %d", ret)
|
||||
}
|
||||
|
||||
got := done(t).All()
|
||||
if strings.Contains(got, "Success!") != tc.wantSuccess {
|
||||
t.Errorf("unexpected output:\n%s", got)
|
||||
}
|
||||
if !strings.Contains(got, tc.wantSubstring) {
|
||||
t.Errorf("expected output to include %q, but was:\n%s", tc.wantSubstring, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateJSON(t *testing.T) {
|
||||
testCases := map[string]struct {
|
||||
diag tfdiags.Diagnostic
|
||||
wantSuccess bool
|
||||
}{
|
||||
"success": {
|
||||
nil,
|
||||
true,
|
||||
},
|
||||
"warning": {
|
||||
tfdiags.Sourceless(
|
||||
tfdiags.Warning,
|
||||
"Your shoelaces are untied",
|
||||
"Watch out, or you'll trip!",
|
||||
),
|
||||
true,
|
||||
},
|
||||
"error": {
|
||||
tfdiags.Sourceless(
|
||||
tfdiags.Error,
|
||||
"Configuration is missing random_pet",
|
||||
"Every configuration should have a random_pet.",
|
||||
),
|
||||
false,
|
||||
},
|
||||
}
|
||||
for name, tc := range testCases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
streams, done := terminal.StreamsForTesting(t)
|
||||
view := NewView(streams)
|
||||
view.Configure(&arguments.View{NoColor: true})
|
||||
v := NewValidate(arguments.ViewJSON, view)
|
||||
|
||||
var diags tfdiags.Diagnostics
|
||||
|
||||
if tc.diag != nil {
|
||||
diags = diags.Append(tc.diag)
|
||||
}
|
||||
|
||||
ret := v.Results(diags)
|
||||
|
||||
if tc.wantSuccess && ret != 0 {
|
||||
t.Errorf("expected 0 return code, got %d", ret)
|
||||
} else if !tc.wantSuccess && ret != 1 {
|
||||
t.Errorf("expected 1 return code, got %d", ret)
|
||||
}
|
||||
|
||||
got := done(t).All()
|
||||
|
||||
// Make sure the result looks like JSON; we comprehensively test
|
||||
// the structure of this output in the command package tests.
|
||||
var result map[string]interface{}
|
||||
|
||||
if err := json.Unmarshal([]byte(got), &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Loading…
Reference in new issue