command staticcheck

This commit is contained in:
James Bardin 2020-12-01 12:34:50 -05:00
parent ccf0d8815f
commit 1c58c6ba48
17 changed files with 21 additions and 167 deletions

View File

@ -31,7 +31,6 @@ import (
"github.com/hashicorp/terraform/plans"
"github.com/hashicorp/terraform/plans/planfile"
"github.com/hashicorp/terraform/providers"
"github.com/hashicorp/terraform/provisioners"
"github.com/hashicorp/terraform/states"
"github.com/hashicorp/terraform/states/statefile"
"github.com/hashicorp/terraform/states/statemgr"
@ -120,23 +119,6 @@ func metaOverridesForProvider(p providers.Interface) *testingOverrides {
}
}
func metaOverridesForProviderAndProvisioner(p providers.Interface, pr provisioners.Interface) *testingOverrides {
return &testingOverrides{
Providers: map[addrs.Provider]providers.Factory{
addrs.NewDefaultProvider("test"): providers.FactoryFixed(p),
},
Provisioners: map[string]provisioners.Factory{
"shell": provisioners.FactoryFixed(pr),
},
}
}
func testModule(t *testing.T, name string) *configs.Config {
t.Helper()
c, _ := testModuleWithSnapshot(t, name)
return c
}
func testModuleWithSnapshot(t *testing.T, name string) (*configs.Config, *configload.Snapshot) {
t.Helper()
@ -516,26 +498,6 @@ func testTempDir(t *testing.T) string {
return d
}
// testRename renames the path to new and returns a function to defer to
// revert the rename.
func testRename(t *testing.T, base, path, new string) func() {
t.Helper()
if base != "" {
path = filepath.Join(base, path)
new = filepath.Join(base, new)
}
if err := os.Rename(path, new); err != nil {
t.Fatalf("err: %s", err)
}
return func() {
// Just re-rename and ignore the return value
testRename(t, "", new, path)
}
}
// testChdir changes the directory and returns a function to defer to
// revert the old cwd.
func testChdir(t *testing.T, new string) func() {
@ -945,8 +907,6 @@ func testCopyDir(t *testing.T, src, dst string) {
}
}
}
return
}
// normalizeJSON removes all insignificant whitespace from the given JSON buffer

View File

@ -967,15 +967,3 @@ test_instance.foo:
ID = yay
provider = provider["registry.terraform.io/hashicorp/test"]
`
const testImportCustomProviderStr = `
test_instance.foo:
ID = yay
provider = provider["registry.terraform.io/hashicorp/test"].alias
`
const testImportProviderMismatchStr = `
test_instance.foo:
ID = yay
provider = provider["registry.terraform.io/hashicorp/test-beta"]
`

View File

@ -322,9 +322,9 @@ func (c *InitCommand) getModules(path string, earlyRoot *tfconfig.Module, upgrad
}
if upgrade {
c.Ui.Output(c.Colorize().Color(fmt.Sprintf("[reset][bold]Upgrading modules...")))
c.Ui.Output(c.Colorize().Color("[reset][bold]Upgrading modules..."))
} else {
c.Ui.Output(c.Colorize().Color(fmt.Sprintf("[reset][bold]Initializing modules...")))
c.Ui.Output(c.Colorize().Color("[reset][bold]Initializing modules..."))
}
hooks := uiModuleInstallHooks{
@ -351,7 +351,7 @@ func (c *InitCommand) getModules(path string, earlyRoot *tfconfig.Module, upgrad
}
func (c *InitCommand) initBackend(root *configs.Module, extraConfig rawFlags) (be backend.Backend, output bool, diags tfdiags.Diagnostics) {
c.Ui.Output(c.Colorize().Color(fmt.Sprintf("\n[reset][bold]Initializing the backend...")))
c.Ui.Output(c.Colorize().Color("\n[reset][bold]Initializing the backend..."))
var backendConfig *configs.Backend
var backendConfigOverride hcl.Body
@ -1092,15 +1092,6 @@ rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
`
const outputInitProvidersUnconstrained = `
The following providers do not have any version constraints in configuration,
so the latest version was installed.
To prevent automatic upgrades to new major versions that may contain breaking
changes, we recommend adding version constraints in a required_providers block
in your configuration, with the constraint strings suggested below.
`
// providerProtocolTooOld is a message sent to the CLI UI if the provider's
// supported protocol versions are too old for the user's version of terraform,
// but a newer version of the provider is compatible.

View File

@ -844,7 +844,7 @@ func TestInit_inputFalse(t *testing.T) {
}
args := []string{"-input=false", "-backend-config=path=foo"}
if code := c.Run([]string{"-input=false"}); code != 0 {
if code := c.Run(args); code != 0 {
t.Fatalf("bad: \n%s", ui.ErrorWriter)
}
@ -975,7 +975,7 @@ func TestInit_getProvider(t *testing.T) {
Version: 999,
Lineage: "123-456-789",
TerraformVersion: "999.0.0",
Outputs: make(map[string]interface{}, 0),
Outputs: make(map[string]interface{}),
Resources: make([]map[string]interface{}, 0),
}
src, err := json.MarshalIndent(fs, "", " ")
@ -984,6 +984,9 @@ func TestInit_getProvider(t *testing.T) {
}
src = append(src, '\n')
_, err = f.Write(src)
if err != nil {
t.Fatal(err)
}
ui := new(cli.MockUi)
m.Ui = ui

View File

@ -198,7 +198,6 @@ type Meta struct {
stateOutPath string
backupPath string
parallelism int
provider string
stateLock bool
stateLockTimeout time.Duration
forceInitCopy bool
@ -639,49 +638,6 @@ func (m *Meta) showDiagnostics(vals ...interface{}) {
}
}
// outputShadowError outputs the error from ctx.ShadowError. If the
// error is nil then nothing happens. If output is false then it isn't
// outputted to the user (you can define logic to guard against outputting).
func (m *Meta) outputShadowError(err error, output bool) bool {
// Do nothing if no error
if err == nil {
return false
}
// If not outputting, do nothing
if !output {
return false
}
// Write the shadow error output to a file
path := fmt.Sprintf("terraform-error-%d.log", time.Now().UTC().Unix())
if err := ioutil.WriteFile(path, []byte(err.Error()), 0644); err != nil {
// If there is an error writing it, just let it go
log.Printf("[ERROR] Error writing shadow error: %s", err)
return false
}
// Output!
m.Ui.Output(m.Colorize().Color(fmt.Sprintf(
"[reset][bold][yellow]\nExperimental feature failure! Please report a bug.\n\n"+
"This is not an error. Your Terraform operation completed successfully.\n"+
"Your real infrastructure is unaffected by this message.\n\n"+
"[reset][yellow]While running, Terraform sometimes tests experimental features in the\n"+
"background. These features cannot affect real state and never touch\n"+
"real infrastructure. If the features work properly, you see nothing.\n"+
"If the features fail, this message appears.\n\n"+
"You can report an issue at: https://github.com/hashicorp/terraform/issues\n\n"+
"The failure was written to %q. Please\n"+
"double check this file contains no sensitive information and report\n"+
"it with your issue.\n\n"+
"This is not an error. Your terraform operation completed successfully\n"+
"and your real infrastructure is unaffected by this message.",
path,
)))
return true
}
// WorkspaceNameEnvVar is the name of the environment variable that can be used
// to set the name of the Terraform workspace, overriding the workspace chosen
// by `terraform workspace select`.
@ -690,14 +646,14 @@ func (m *Meta) outputShadowError(err error, output bool) bool {
// and `terraform workspace delete`.
const WorkspaceNameEnvVar = "TF_WORKSPACE"
var invalidWorkspaceNameEnvVar = fmt.Errorf("Invalid workspace name set using %s", WorkspaceNameEnvVar)
var errInvalidWorkspaceNameEnvVar = fmt.Errorf("Invalid workspace name set using %s", WorkspaceNameEnvVar)
// Workspace returns the name of the currently configured workspace, corresponding
// to the desired named state.
func (m *Meta) Workspace() (string, error) {
current, overridden := m.WorkspaceOverridden()
if overridden && !validWorkspaceName(current) {
return "", invalidWorkspaceNameEnvVar
return "", errInvalidWorkspaceNameEnvVar
}
return current, nil
}

View File

@ -1240,12 +1240,3 @@ const successBackendSet = `
Successfully configured the backend %q! Terraform will automatically
use this backend unless the backend configuration changes.
`
const errBackendLegacy = `
This working directory is configured to use the legacy remote state features
from Terraform 0.8 or earlier. Remote state changed significantly in Terraform
0.9 and the automatic upgrade mechanism has now been removed.
To upgrade, please first use Terraform v0.11 to complete the upgrade steps:
https://www.terraform.io/docs/backends/legacy-0-8.html
`

View File

@ -1541,7 +1541,7 @@ func TestMetaBackend_planLocalStatePath(t *testing.T) {
defer testChdir(t, td)()
original := testState()
mark := markStateForMatching(original, "hello")
markStateForMatching(original, "hello")
backendConfigBlock := cty.ObjectVal(map[string]cty.Value{
"path": cty.NullVal(cty.String),
@ -1607,7 +1607,7 @@ func TestMetaBackend_planLocalStatePath(t *testing.T) {
// Write some state
state = states.NewState()
mark = markStateForMatching(state, "changing")
mark := markStateForMatching(state, "changing")
s.WriteState(state)
if err := s.PersistState(); err != nil {

View File

@ -236,7 +236,7 @@ func TestMeta_Workspace_override(t *testing.T) {
},
"invalid name": {
"",
invalidWorkspaceNameEnvVar,
errInvalidWorkspaceNameEnvVar,
},
}

View File

@ -963,17 +963,3 @@ foo = "bar"
variable "nope" {
}
`
const testPlanNoStateStr = `
<not created>
`
const testPlanStateStr = `
ID = bar
Tainted = false
`
const testPlanStateDefaultStr = `
ID = bar
Tainted = false
`

View File

@ -2,7 +2,6 @@ package command
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"os"
@ -691,25 +690,6 @@ func TestRefresh_displaysOutputs(t *testing.T) {
}
}
// newInstanceState creates a new states.ResourceInstanceObjectSrc with the
// given value for its single id attribute. It is named newInstanceState for
// historical reasons, because it was originally written for the poorly-named
// terraform.InstanceState type.
func newInstanceState(id string) *states.ResourceInstanceObjectSrc {
attrs := map[string]interface{}{
"id": id,
}
attrsJSON, err := json.Marshal(attrs)
if err != nil {
panic(fmt.Sprintf("failed to marshal attributes: %s", err)) // should never happen
}
return &states.ResourceInstanceObjectSrc{
AttrsJSON: attrsJSON,
Status: states.ObjectReady,
}
}
// refreshFixtureSchema returns a schema suitable for processing the
// configuration in testdata/refresh . This schema should be
// assigned to a mock provider named "test".
func refreshFixtureSchema() *terraform.ProviderSchema {

View File

@ -61,7 +61,7 @@ func (c *StateListCommand) Run(args []string) int {
state := stateMgr.State()
if state == nil {
c.Ui.Error(fmt.Sprintf(errStateNotFound))
c.Ui.Error(errStateNotFound)
return 1
}

View File

@ -64,7 +64,7 @@ func (c *StateMvCommand) Run(args []string) int {
stateFrom := stateFromMgr.State()
if stateFrom == nil {
c.Ui.Error(fmt.Sprintf(errStateNotFound))
c.Ui.Error(errStateNotFound)
return 1
}

View File

@ -22,7 +22,6 @@ func (c *StatePullCommand) Run(args []string) int {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
return 1
}
args = cmdFlags.Args()
// Load the backend
b, backendDiags := c.Backend(nil)

View File

@ -90,7 +90,7 @@ func (c *StateReplaceProviderCommand) Run(args []string) int {
state := stateMgr.State()
if state == nil {
c.Ui.Error(fmt.Sprintf(errStateNotFound))
c.Ui.Error(errStateNotFound)
return 1
}
@ -119,7 +119,7 @@ func (c *StateReplaceProviderCommand) Run(args []string) int {
// Explain the changes
colorize := c.Colorize()
c.Ui.Output("Terraform will perform the following actions:\n")
c.Ui.Output(colorize.Color(fmt.Sprintf(" [yellow]~[reset] Updating provider:")))
c.Ui.Output(colorize.Color(" [yellow]~[reset] Updating provider:"))
c.Ui.Output(colorize.Color(fmt.Sprintf(" [red]-[reset] %s", from)))
c.Ui.Output(colorize.Color(fmt.Sprintf(" [green]+[reset] %s\n", to)))
@ -134,7 +134,7 @@ func (c *StateReplaceProviderCommand) Run(args []string) int {
"\n[bold]Do you want to make these changes?[reset]\n" +
"Only 'yes' will be accepted to continue.\n",
))
v, err := c.Ui.Ask(fmt.Sprintf("Enter a value:"))
v, err := c.Ui.Ask("Enter a value:")
if err != nil {
c.Ui.Error(fmt.Sprintf("Error asking for approval: %s", err))
return 1

View File

@ -59,7 +59,7 @@ func (c *StateRmCommand) Run(args []string) int {
state := stateMgr.State()
if state == nil {
c.Ui.Error(fmt.Sprintf(errStateNotFound))
c.Ui.Error(errStateNotFound)
return 1
}

View File

@ -109,7 +109,7 @@ func (c *StateShowCommand) Run(args []string) int {
state := stateMgr.State()
if state == nil {
c.Ui.Error(fmt.Sprintf(errStateNotFound))
c.Ui.Error(errStateNotFound)
return 1
}

View File

@ -15,7 +15,7 @@ type WorkspaceCommand struct {
}
func (c *WorkspaceCommand) Run(args []string) int {
args = c.Meta.process(args)
c.Meta.process(args)
envCommandShowWarning(c.Ui, c.LegacyName)
cmdFlags := c.Meta.extendedFlagSet("workspace")