Strider report

Strider corpus: opentofu

820 msformat3610 mscheck 32940total 2584errors 13094warnings 17262notes

Showing 1000 of 32940 detailed findings. The summary includes all 32940 findings.

cmd/tofu/main_test.go1

55:30add-constantstring literal "foo" appears more than twice; define a constant

cmd/tofu/main_test.go:55:30

54 "both env var and CLI",
55 []string{testCommandName, "foo", "bar"},
56 "-foo baz",

internal/backend/remote-state/consul/backend_state.go1

52:18append-to-sized-sliceresult already has a positive length; use make with length zero and capacity, or reslice to zero before append

internal/backend/remote-state/consul/backend_state.go:52:18

51 for k := range envs {
52 result = append(result, k)
53 }

internal/legacy/helper/schema/schema_test.go1

3136:44argument-overwritten-before-useargument v is overwritten before its incoming value is used

internal/legacy/helper/schema/schema_test.go:3136:44

3135 },
3136 CustomizeDiff: func(diff *ResourceDiff, v interface{}) error {
3137 v, ok := diff.GetOk("unrelated_set")

internal/communicator/ssh/communicator.go1

32:2blank-importsblank import should be justified by a comment

internal/communicator/ssh/communicator.go:32:2

31
32 _ "github.com/opentofu/opentofu/internal/logging"
33)

internal/addrs/provider_test.go1

440:7boolean-literal-comparisonomit the boolean literal from the logical expression

internal/addrs/provider_test.go:440:7

439 if len(diags) > 0 {
440 if test.Err == false {
441 t.Errorf("got error, expected success")

internal/backend/local/backend_test.go1

39:3call-to-gcavoid explicit garbage collection

internal/backend/local/backend_test.go:39:3

38 if runtime.GOOS == "windows" {
39 runtime.GC()
40 }

cmd/tofu/help.go1

19:6cognitive-complexityfunction has cognitive complexity 14; maximum is 7

cmd/tofu/help.go:19:6

18// helpFunc is a cli.HelpFunc that can be used to output the help CLI instructions for OpenTofu.
19func helpFunc(commands map[string]cli.CommandFactory) string {
20 // Determine the maximum key length, and classify based on type

internal/addrs/parse_ref.go1

164:6confusing-namingname parseRef differs from ParseRef only by capitalization

internal/addrs/parse_ref.go:164:6

163
164func parseRef(traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) {
165 var diags tfdiags.Diagnostics

internal/addrs/move_endpoint_module.go1

452:100confusing-resultsadjacent unnamed results of the same type should be named

internal/addrs/move_endpoint_module.go:452:100

451// API.
452func (e *MoveEndpointInModule) matchModuleInstancePrefix(instAddr ModuleInstance) (ModuleInstance, ModuleInstance, bool) {
453 if len(e.module) > len(instAddr) {

internal/command/cliconfig/ociauthconfig/credentials_config.go1

40:6constructor-interface-returnNewGlobalDockerCredentialHelperCredentialsConfig returns interface CredentialsConfig although its concrete result is consistently globalDockerCredentialHelperCredentialsConfig; return the concrete type

internal/command/cliconfig/ociauthconfig/credentials_config.go:40:6

39// helper name.
40func NewGlobalDockerCredentialHelperCredentialsConfig(locationForUI string, helperName string) CredentialsConfig {
41 return globalDockerCredentialHelperCredentialsConfig{

internal/backend/local/backend.go1

355:10context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend.go:355:10

354 doneCh <-chan struct{},
355 stopCtx context.Context,
356 cancelCtx context.Context,

internal/backend/backend.go1

389:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/backend/backend.go:389:2

388 // is fully done.
389 context.Context
390

internal/legacy/helper/schema/resource_data.go1

432:3copy-lock-valueassignment copies tofu.InstanceState by value; it contains sync.Mutex

internal/legacy/helper/schema/resource_data.go:432:3

431 if d.state != nil {
432 copyState = *d.state.DeepCopy()
433 }

cmd/tofu/main.go1

53:6cyclomatic-complexityfunction complexity is 40; maximum is 10

cmd/tofu/main.go:53:6

52
53func realMain() int {
54 defer logging.PanicHandler()

internal/backend/local/local_test.go1

18:2deep-exitprocess-exit calls should be confined to main or init

internal/backend/local/local_test.go:18:2

17 flag.Parse()
18 os.Exit(m.Run())
19}

internal/backend/remote-state/gcs/backend.go1

185:37deprecated-api-usagegoogle.golang.org/api/option.WithCredentialsJSON is deprecated: This function is being deprecated because of a potential security risk.

internal/backend/remote-state/gcs/backend.go:185:37

184 // closely as possible.
185 credOptions = append(credOptions, option.WithCredentialsJSON([]byte(contents)))
186 }

cmd/tofu/commands.go1

498:13discarded-error-resulterror result returned by cmdFact is discarded

cmd/tofu/commands.go:498:13

497 for key, cmdFact := range commands {
498 cmd, _ := cmdFact()
499 _, ok := cmd.(*command.AliasCommand)

cmd/tofu/main_test.go1

253:1doc-comment-perioddocumentation comment should end with punctuation

cmd/tofu/main_test.go:253:1

252
253// verify that we output valid autocomplete results
254func TestMain_autoComplete(t *testing.T) {

internal/addrs/provider_config.go1

169:2early-returninvert the condition and return early to reduce nesting

internal/addrs/provider_config.go:169:2

168
169 if tt, ok := remain[1].(hcl.TraverseIndex); ok {
170 if !tt.Key.Type().Equals(cty.String) {

internal/command/jsonprovider/attribute.go1

36:2enforce-switch-styledefault clause should be the last switch clause

internal/command/jsonprovider/attribute.go:36:2

35 switch sk {
36 default:
37 return "plain"

cmd/tofu/main.go1

369:4error-stringserror string should not be capitalized or end with punctuation

cmd/tofu/main.go:369:4

368 return nil, fmt.Errorf(
369 "Error parsing extra CLI args from %s: %s",
370 envName, err)

internal/command/cliconfig/credentials.go1

495:6error-type-namingerror implementation type should have an Error suffix

internal/command/cliconfig/credentials.go:495:6

494// in a file that we cannot automatically update.
495type ErrUnwritableHostCredentials svchost.Hostname
496

internal/communicator/ssh/communicator_test.go1

477:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

internal/communicator/ssh/communicator_test.go:477:2

476func TestHostCert(t *testing.T) {
477 pk, _, _, _, err := ssh.ParseAuthorizedKey([]byte(testServerHostCert))
478 if err != nil {

cmd/tofu/main.go1

46:2exported-declaration-commentexported declaration should have a comment beginning with its name

cmd/tofu/main.go:46:2

45
46 EnvCPUProfile = "TOFU_CPU_PROFILE"
47)

cmd/tofu/commands.go1

1:1file-length-limitfile has 506 lines; maximum is 500

cmd/tofu/commands.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/backend/remote-state/azure/auth/utility.go1

17:65flag-parameterboolean parameter acceptEmpty controls function flow

internal/backend/remote-state/azure/auth/utility.go:17:65

16// an error unless acceptEmpty is true.
17func consolidateFileAndValue(value, fileName, fieldName string, acceptEmpty bool) (string, error) {
18 var fileValue string

cmd/tofu/commands.go2

1:1formatfile is not formatted

cmd/tofu/commands.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/commands.go`
56:6function-lengthfunction has 15 statements and 405 lines; maximum is 50 statements or 75 lines

cmd/tofu/commands.go:56:6

55
56func initCommands(
57 ctx context.Context,

internal/backend/local/backend_local.go1

49:17function-result-limitfunction returns 4 values; maximum is 3

internal/backend/local/backend_local.go:49:17

48
49func (b *Local) localRun(ctx context.Context, stopCtx context.Context, op *backend.Operation) (*backend.LocalRun, *configload.Snapshot, statemgr.Full, tfdiags.Diagnostics) {
50 var diags tfdiags.Diagnostics

internal/initwd/module_install.go1

324:13identical-branchesif and else branches are identical

internal/initwd/module_install.go:324:13

323 diags = diags.Extend(mDiags)
324 } else {
325 diags = diags.Extend(mDiags)

internal/genconfig/generate_config.go1

110:28identical-if-chain-branchesif-else-if chain repeats a branch body

internal/genconfig/generate_config.go:110:28

109 writeAttrTypeConstraint(buf, attrS)
110 } else if attrS.Optional {
111 buf.WriteString(strings.Repeat(" ", indent))

internal/addrs/check_rule.go1

47:2identical-switch-branchesswitch repeats a case body

internal/addrs/check_rule.go:47:2

46 return fmt.Sprintf("%s.postcondition[%d]", container, c.Index)
47 case OutputPrecondition:
48 return fmt.Sprintf("%s.precondition[%d]", container, c.Index)

cmd/tofu/commands.go1

28:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/tofu/commands.go:28:2

27 "github.com/opentofu/opentofu/internal/getproviders"
28 pluginDiscovery "github.com/opentofu/opentofu/internal/plugin/discovery"
29)

cmd/tofu/provider_source.go1

240:3import-shadowingidentifier url shadows an imported package

cmd/tofu/provider_source.go:240:3

239 case cliconfig.ProviderInstallationNetworkMirror:
240 url, err := url.Parse(string(loc))
241 if err != nil {

internal/legacy/hcl2shim/values.go1

160:7impossible-integer-comparisoncomparison is always true for type int64

internal/legacy/hcl2shim/values.go:160:7

159 const MinInt = -MaxInt - 1
160 if i <= int64(MaxInt) && i >= int64(MinInt) {
161 return int(i) // Like HCL token.NUMBER

internal/legacy/tofu/state_upgrade_v2_to_v3.go1

145:3increment-decrementuse ++ or -- instead of assigning an addition or subtraction of one

internal/legacy/tofu/state_upgrade_v2_to_v3.go:145:3

144 output[i] = key
145 i = i + 1
146 }

internal/backend/remote/backend_context.go1

135:8inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/backend/remote/backend_context.go:135:8

134 if _, ok := op.Variables[v.Key]; !ok {
135 op.Variables[v.Key] = &remoteStoredVariableValue{
136 definition: v,

internal/backend/remote-state/pg/client.go1

158:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.FormatInt with base 10

internal/backend/remote-state/pg/client.go:158:9

157 hash.Write([]byte(c.SchemaName + "\x00" + c.TableName))
158 return fmt.Sprintf("%d", int64(hash.Sum32())*-1)
159}

internal/addrs/module_source_test.go1

267:11insecure-url-schemeURL uses insecure http scheme

internal/addrs/module_source_test.go:267:11

266 "HTTP URL": {
267 input: "http://example.com/module",
268 want: ModuleSourceRemote{

internal/command/views/backend.go1

14:14interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

internal/command/views/backend.go:14:14

13
14type Backend interface {
15 Basic

internal/backend/remote/backend_common.go1

128:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_common.go:128:7

127 for _, item := range rl.Items {
128 if !found {
129 if r.ID == item.ID {

cmd/tofu/commands.go1

56:6max-parametersfunction has 9 parameters; maximum is 8

cmd/tofu/commands.go:56:6

55
56func initCommands(
57 ctx context.Context,

internal/cloud/tfe_client_mock.go1

525:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:525:6

524
525type MockRedactedPlans struct {
526 client *MockClient

internal/addrs/module.go1

307:2modifies-parameterassignment modifies parameter remain

internal/addrs/module.go:307:2

306 kwRange := remain[0].SourceRange()
307 remain = remain[1:]
308 // If we have the prefix "module" then we should be followed by a

internal/addrs/map.go1

47:2modifies-value-receiverassignment modifies value receiver m

internal/addrs/map.go:47:2

46 realKey := key.UniqueKey()
47 m.Elems[realKey] = MapElem[K, V]{key, value}
48}

cmd/tofu/commands.go1

54:31nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/commands.go:54:31

53// hiddenCommands set, because that would be rather silly.
54var hiddenCommands map[string]struct{}
55

internal/backend/remote-state/azure/client.go2

53:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/azure/client.go:53:4

52 if notFoundError(err) {
53 return nil, nil
54 }
53:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/azure/client.go:53:4

52 if notFoundError(err) {
53 return nil, nil
54 }

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

132:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

internal/builtin/provisioners/remote-exec/resource_provisioner.go:132:3

131 for _, s := range scripts {
132 defer s.Close()
133 }

internal/addrs/parse_target.go1

109:5no-else-after-returnremove else and unindent its body after the return

internal/addrs/parse_target.go:109:5

108 return moduleAddr.ResourceInstance(mode, typeName, name, key), diags
109 } else {
110 diags = diags.Append(&hcl.Diagnostic{

internal/backend/remote-state/inmem/backend.go1

32:6no-initreplace init with explicit initialization

internal/backend/remote-state/inmem/backend.go:32:6

31
32func init() {
33 Reset()

internal/addrs/module_source_test.go1

669:2no-naked-returnreturn values must be explicit

internal/addrs/module_source_test.go:669:2

668 }
669 return
670}

cmd/tofu/commands.go1

37:5no-package-varpackage variables introduce mutable global state

cmd/tofu/commands.go:37:5

36// commands is the mapping of all the available OpenTofu commands.
37var commands map[string]cli.CommandFactory
38

internal/lang/eval/config_dependencies.go1

37:2overwritten-before-usethis value of ctx is overwritten before use

internal/lang/eval/config_dependencies.go:37:2

36 // as the initial worker node in the work graph.
37 ctx = grapheval.ContextWithNewWorker(ctx)
38 _ = ctx // just so we can keep the above as a reminder of the need to have a grapheval worker in future work

cmd/tofu/commands.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/commands.go:6:9

5
6package main
7

internal/command/jsonformat/structured/attribute_path/matcher.go2

6:9package-directory-mismatchpackage attribute_path does not match directory attribute_path

internal/command/jsonformat/structured/attribute_path/matcher.go:6:9

5
6package attribute_path
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/command/jsonformat/structured/attribute_path/matcher.go:6:9

5
6package attribute_path
7

cmd/tofu/main.go1

443:28range-value-addresstaking the address of range value c can be misleading

cmd/tofu/main.go:443:28

442 }
443 unmanagedProviders[a] = &plugin.ReattachConfig{
444 Protocol: plugin.Protocol(c.Protocol),

internal/legacy/tofu/resource_address.go1

397:7receiver-namingreceiver name addr is inconsistent with r

internal/legacy/tofu/resource_address.go:397:7

396// the new type is required.
397func (addr *ResourceAddress) AbsResourceInstanceAddr() addrs.AbsResourceInstance {
398 if !addr.HasResourceSpec() {

internal/addrs/module_source_resolve.go1

28:3redefines-builtin-ididentifier new shadows a predeclared identifier

internal/addrs/module_source_resolve.go:28:3

27 aRaw := string(a)
28 new := path.Join(aRaw, bRaw)
29 if !isModuleSourceLocal(new) {

internal/addrs/instance_key_test.go1

19:4redundant-conversionconversion from IntKey to the identical type is redundant

internal/addrs/instance_key_test.go:19:4

18 {
19 IntKey(0),
20 `[0]`,

internal/backend/remote-state/s3/backend_state.go1

18:2redundant-import-aliasimport alias is identical to the package name

internal/backend/remote-state/s3/backend_state.go:18:2

17 "github.com/aws/aws-sdk-go-v2/service/s3"
18 types "github.com/aws/aws-sdk-go-v2/service/s3/types"
19 "github.com/aws/smithy-go"

internal/legacy/helper/schema/field_reader.go1

213:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/field_reader.go:213:9

212 result := make([]interface{}, countResult.Value.(int))
213 for i, _ := range result {
214 is := strconv.FormatInt(int64(i), 10)

internal/addrs/move_endpoint_module.go1

108:2single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:108:2

107 // in the string representation.
108 switch e.relSubject.(type) {
109 case AbsModuleCall, AbsResource:

internal/legacy/helper/schema/resource_timeout.go1

144:4single-iteration-loopthe surrounding loop always terminates during its first iteration

internal/legacy/helper/schema/resource_timeout.go:144:4

143 }
144 return nil
145 }

cmd/tofu/provider_source.go1

60:6slice-preallocationpreallocate searchRules with capacity len(range source) before appending once per iteration

cmd/tofu/provider_source.go:60:6

59 var diags tfdiags.Diagnostics
60 var searchRules []getproviders.MultiSourceSelector
61

internal/backend/remote-state/oss/backend.go1

640:38standard-http-method-constantreplace the HTTP method literal with http.MethodGet

internal/backend/remote-state/oss/backend.go:640:38

639 requestUrl := securityCredURL + ecsRoleName
640 httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader(""))
641 if err != nil {

cmd/tofu/main.go1

213:2task-commentTODO comment should be resolved or linked to an owned work item

cmd/tofu/main.go:213:2

212 }
213 // TODO meta-refactor - this is temporary because chdir logic strips away the -chdir flag from the args.
214 // Once we move to a different CLI lib, this will be handled by that, where flags defined on a parent

internal/backend/remote-state/s3/validate.go1

253:35time-namingtime.Duration name should not include a unit suffix

internal/backend/remote-state/s3/validate.go:253:35

252
253func validateDuration(val string, min, max time.Duration, path cty.Path, diags *tfdiags.Diagnostics) {
254 d, err := time.ParseDuration(val)

cmd/tofu/main_test.go1

280:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/tofu/main_test.go:280:1

279
280type testCommandCLI struct {
281 Args []string

internal/addrs/check_rule_diagnostic_test.go1

29:30unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/check_rule_diagnostic_test.go:29:30

28
29 if overridden[0].ExtraInfo().(*CheckRuleDiagnosticExtra).wrapped.(string) != "extra" {
30 t.Errorf("unexpected extra info: %v", overridden[0].ExtraInfo())

internal/backend/remote-state/oss/backend.go1

646:2unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

internal/backend/remote-state/oss/backend.go:646:2

645 httpClient := &http.Client{}
646 httpResponse, err := httpClient.Do(httpRequest)
647 if err != nil {

internal/flock/filesystem_lock_windows.go1

30:2unexported-namingunexported identifier should not begin with an underscore

internal/flock/filesystem_lock_windows.go:30:2

29 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx
30 _LOCKFILE_FAIL_IMMEDIATELY = 1
31 _LOCKFILE_EXCLUSIVE_LOCK = 2

internal/backend/remote-state/s3/backend_complete_test.go1

47:53unexported-returnexported function returns an unexported type

internal/backend/remote-state/s3/backend_complete_test.go:47:53

46
47func ExpectDiagsEqual(expected tfdiags.Diagnostics) diagsValidator {
48 return func(t *testing.T, diags tfdiags.Diagnostics) {

internal/legacy/tofu/state.go1

1293:20unnecessary-formatformatting call has no formatting directive

internal/legacy/tofu/state.go:1293:20

1292 if len(rs.Dependencies) > 0 {
1293 buf.WriteString(fmt.Sprintf("\n Dependencies:\n"))
1294 for _, dep := range rs.Dependencies {

internal/backend/init/testing.go1

148:33unused-parameterparameter ctx is unused

internal/backend/init/testing.go:148:33

147// Configure implements Backend.
148func (m *MockBackend) Configure(ctx context.Context, configObj cty.Value) tfdiags.Diagnostics {
149 m.ConfigureCalled = true

cmd/tofu/main_test.go1

289:7unused-receiverreceiver c is unused

cmd/tofu/main_test.go:289:7

288
289func (c *testCommandCLI) Synopsis() string { return "" }
290func (c *testCommandCLI) Help() string { return "" }

internal/backend/remote-state/consul/backend_test.go1

60:114use-anyuse any instead of interface{}

internal/backend/remote-state/consul/backend_test.go:60:114

59 // Get the backend. We need two to test locking.
60 b1 := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
61 "address": srv.HTTPAddr,

internal/addrs/instance_key.go1

50:17use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/addrs/instance_key.go:50:17

49 default:
50 return NoKey, fmt.Errorf("either a string or an integer is required")
51 }

internal/encryption/enctest/setup.go1

105:3use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

internal/encryption/enctest/setup.go:105:3

104 for _, d := range diags {
105 println(d.Error())
106 }

internal/addrs/resource_test.go1

677:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/addrs/resource_test.go:677:2

676 got := []Resource{managed, data, ephemeral, managed, ephemeral, data}
677 sort.SliceStable(got, func(i, j int) bool { return got[i].Less(got[j]) })
678

internal/cloud/backend_taskStage_taskResults.go1

99:41var-declarationomit the explicit zero value from the variable declaration

internal/cloud/backend_taskStage_taskResults.go:99:41

98 // Track the first task name that is a mandatory enforcement level breach.
99 var firstMandatoryTaskFailed *string = nil
100

internal/backend/remote-state/azure/auth/msi_auth.go1

63:7var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/auth/msi_auth.go:63:7

62
63const MSI_ENDPOINT string = "MSI_ENDPOINT"
64

internal/communicator/ssh/communicator_test.go1

103:4waitgroup-add-inside-goroutinecall WaitGroup.Add before starting the goroutine to avoid racing with Wait

internal/communicator/ssh/communicator_test.go:103:4

102 for newChannel := range chans {
103 wg.Add(1)
104 channel, requests, err := newChannel.Accept()

internal/backend/remote-state/consul/client.go1

116:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/consul/client.go:116:9

115
116 md5 := md5.Sum(payload)
117

cmd/tofu/main_test.go1

55:37add-constantstring literal "bar" appears more than twice; define a constant

cmd/tofu/main_test.go:55:37

54 "both env var and CLI",
55 []string{testCommandName, "foo", "bar"},
56 "-foo baz",

internal/legacy/tofu/util.go1

65:19append-to-sized-sliceresult already has a positive length; use make with length zero and capacity, or reslice to zero before append

internal/legacy/tofu/util.go:65:19

64 if s[i] != result[len(result)-1] {
65 result = append(result, s[i])
66 }

internal/legacy/helper/schema/shims_test.go1

3375:44argument-overwritten-before-useargument v is overwritten before its incoming value is used

internal/legacy/helper/schema/shims_test.go:3375:44

3374 },
3375 CustomizeDiff: func(diff *ResourceDiff, v interface{}) error {
3376 v, ok := diff.GetOk("unrelated_set")

internal/lang/eval/internal/tofu2024/doc.go1

23:2blank-importsblank import should be justified by a comment

internal/lang/eval/internal/tofu2024/doc.go:23:2

22import (
23 _ "github.com/opentofu/opentofu/internal/configs"
24)

internal/backend/remote-state/azure/backend_test.go1

54:5boolean-literal-comparisonomit the boolean literal from the logical expression

internal/backend/remote-state/azure/backend_test.go:54:5

53 }
54 if b.snapshot != false {
55 t.Fatalf("Incorrect snapshot was populated")

internal/backend/local/testing.go1

50:3call-to-gcavoid explicit garbage collection

internal/backend/local/testing.go:50:3

49 // on Windows.
50 runtime.GC()
51 })

cmd/tofu/main.go1

53:6cognitive-complexityfunction has cognitive complexity 50; maximum is 7

cmd/tofu/main.go:53:6

52
53func realMain() int {
54 defer logging.PanicHandler()

internal/backend/local/backend_local.go1

49:17confusing-namingname localRun differs from LocalRun only by capitalization

internal/backend/local/backend_local.go:49:17

48
49func (b *Local) localRun(ctx context.Context, stopCtx context.Context, op *backend.Operation) (*backend.LocalRun, *configload.Snapshot, statemgr.Full, tfdiags.Diagnostics) {
50 var diags tfdiags.Diagnostics

internal/backend/remote-state/oss/backend.go1

456:144confusing-resultsadjacent unnamed results of the same type should be named

internal/backend/remote-state/oss/backend.go:456:144

455
456func getAssumeRoleAK(accessKey, secretKey, stsToken, region, roleArn, sessionName, policy, stsEndpoint string, sessionExpiration int) (string, string, string, error) {
457 request := sts.CreateAssumeRoleRequest()

internal/command/cliconfig/ociauthconfig/credentials_source.go1

19:6constructor-interface-returnNewStaticCredentialsSource returns interface CredentialsSource although its concrete result is consistently *staticCredentialsSource; return the concrete type

internal/command/cliconfig/ociauthconfig/credentials_source.go:19:6

18
19func NewStaticCredentialsSource(creds Credentials, spec CredentialsSpecificity) CredentialsSource {
20 return &staticCredentialsSource{

internal/backend/local/backend.go1

356:12context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend.go:356:12

355 stopCtx context.Context,
356 cancelCtx context.Context,
357 tfCtx *tofu.Context,

internal/builtin/provisioners/file/resource_provisioner.go1

35:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/builtin/provisioners/file/resource_provisioner.go:35:2

34 // This allows the Stop method to cancel any in-flight requests.
35 ctx context.Context
36 cancel context.CancelFunc

internal/addrs/checkable.go1

96:6cyclomatic-complexityfunction complexity is 12; maximum is 10

internal/addrs/checkable.go:96:6

95// results between runs.
96func ParseCheckableStr(kind CheckableKind, src string) (Checkable, tfdiags.Diagnostics) {
97 var diags tfdiags.Diagnostics

internal/backend/remote-state/inmem/backend_test.go1

25:2deep-exitprocess-exit calls should be confined to main or init

internal/backend/remote-state/inmem/backend_test.go:25:2

24 flag.Parse()
25 os.Exit(m.Run())
26}

internal/backend/remote-state/gcs/backend_test.go1

465:36deprecated-api-usagegoogle.golang.org/api/option.WithCredentialsJSON is deprecated: This function is being deprecated because of a potential security risk.

internal/backend/remote-state/gcs/backend_test.go:465:36

464 // closely as possible.
465 credOptions = append(credOptions, option.WithCredentialsJSON([]byte(contents)))
466 opts = append(opts, credOptions...)

cmd/tofu/provider_source_test.go1

182:11discarded-error-resulterror result returned by w.Write is discarded

cmd/tofu/provider_source_test.go:182:11

181 case "/providers/v1/test/exists/0.0.0/download/foo_os/bar_arch":
182 _, _ = w.Write([]byte(`{"os":"foo_os","arch":"bar_arch","download_url":"/providers/v1/test/exists_0.0.0.zip","shasum":"4cbc33c22abdebe3a3679666d4052ec95c40bd8904a9458f90cf934363a14cc7"}`))
183 case "/providers/v1/test/exists_0.0.0.zip":

internal/addrs/check_rule.go1

84:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/check_rule.go:84:1

83// describe the type of object being checked rather than the type of the check
84// itself.)
85type CheckRuleType int

internal/addrs/provider_config.go1

196:3early-returninvert the condition and return early to reduce nesting

internal/addrs/provider_config.go:196:3

195 if len(remain) > 2 {
196 if tt, ok := remain[2].(hcl.TraverseAttr); ok {
197 ret.Alias = tt.Name

internal/plugin/convert/schema.go1

141:2enforce-switch-styledefault clause should be the last switch clause

internal/plugin/convert/schema.go:141:2

140 switch k {
141 default:
142 return proto.StringKind_PLAIN

cmd/tofu/main.go1

421:42error-stringserror string should not be capitalized or end with punctuation

cmd/tofu/main.go:421:42

420 if err != nil {
421 return unmanagedProviders, fmt.Errorf("Invalid format for TF_REATTACH_PROVIDERS: %w", err)
422 }

internal/command/meta_providers.go1

495:6error-type-namingerror implementation type should have an Error suffix

internal/command/meta_providers.go:495:6

494// to return a more helpful error message.
495type providerPluginErrors map[addrs.Provider]error
496

internal/communicator/ssh/communicator_test.go1

845:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

internal/communicator/ssh/communicator_test.go:845:3

844 return func(_ ssh.ConnMetadata, inkey ssh.PublicKey) (*ssh.Permissions, error) {
845 goodkey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(keystr))
846 if err != nil {

cmd/tofu/version.go1

17:5exported-declaration-commentexported declaration should have a comment beginning with its name

cmd/tofu/version.go:17:5

16
17var Version = version.Version
18

internal/addrs/module_instance.go1

1:1file-length-limitfile has 589 lines; maximum is 500

internal/addrs/module_instance.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/backend/remote-state/cos/client.go1

331:58flag-parameterboolean parameter recursive controls function flow

internal/backend/remote-state/cos/client.go:331:58

330// deleteBucket delete cos bucket
331func (c *remoteClient) deleteBucket(ctx context.Context, recursive bool) error {
332 if recursive {

cmd/tofu/help.go1

1:1formatfile is not formatted

cmd/tofu/help.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/help.go`

cmd/tofu/main.go1

53:6function-lengthfunction has 131 statements and 305 lines; maximum is 50 statements or 75 lines

cmd/tofu/main.go:53:6

52
53func realMain() int {
54 defer logging.PanicHandler()

internal/backend/remote-state/consul/client.go1

686:24function-result-limitfunction returns 5 values; maximum is 3

internal/backend/remote-state/consul/client.go:686:24

685
686func (c *RemoteClient) chunkedMode() (bool, string, []string, *consulapi.KVPair, error) {
687 kv := c.Client.KV()

internal/addrs/instance_key.go1

140:2identical-switch-branchesswitch repeats a case body

internal/addrs/instance_key.go:140:2

139 return cty.UnknownVal(cty.String).RefineNotNull()
140 default: // (only UnknownKeyType should be left to handle here)
141 // If we don't even know what type of instance key we're expecting

cmd/tofu/main.go1

36:2import-alias-namingimport alias should contain lower-case letters and digits

cmd/tofu/main.go:36:2

35
36 backendInit "github.com/opentofu/opentofu/internal/backend/init"
37)

cmd/tofu/provider_source_test.go1

258:4import-shadowingidentifier disco shadows an imported package

cmd/tofu/provider_source_test.go:258:4

257 defer server.Close()
258 disco := disco.New(disco.WithHTTPClient(server.Client()))
259 disco.ForceHostServices("local.testing", map[string]any{

internal/legacy/hcl2shim/values.go1

160:29impossible-integer-comparisoncomparison is always true for type int64

internal/legacy/hcl2shim/values.go:160:29

159 const MinInt = -MaxInt - 1
160 if i <= int64(MaxInt) && i >= int64(MinInt) {
161 return int(i) // Like HCL token.NUMBER

internal/cloud/backend_context.go1

136:8inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/cloud/backend_context.go:136:8

135 if _, ok := op.Variables[v.Key]; !ok {
136 op.Variables[v.Key] = &remoteStoredVariableValue{
137 definition: v,

internal/builtin/provisioners/local-exec/resource_provisioner_test.go1

327:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/builtin/provisioners/local-exec/resource_provisioner_test.go:327:9

326 } {
327 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
328

internal/addrs/module_source_test.go1

269:28insecure-url-schemeURL uses insecure http scheme

internal/addrs/module_source_test.go:269:28

268 want: ModuleSourceRemote{
269 Package: ModulePackage("http://example.com/module"),
270 },

internal/command/views/backend_remote.go1

17:20interface-method-limitinterface has 20 methods, exceeding the configured design limit of 10

internal/command/views/backend_remote.go:17:20

16
17type BackendRemote interface {
18 Basic

internal/backend/remote/backend_common.go1

129:8max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_common.go:129:8

128 if !found {
129 if r.ID == item.ID {
130 found = true

internal/backend/remote-state/oss/backend.go1

456:6max-parametersfunction has 9 parameters; maximum is 8

internal/backend/remote-state/oss/backend.go:456:6

455
456func getAssumeRoleAK(accessKey, secretKey, stsToken, region, roleArn, sessionName, policy, stsEndpoint string, sessionExpiration int) (string, string, string, error) {
457 request := sts.CreateAssumeRoleRequest()

internal/cloud/tfe_client_mock.go1

571:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:571:6

570
571type MockPlans struct {
572 client *MockClient

internal/addrs/module_source.go1

163:3modifies-parameterassignment modifies parameter raw

internal/addrs/module_source.go:163:3

162 // package, not physical filesystem paths.
163 raw = strings.ReplaceAll(raw, `\`, "/")
164 }

internal/addrs/set.go1

55:2modifies-value-receiverassignment modifies value receiver s

internal/addrs/set.go:55:2

54func (s Set[T]) Add(addr T) {
55 s[addr.UniqueKey()] = addr
56}

cmd/tofu/commands.go1

465:30nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/commands.go:465:30

464
465 hiddenCommands = map[string]struct{}{
466 "env": {},

internal/backend/remote-state/cos/client.go1

336:5nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/cos/client.go:336:5

335 if strings.Contains(err.Error(), "not exists") {
336 return nil
337 }

internal/backend/remote-state/azure/client.go1

70:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/azure/client.go:70:3

69 if len(data) == 0 {
70 return nil, nil
71 }

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

260:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

internal/builtin/provisioners/remote-exec/resource_provisioner.go:260:3

259 errR, errW := io.Pipe()
260 defer outW.Close()
261 defer errW.Close()

internal/addrs/provider_config.go1

445:5no-else-after-returnremove else and unindent its body after the return

internal/addrs/provider_config.go:445:5

444 return fmt.Sprintf("%s.%s.%s", "provider", pc.Provider.LegacyString(), pc.Alias)
445 } else {
446 return fmt.Sprintf("%s.%s.%s.%s", pc.Module.String(), "provider", pc.Provider.LegacyString(), pc.Alias)

internal/builtin/providers/tf/provider_test.go1

12:6no-initreplace init with explicit initialization

internal/builtin/providers/tf/provider_test.go:12:6

11
12func init() {
13 // Initialize the backends

internal/addrs/module_source_test.go1

679:2no-naked-returnreturn values must be explicit

internal/addrs/module_source_test.go:679:2

678 }
679 return
680}

cmd/tofu/commands.go1

44:5no-package-varpackage variables introduce mutable global state

cmd/tofu/commands.go:44:5

43// HiddenCommands set appears under "all other commands".
44var primaryCommands []string
45

internal/lang/eval/internal/tofu2024/compile_functions.go1

71:3overwritten-before-usethis value of providerMarks is overwritten before use

internal/lang/eval/internal/tofu2024/compile_functions.go:71:3

70 maybeProvider, err := configgraph.ProviderInstanceFromValue(pv, reqdProvider.Type)
71 maybeProvider, providerMarks := maybeProvider.Unmark()
72 if err != nil {

cmd/tofu/experiments.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/experiments.go:6:9

5
6package main
7

internal/command/jsonformat/structured/attribute_path/matcher_test.go2

6:9package-directory-mismatchpackage attribute_path does not match directory attribute_path

internal/command/jsonformat/structured/attribute_path/matcher_test.go:6:9

5
6package attribute_path
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/command/jsonformat/structured/attribute_path/matcher_test.go:6:9

5
6package attribute_path
7

internal/addrs/move_endpoint_module_test.go1

1338:17range-value-addresstaking the address of range value test can be misleading

internal/addrs/move_endpoint_module_test.go:1338:17

1337 func(t *testing.T) {
1338 endpoint := &MoveEndpointInModule{
1339 relSubject: test.Endpoint,

internal/legacy/tofu/resource_address.go1

432:7receiver-namingreceiver name addr is inconsistent with r

internal/legacy/tofu/resource_address.go:432:7

431// addrs.ModuleInstance value.
432func (addr *ResourceAddress) ModuleInstanceAddr() addrs.ModuleInstance {
433 path := make(addrs.ModuleInstance, len(addr.Path))

internal/addrs/module_source_resolve.go1

61:2redefines-builtin-ididentifier new shadows a predeclared identifier

internal/addrs/module_source_resolve.go:61:2

60func joinModuleSourceSubPath(subPath, rel string) (string, error) {
61 new := path.Join(subPath, rel)
62 if new == "." {

internal/addrs/instance_key_test.go1

23:4redundant-conversionconversion from IntKey to the identical type is redundant

internal/addrs/instance_key_test.go:23:4

22 {
23 IntKey(5),
24 `[5]`,

internal/backend/remote-state/s3/backend_test.go1

25:2redundant-import-aliasimport alias is identical to the package name

internal/backend/remote-state/s3/backend_test.go:25:2

24 "github.com/aws/aws-sdk-go-v2/service/s3"
25 types "github.com/aws/aws-sdk-go-v2/service/s3/types"
26 "github.com/google/go-cmp/cmp"

internal/legacy/helper/schema/field_writer_map.go1

153:10simplify-rangeomit the blank range value

internal/legacy/helper/schema/field_writer_map.go:153:10

152 if err != nil {
153 for i, _ := range vs {
154 is := strconv.FormatInt(int64(i), 10)

internal/addrs/move_endpoint_module.go1

358:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:358:3

357 case AbsModuleCall, ModuleInstance:
358 switch eSub.(type) {
359 case AbsModuleCall, ModuleInstance:

cmd/tofu/provider_source.go1

197:6slice-preallocationpreallocate directExcluded with capacity len(range source) before appending once per iteration

cmd/tofu/provider_source.go:197:6

196 // looked up via the registry source we're about to construct.
197 var directExcluded getproviders.MultiSourceMatchingPatterns
198 for addr := range foundLocally {

internal/command/cliconfig/credentials_test.go1

57:31standard-http-method-constantreplace the HTTP method literal with http.MethodGet

internal/command/cliconfig/credentials_test.go:57:31

56
57 req, err := http.NewRequest("GET", "http://example.com/", nil)
58 if err != nil {

cmd/tofu/module_source.go2

17:2task-commentTODO comment should be resolved or linked to an owned work item

cmd/tofu/module_source.go:17:2

16func remoteModulePackageFetcher(ctx context.Context, getOCICredsPolicy oci.OCICredsPolicyBuilder) *getmodules.PackageFetcher {
17 // TODO: Pass in a real getmodules.PackageFetcherEnvironment here,
18 // which knows how to make use of the OCI authentication policy.
24:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

cmd/tofu/module_source.go:24:1

23
24type modulePackageFetcherEnvironment struct {
25 getOCICredsPolicy oci.OCICredsPolicyBuilder

internal/addrs/check_rule_diagnostic_test.go1

29:66unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/check_rule_diagnostic_test.go:29:66

28
29 if overridden[0].ExtraInfo().(*CheckRuleDiagnosticExtra).wrapped.(string) != "extra" {
30 t.Errorf("unexpected extra info: %v", overridden[0].ExtraInfo())

internal/command/webbrowser/mock.go1

117:3unclosed-http-response-bodylocally acquired HTTP response body is not directly closed or transferred before replacement or function exit

internal/command/webbrowser/mock.go:117:3

116 }
117 resp, err := l.Client.Do(req)
118 if err != nil {

internal/flock/filesystem_lock_windows.go1

31:2unexported-namingunexported identifier should not begin with an underscore

internal/flock/filesystem_lock_windows.go:31:2

30 _LOCKFILE_FAIL_IMMEDIATELY = 1
31 _LOCKFILE_EXCLUSIVE_LOCK = 2
32 // https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-

internal/backend/remote-state/s3/backend_complete_test.go1

59:86unexported-returnexported function returns an unexported type

internal/backend/remote-state/s3/backend_complete_test.go:59:86

58// ExpectDiagsMatching returns a validator expecting a single Diagnostic with fields matching the expectation
59func ExpectDiagsMatching(severity tfdiags.Severity, summary matcher, detail matcher) diagsValidator {
60 return func(t *testing.T, diags tfdiags.Diagnostics) {

internal/backend/local/backend_apply_test.go1

342:63unused-parameterparameter name is unused

internal/backend/local/backend_apply_test.go:342:63

341
342func (b *backendWithFailingState) StateMgr(_ context.Context, name string) (statemgr.Full, error) {
343 return &failingState{

cmd/tofu/main_test.go1

290:7unused-receiverreceiver c is unused

cmd/tofu/main_test.go:290:7

289func (c *testCommandCLI) Synopsis() string { return "" }
290func (c *testCommandCLI) Help() string { return "" }
291

internal/backend/remote-state/consul/backend_test.go1

65:114use-anyuse any instead of interface{}

internal/backend/remote-state/consul/backend_test.go:65:114

64
65 b2 := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
66 "address": srv.HTTPAddr,

internal/backend/local/backend_local.go1

92:24use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local.go:92:24

91 if op.PlanFile.IsCloud() {
92 diags = diags.Append(fmt.Errorf("error: using a saved cloud plan when executing OpenTofu locally is not supported"))
93 return nil, nil, nil, diags

internal/encryption/example_test.go1

99:3use-fmt-printuse fmt.Print or fmt.Println instead of the builtin

internal/encryption/example_test.go:99:3

98 for _, d := range diags {
99 println(d.Error())
100 }

internal/command/format/diagnostic.go1

320:4use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/format/diagnostic.go:320:4

319 copy(values, snippet.Values)
320 sort.Slice(values, func(i, j int) bool {
321 return values[i].Traversal < values[j].Traversal

internal/command/command.go1

15:17var-declarationomit the explicit zero value from the variable declaration

internal/command/command.go:15:17

14// Set to true when we're testing
15var test bool = false
16

internal/backend/remote-state/azure/backend_test.go1

122:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:122:2

121func (p mockClient) NewListBlobsFlatPager(params *container.ListBlobsFlatOptions) *runtime.Pager[container.ListBlobsFlatResponse] {
122 env_name := "env-name"
123 blobDetails := make([]*container.BlobItem, 5000)

internal/backend/remote-state/consul/client.go1

269:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/consul/client.go:269:9

268
269 md5 := md5.Sum(data)
270 chunks := split(payload, 524288)

cmd/tofu/main_test.go1

73:13add-constantstring literal "-foo" appears more than twice; define a constant

cmd/tofu/main_test.go:73:13

72 "-foo bar",
73 []string{"-foo", "bar", "bar", "", "baz"},
74 false,

internal/registry/client.go1

276:16append-to-sized-sliceparts already has a positive length; use make with length zero and capacity, or reslice to zero before append

internal/registry/client.go:276:16

275 parts[2] = packageAddr.TargetSystem
276 parts = append(parts, subComponents...)
277 relPath := path.Join(parts...)

version/version.go1

13:2blank-importsblank import should be justified by a comment

version/version.go:13:2

12import (
13 _ "embed"
14 "fmt"

internal/cloud/backend_plan_test.go1

399:6boolean-literal-comparisonomit the boolean literal from the logical expression

internal/cloud/backend_plan_test.go:399:6

398 for _, configVersion := range configVersionsAPI.configVersions {
399 if configVersion.Provisional != true {
400 t.Errorf("wrong Provisional setting in the created configuration version\ngot %v, expected %v", configVersion.Provisional, true)

internal/command/apply_test.go1

768:2call-to-gcavoid explicit garbage collection

internal/command/apply_test.go:768:2

767 // to avoid TempDir RemoveAll cleanup errors on Windows.
768 runtime.GC()
769}

cmd/tofu/main.go1

405:6cognitive-complexityfunction has cognitive complexity 19; maximum is 7

cmd/tofu/main.go:405:6

404// JSON-encoded environment variable.
405func parseReattachProviders(in string) (map[addrs.Provider]*plugin.ReattachConfig, error) {
406 unmanagedProviders := map[addrs.Provider]*plugin.ReattachConfig{}

internal/backend/remote-state/azure/auth/clients.go1

218:6confusing-namingname newContainerClientFromStorageAccessKey differs from NewContainerClientFromStorageAccessKey only by capitalization

internal/backend/remote-state/azure/auth/clients.go:218:6

217
218func newContainerClientFromStorageAccessKey(client *http.Client, names StorageAddresses, storageAccessKey string) (*container.Client, string, error) {
219 sharedKeyCredential, err := container.NewSharedKeyCredential(names.StorageAccount, storageAccessKey)

internal/backend/remote-state/oss/backend.go1

456:152confusing-resultsadjacent unnamed results of the same type should be named

internal/backend/remote-state/oss/backend.go:456:152

455
456func getAssumeRoleAK(accessKey, secretKey, stsToken, region, roleArn, sessionName, policy, stsEndpoint string, sessionExpiration int) (string, string, string, error) {
457 request := sts.CreateAssumeRoleRequest()

internal/command/cliconfig/ociauthconfig/credentials_source.go1

26:6constructor-interface-returnNewDockerCredentialHelperCredentialsSource returns interface CredentialsSource although its concrete result is consistently *dockerCredentialHelperCredentialSource; return the concrete type

internal/command/cliconfig/ociauthconfig/credentials_source.go:26:6

25
26func NewDockerCredentialHelperCredentialsSource(helperName string, serverURL string, spec CredentialsSpecificity) CredentialsSource {
27 return &dockerCredentialHelperCredentialSource{

internal/backend/local/backend_apply.go1

56:12context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend_apply.go:56:12

55 stopCtx context.Context,
56 cancelCtx context.Context,
57 op *backend.Operation,

internal/builtin/provisioners/local-exec/resource_provisioner.go1

45:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/builtin/provisioners/local-exec/resource_provisioner.go:45:2

44 // This allows the Stop method to cancel any in-flight requests.
45 ctx context.Context
46 cancel context.CancelFunc

internal/addrs/instance_key.go1

219:6cyclomatic-complexityfunction complexity is 13; maximum is 10

internal/addrs/instance_key.go:219:6

218// - Escaping anything that would be treated as a template interpolation or control sequence.
219func toHCLQuotedString(s string) string {
220 // This is an adaptation of a similar function inside the hclwrite package,

internal/backend/remote/remote_test.go1

29:2deep-exitprocess-exit calls should be confined to main or init

internal/backend/remote/remote_test.go:29:2

28
29 os.Exit(m.Run())
30}

internal/cloud/tfe_client_mock.go1

501:97deprecated-api-usagegithub.com/hashicorp/go-tfe.DataRetentionPolicy is deprecated: Use DataRetentionPolicyDeleteOlder instead. This is the original representation of a data retention policy, only present in TFE v202311-1 and v202312-1

internal/cloud/tfe_client_mock.go:501:97

500
501func (m *MockOrganizations) ReadDataRetentionPolicy(ctx context.Context, organization string) (*tfe.DataRetentionPolicy, error) {
502 panic("not implemented")

internal/backend/backend_test.go1

26:2discarded-error-resulterror result returned by f.Close is discarded

internal/backend/backend_test.go:26:2

25 }
26 f.Close()
27

internal/addrs/for_each_attr.go1

9:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/for_each_attr.go:9:1

8// ForEachAttr is the address of an attribute referencing the current "for_each" object in
9// the interpolation scope, addressed using the "each" keyword, ex. "each.key" and "each.value"
10type ForEachAttr struct {

internal/addrs/provider_config.go1

210:3early-returninvert the condition and return early to reduce nesting

internal/addrs/provider_config.go:210:3

209 if len(remain) > 3 {
210 if tt, ok := remain[3].(hcl.TraverseIndex); ok {
211 var keyErr error

internal/plugin/convert/schema.go1

232:2enforce-switch-styledefault clause should be the last switch clause

internal/plugin/convert/schema.go:232:2

231 switch k {
232 default:
233 return configschema.StringPlain

cmd/tofu/main.go1

426:43error-stringserror string should not be capitalized or end with punctuation

cmd/tofu/main.go:426:43

425 if diags.HasErrors() {
426 return unmanagedProviders, fmt.Errorf("Error parsing %q as a provider address: %w", a, diags.Err())
427 }

internal/command/show.go1

35:6error-type-namingerror implementation type should have an Error suffix

internal/command/show.go:35:6

34// that! So, we have to do a couple ourselves if we want to preserve that data.
35type errUnusableDataMisc struct {
36 inner error

internal/communicator/ssh/provisioner.go1

410:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

internal/communicator/ssh/provisioner.go:410:2

409 // guaranteed to be a certificate.
410 maybeCert, _, _, _, err := ssh.ParseAuthorizedKey([]byte(certificate))
411 if err != nil {

cmd/tofu/version.go1

19:5exported-declaration-commentexported declaration should have a comment beginning with its name

cmd/tofu/version.go:19:5

18
19var VersionPrerelease = version.Prerelease
20

internal/addrs/module_source_test.go1

1:1file-length-limitfile has 681 lines; maximum is 500

internal/addrs/module_source_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/backend/remote-state/s3/client.go1

617:34flag-parameterboolean parameter skipS3Checksum controls function flow

internal/backend/remote-state/s3/client.go:617:34

616// More details about the feature: https://docs.aws.amazon.com/sdkref/latest/guide/feature-dataintegrity.html
617func s3optDisableDefaultChecksum(skipS3Checksum bool) func(*s3.Options) {
618 if skipS3Checksum {

cmd/tofu/main.go1

1:1formatfile is not formatted

cmd/tofu/main.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/main.go`

cmd/tofu/main_test.go1

19:6function-lengthfunction has 10 statements and 131 lines; maximum is 50 statements or 75 lines

cmd/tofu/main_test.go:19:6

18
19func TestMain_cliArgsFromEnv(t *testing.T) {
20 // Set up the state. This test really messes with the environment and

internal/backend/remote-state/cos/client.go1

188:24function-result-limitfunction returns 4 values; maximum is 3

internal/backend/remote-state/cos/client.go:188:24

187// getObject get remote object
188func (c *remoteClient) getObject(ctx context.Context, cosFile string) (exists bool, data []byte, checksum string, err error) {
189 rsp, err := c.cosClient.Object.Get(ctx, cosFile, nil)

internal/addrs/instance_key.go1

158:2identical-switch-branchesswitch repeats a case body

internal/addrs/instance_key.go:158:2

157 return true
158 case j == NoKey:
159 return false

internal/backend/init/init.go1

17:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:17:2

16 "github.com/opentofu/opentofu/internal/backend"
17 backendLocal "github.com/opentofu/opentofu/internal/backend/local"
18 backendRemote "github.com/opentofu/opentofu/internal/backend/remote"

internal/backend/local/backend.go1

94:2import-shadowingidentifier encryption shadows an imported package

internal/backend/local/backend.go:94:2

93
94 encryption encryption.StateEncryption
95}

internal/command/jsonconfig/expression.go1

154:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/command/jsonconfig/expression.go:154:5

153 if _, exists := ret[typeName]; !exists {
154 ret[typeName] = make([]map[string]any, 0, 1)
155 }

internal/builtin/provisioners/remote-exec/resource_provisioner_test.go1

317:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/builtin/provisioners/remote-exec/resource_provisioner_test.go:317:9

316 } {
317 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
318

internal/backend/remote-state/http/backend_test.go1

27:28insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:27:28

26 conf := map[string]cty.Value{
27 "address": cty.StringVal("http://127.0.0.1:8888/foo"),
28 }

internal/command/views/init.go1

17:11interface-method-limitinterface has 26 methods, exceeding the configured design limit of 10

internal/command/views/init.go:17:11

16
17type Init interface {
18 CopyFromModule(src string)

internal/backend/remote/backend_common.go1

136:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_common.go:136:7

135 // If the run is in a final state, ignore it and continue.
136 switch item.Status {
137 case tfe.RunApplied, tfe.RunCanceled, tfe.RunDiscarded, tfe.RunErrored:

internal/lang/eval/internal/tofu2024/compile_resources.go1

26:6max-parametersfunction has 11 parameters; maximum is 8

internal/lang/eval/internal/tofu2024/compile_resources.go:26:6

25
26func compileModuleInstanceResources(
27 ctx context.Context,

internal/cloud/tfe_client_mock.go1

683:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:683:6

682
683type MockTaskStages struct {
684 client *MockClient

internal/addrs/module_source.go1

281:2modifies-parameterassignment modifies parameter raw

internal/addrs/module_source.go:281:2

280 var subDir string
281 raw, subDir = getmodules.SplitPackageSubdir(raw)
282 if strings.HasPrefix(subDir, "../") {

internal/backend/remote-state/azure/backend_test.go1

137:4modifies-value-receiverassignment modifies value receiver p

internal/backend/remote-state/azure/backend_test.go:137:4

136 prevMarker := p.marker
137 p.marker = returnMarker
138 return container.ListBlobsFlatResponse{

cmd/tofu/commands.go1

474:30nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/commands.go:474:30

473// A message will be sent on the channel for every interrupt received.
474func makeShutdownCh() <-chan struct{} {
475 resultCh := make(chan struct{})

internal/backend/remote-state/gcs/client.go1

38:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/gcs/client.go:38:4

37 if errors.Is(err, storage.ErrObjectNotExist) {
38 return nil, nil
39 } else {

internal/backend/remote-state/azure/client.go1

357:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/azure/client.go:357:3

356 if keyB64 == "" {
357 return nil, nil
358 }

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

261:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

internal/builtin/provisioners/remote-exec/resource_provisioner.go:261:3

260 defer outW.Close()
261 defer errW.Close()
262

internal/addrs/provider_config_test.go1

176:6no-else-after-returnremove else and unindent its body after the return

internal/addrs/provider_config_test.go:176:6

175 return
176 } else {
177 if len(diags) != 0 {

internal/command/cliconfig/registry_protocols.go1

192:6no-initreplace init with explicit initialization

internal/command/cliconfig/registry_protocols.go:192:6

191
192func init() {
193 // BuiltinConfig should contain the default values for a registry_protocols

internal/backend/local/backend.go1

400:2no-naked-returnreturn values must be explicit

internal/backend/local/backend.go:400:2

399 }
400 return
401}

cmd/tofu/commands.go1

54:5no-package-varpackage variables introduce mutable global state

cmd/tofu/commands.go:54:5

53// hiddenCommands set, because that would be rather silly.
54var hiddenCommands map[string]struct{}
55

internal/legacy/tofu/state.go1

442:5overwritten-before-usethis value of is is overwritten before use

internal/legacy/tofu/state.go:442:5

441 // Found it, remove it
442 is, is[len(is)-1] = append(is[:i], is[i+1:]...), nil
443

cmd/tofu/help.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/help.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/compliance_test.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/compliance_test.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/compliance_test.go:6:9

5
6package aws_kms
7

internal/addrs/move_endpoint_module_test.go1

1343:14range-value-addresstaking the address of range value test can be misleading

internal/addrs/move_endpoint_module_test.go:1343:14

1342
1343 other := &MoveEndpointInModule{
1344 relSubject: test.Other,

internal/legacy/tofu/resource_address.go1

446:7receiver-namingreceiver name addr is inconsistent with r

internal/legacy/tofu/resource_address.go:446:7

445// an indexed resource instance is contained with the unindexed resource, etc.
446func (addr *ResourceAddress) Contains(other *ResourceAddress) bool {
447 ourPath := addr.Path

internal/backend/remote-state/cos/backend.go1

192:29redefines-builtin-ididentifier min shadows a predeclared identifier

internal/backend/remote-state/cos/backend.go:192:29

191
192func validateIntegerInRange(min, max int64) schema.SchemaValidateFunc {
193 return func(v interface{}, k string) (ws []string, errors []error) {

internal/addrs/instance_key_test.go1

27:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:27:4

26 {
27 StringKey(""),
28 `[""]`,

internal/backend/remote-state/s3/client.go1

27:2redundant-import-aliasimport alias is identical to the package name

internal/backend/remote-state/s3/client.go:27:2

26 "github.com/aws/aws-sdk-go-v2/service/s3"
27 types "github.com/aws/aws-sdk-go-v2/service/s3/types"
28 multierror "github.com/hashicorp/go-multierror"

internal/legacy/helper/schema/field_writer_map.go1

234:11simplify-rangeomit the blank range value

internal/legacy/helper/schema/field_writer_map.go:234:11

233 if err != nil {
234 for k1, _ := range v {
235 w.set(append(addrCopy, k1), nil)

internal/addrs/move_endpoint_module.go2

366:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:366:3

365 case AbsResource:
366 switch eSub := eSub.(type) {
367 case AbsResource:
225:6slice-preallocationpreallocate inst with capacity len(range source) before appending once per iteration

internal/addrs/move_endpoint_module.go:225:6

224func (e *MoveEndpointInModule) synthModuleInstance() ModuleInstance {
225 var inst ModuleInstance
226

internal/command/cliconfig/credentials_test.go1

230:31standard-http-method-constantreplace the HTTP method literal with http.MethodGet

internal/command/cliconfig/credentials_test.go:230:31

229
230 req, err := http.NewRequest("GET", "http://example.com/", nil)
231 if err != nil {

internal/addrs/module_source_resolve.go1

14:1task-commentFIXME comment should be resolved or linked to an owned work item

internal/addrs/module_source_resolve.go:14:1

13
14// FIXME: Everything in here should have unit tests
15

internal/addrs/check.go1

55:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/check.go:55:1

54// a check block within the entire configuration.
55type ConfigCheck struct {
56 Module Module

internal/addrs/instance_key.go1

167:15unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/instance_key.go:167:15

166 case iTy == IntKeyType:
167 return int(i.(IntKey)) < int(j.(IntKey))
168 case iTy == StringKeyType:

internal/flock/filesystem_lock_windows.go1

135:6unexported-namingunexported identifier should not begin with an underscore

internal/flock/filesystem_lock_windows.go:135:6

134func createEvent(sa *syscall.SecurityAttributes, manualReset bool, initialState bool, name *uint16) (handle syscall.Handle, err error) {
135 var _p0 uint32
136 if manualReset {

internal/backend/remote-state/s3/backend_complete_test.go1

81:85unexported-returnexported function returns an unexported type

internal/backend/remote-state/s3/backend_complete_test.go:81:85

80
81func ExpectDiagMatching(severity tfdiags.Severity, summary matcher, detail matcher) diagValidator {
82 return func(t *testing.T, d tfdiags.Diagnostic) {

internal/backend/local/backend_apply_test.go1

354:34unused-parameterparameter state is unused

internal/backend/local/backend_apply_test.go:354:34

353
354func (s failingState) WriteState(state *states.State) error {
355 return errors.New("fake failure")

internal/addrs/check.go1

49:7unused-receiverreceiver c is unused

internal/addrs/check.go:49:7

48
49func (c Check) uniqueKeySigil() {}
50

internal/backend/remote-state/consul/backend_test.go1

82:114use-anyuse any instead of interface{}

internal/backend/remote-state/consul/backend_test.go:82:114

81 // Get the backend. We need two to test locking.
82 b1 := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
83 "address": srv.HTTPAddr,

internal/backend/local/backend_local_test.go1

273:9use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:273:9

272func (b backendWithStateStorageThatFailsRefresh) DeleteWorkspace(_ context.Context, name string, force bool) error {
273 return fmt.Errorf("unimplemented")
274}

internal/command/jsonchecks/checks.go1

37:4use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonchecks/checks.go:37:4

36 }
37 sort.Slice(problems, func(i, j int) bool {
38 return problems[i].Message < problems[j].Message

internal/command/login_test.go1

53:46var-declarationomit the explicit zero value from the variable declaration

internal/command/login_test.go:53:46

52
53 var browserLauncher webbrowser.Launcher = nil
54 if useBrowserLauncher {

internal/backend/remote-state/azure/backend_test.go1

318:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:318:2

317
318 client_id := os.Getenv("TF_AZURE_TEST_CLIENT_ID")
319 client_secret := os.Getenv("TF_AZURE_TEST_CLIENT_SECRET")

internal/backend/remote-state/cos/backend_test.go1

270:63weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/cos/backend_test.go:270:63

269 unique := fmt.Sprintf("%s-%x", t.Name(), time.Now().UnixNano())
270 return fmt.Sprintf("terraform-test-%s-%s", fmt.Sprintf("%x", md5.Sum([]byte(unique)))[:10], "")
271}

cmd/tofu/main_test.go1

73:39add-constantstring literal "baz" appears more than twice; define a constant

cmd/tofu/main_test.go:73:39

72 "-foo bar",
73 []string{"-foo", "bar", "bar", "", "baz"},
74 false,

internal/cloud/backend_plan_test.go1

403:6boolean-literal-comparisonomit the boolean literal from the logical expression

internal/cloud/backend_plan_test.go:403:6

402
403 if configVersion.Speculative != false {
404 t.Errorf("wrong Speculative setting in the created configuration version\ngot %v, expected %v", configVersion.Speculative, false)

internal/command/command_test.go1

838:4call-to-gcavoid explicit garbage collection

internal/command/command_test.go:838:4

837 if runtime.GOOS == "windows" {
838 runtime.GC()
839 }

cmd/tofu/provider_source.go1

52:6cognitive-complexityfunction has cognitive complexity 10; maximum is 7

cmd/tofu/provider_source.go:52:6

51
52func explicitProviderSource(
53 ctx context.Context,

internal/backend/remote-state/consul/client.go1

393:24confusing-namingname lock differs from Lock only by capitalization

internal/backend/remote-state/consul/client.go:393:24

392// Only to be called while holding Client.mu
393func (c *RemoteClient) lock() (string, error) {
394 // We create a new session here, so it can be canceled when the lock is

internal/backend/remote-state/s3/backend.go1

1090:52confusing-resultsadjacent unnamed results of the same type should be named

internal/backend/remote-state/s3/backend.go:1090:52

1089
1090func boolAttrOk(obj cty.Value, name string) (bool, bool) {
1091 if val := obj.GetAttr(name); val.IsNull() {

internal/command/clistate/state.go1

87:6constructor-interface-returnNewLocker returns interface Locker although its concrete result is consistently *locker; return the concrete type

internal/command/clistate/state.go:87:6

86// reported to the user through the provided UI.
87func NewLocker(timeout time.Duration, view views.StateLocker) Locker {
88 return &locker{

internal/backend/local/backend_local.go1

34:55context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend_local.go:34:55

33// backend.Local implementation.
34func (b *Local) LocalRun(ctx context.Context, stopCtx context.Context, op *backend.Operation) (*backend.LocalRun, statemgr.Full, tfdiags.Diagnostics) {
35 // Make sure the type is invalid. We use this as a way to know not

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

39:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/builtin/provisioners/remote-exec/resource_provisioner.go:39:2

38 // This allows the Stop method to cancel any in-flight requests.
39 ctx context.Context
40 cancel context.CancelFunc

internal/addrs/map_test.go1

12:6cyclomatic-complexityfunction complexity is 21; maximum is 10

internal/addrs/map_test.go:12:6

11
12func TestMap(t *testing.T) {
13 variableName := InputVariable{Name: "name"}

internal/builtin/provisioners/remote-exec/resource_provisioner_test.go1

167:3deep-exitprocess-exit calls should be confined to main or init

internal/builtin/provisioners/remote-exec/resource_provisioner_test.go:167:3

166 if err != nil {
167 log.Fatal(err)
168 }

internal/cloud/tfe_client_mock.go1

509:102deprecated-api-usagegithub.com/hashicorp/go-tfe.DataRetentionPolicySetOptions is deprecated: Use DataRetentionPolicyDeleteOlder variations instead

internal/cloud/tfe_client_mock.go:509:102

508
509func (m *MockOrganizations) SetDataRetentionPolicy(ctx context.Context, organization string, options tfe.DataRetentionPolicySetOptions) (*tfe.DataRetentionPolicy, error) {
510 panic("not implemented")

internal/backend/backend_test.go1

48:2discarded-error-resulterror result returned by f.Close is discarded

internal/backend/backend_test.go:48:2

47 }
48 f.Close()
49

internal/addrs/module_call.go1

155:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/module_call.go:155:1

154// ModuleCallOutput is the address of a named output and its associated
155// ModuleCall, which may expand into multiple module instances
156type ModuleCallOutput struct {

internal/addrs/provider_config.go1

352:2early-returninvert the condition and return early to reduce nesting

internal/addrs/provider_config.go:352:2

351 // We always assume legacy-style providers in legacy state ...
352 if tt, ok := remain[1].(hcl.TraverseAttr); ok {
353 // ... unless it's the builtin "terraform" provider, a special case.

internal/plugin6/convert/schema.go1

73:2enforce-switch-styledefault clause should be the last switch clause

internal/plugin6/convert/schema.go:73:2

72 switch k {
73 default:
74 return proto.StringKind_PLAIN

cmd/tofu/main.go1

433:44error-stringserror string should not be capitalized or end with punctuation

cmd/tofu/main.go:433:44

432 if err != nil {
433 return unmanagedProviders, fmt.Errorf("Invalid unix socket path %q for %q: %w", c.Addr.String, p, err)
434 }

internal/encryption/keyprovider/errors.go1

11:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/keyprovider/errors.go:11:6

10// ErrKeyProviderFailure indicates a generic key provider failure.
11type ErrKeyProviderFailure struct {
12 Message string

internal/communicator/ssh/provisioner.go1

521:3excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

internal/communicator/ssh/provisioner.go:521:3

520 // finally try it as an authorized key
521 pk, _, _, _, err = ssh.ParseAuthorizedKey(d)
522 if err == nil {

internal/addrs/check.go1

14:6exported-declaration-commentexported type should have a comment beginning with its name

internal/addrs/check.go:14:6

13// so this address uniquely describes a single check within a module.
14type Check struct {
15 referenceable

internal/addrs/move_endpoint_module.go1

1:1file-length-limitfile has 747 lines; maximum is 500

internal/addrs/move_endpoint_module.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/backend/testing.go1

378:57flag-parameterboolean parameter testForceUnlock controls function flow

internal/backend/testing.go:378:57

377
378func testLocksInWorkspace(t *testing.T, b1, b2 Backend, testForceUnlock bool, workspace string) {
379 t.Helper()

cmd/tofu/main_test.go2

1:1formatfile is not formatted

cmd/tofu/main_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/main_test.go`
153:6function-lengthfunction has 7 statements and 99 lines; maximum is 50 statements or 75 lines

cmd/tofu/main_test.go:153:6

152// more control over behavior at the expense of more complex test structures.
153func TestMain_cliArgsFromEnvAdvanced(t *testing.T) {
154 // Restore original CLI args

internal/backend/remote-state/oss/backend.go1

456:6function-result-limitfunction returns 4 values; maximum is 3

internal/backend/remote-state/oss/backend.go:456:6

455
456func getAssumeRoleAK(accessKey, secretKey, stsToken, region, roleArn, sessionName, policy, stsEndpoint string, sessionExpiration int) (string, string, string, error) {
457 request := sts.CreateAssumeRoleRequest()

internal/addrs/instance_key.go1

170:2identical-switch-branchesswitch repeats a case body

internal/addrs/instance_key.go:170:2

169 return string(i.(StringKey)) < string(j.(StringKey))
170 default:
171 // Shouldn't be possible to get down here in practice, since the

internal/backend/init/init.go1

18:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:18:2

17 backendLocal "github.com/opentofu/opentofu/internal/backend/local"
18 backendRemote "github.com/opentofu/opentofu/internal/backend/remote"
19 backendAzure "github.com/opentofu/opentofu/internal/backend/remote-state/azure"

internal/backend/local/backend.go1

108:21import-shadowingidentifier backend shadows an imported package

internal/backend/local/backend.go:108:21

107// dedicated backend for non-enhanced behavior.
108func NewWithBackend(backend backend.Backend, enc encryption.StateEncryption) *Local {
109 return &Local{

internal/command/jsonconfig/expression.go1

159:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/command/jsonconfig/expression.go:159:5

158 if _, exists := ret[typeName]; !exists {
159 ret[typeName] = make(map[string]map[string]any)
160 }

internal/command/jsonformat/state_test.go1

71:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/command/jsonformat/state_test.go:71:9

70 for i, tt := range tests {
71 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
72

internal/backend/remote-state/http/backend_test.go1

35:28insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:35:28

34 }
35 if client.URL.String() != "http://127.0.0.1:8888/foo" {
36 t.Fatalf("Expected address \"%s\", got \"%s\"", conf["address"], client.URL.String())

internal/command/views/login.go1

15:12interface-method-limitinterface has 20 methods, exceeding the configured design limit of 10

internal/command/views/login.go:15:12

14
15type Login interface {
16 Diagnostics(diags tfdiags.Diagnostics)

internal/backend/remote/backend_common.go1

140:8max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_common.go:140:8

139 case tfe.RunPlanned:
140 if op.Type == backend.OperationTypePlan {
141 continue

internal/lang/eval/internal/tofu2024/compile_resources.go1

55:6max-parametersfunction has 9 parameters; maximum is 8

internal/lang/eval/internal/tofu2024/compile_resources.go:55:6

54
55func compileModuleInstanceResource(
56 ctx context.Context,

internal/cloud/tfe_client_mock.go1

713:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:713:6

712
713type MockPolicySetOutcomes struct {
714 client *MockClient

internal/addrs/parse_target.go1

80:3modifies-parameterassignment modifies parameter remain

internal/addrs/parse_target.go:80:3

79 mode = DataResourceMode
80 remain = remain[1:]
81 case "ephemeral":

internal/backend/remote-state/kubernetes/backend.go1

208:2modifies-value-receiverassignment modifies value receiver b

internal/backend/remote-state/kubernetes/backend.go:208:2

207
208 b.kubernetesSecretClient = client.Resource(secretResource).Namespace(b.namespace)
209 return b.kubernetesSecretClient, nil

cmd/tofu/commands.go1

475:24nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/commands.go:475:24

474func makeShutdownCh() <-chan struct{} {
475 resultCh := make(chan struct{})
476

internal/backend/remote-state/kubernetes/backend.go1

378:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/kubernetes/backend.go:378:4

377 log.Printf("[INFO] Unable to load config file as it doesn't exist at %q", pathErr.Path)
378 return nil, nil
379 }

internal/backend/remote-state/consul/client.go1

87:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/consul/client.go:87:3

86 if pair == nil {
87 return nil, nil
88 }

internal/cloud/state_test.go1

327:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

internal/cloud/state_test.go:327:4

326
327 defer server.Close()
328 cfg := &tfe.Config{

internal/backend/remote-state/consul/client.go1

262:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/consul/client.go:262:4

261 return nil
262 } else if !strings.Contains(err.Error(), "too large") {
263 // We failed for some other reason, report this to the user

internal/command/command_test.go1

68:6no-initreplace init with explicit initialization

internal/command/command_test.go:68:6

67
68func init() {
69 test = true

internal/backend/local/backend_refresh_test.go1

101:3no-naked-returnreturn values must be explicit

internal/backend/local/backend_refresh_test.go:101:3

100
101 return
102 }

cmd/tofu/experiments.go1

25:5no-package-varpackage variables introduce mutable global state

cmd/tofu/experiments.go:25:5

24// open experiment.)
25var experimentsAllowed string
26

cmd/tofu/main.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/main.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/config.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/config.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/config.go:6:9

5
6package aws_kms
7

internal/addrs/move_endpoint_module_test.go1

1728:13range-value-addresstaking the address of range value test can be misleading

internal/addrs/move_endpoint_module_test.go:1728:13

1727 func(t *testing.T) {
1728 from := &MoveEndpointInModule{
1729 relSubject: test.from,

internal/legacy/tofu/resource_address.go1

487:7receiver-namingreceiver name addr is inconsistent with r

internal/legacy/tofu/resource_address.go:487:7

486// addresses.
487func (addr *ResourceAddress) Equals(raw interface{}) bool {
488 other, ok := raw.(*ResourceAddress)

internal/backend/remote-state/cos/backend.go1

192:34redefines-builtin-ididentifier max shadows a predeclared identifier

internal/backend/remote-state/cos/backend.go:192:34

191
192func validateIntegerInRange(min, max int64) schema.SchemaValidateFunc {
193 return func(v interface{}, k string) (ws []string, errors []error) {

internal/addrs/instance_key_test.go1

31:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:31:4

30 {
31 StringKey("hi"),
32 `["hi"]`,

internal/cloud/backend_apply_test.go1

20:2redundant-import-aliasimport alias is identical to the package name

internal/cloud/backend_apply_test.go:20:2

19 tfe "github.com/hashicorp/go-tfe"
20 mocks "github.com/hashicorp/go-tfe/mocks"
21 version "github.com/hashicorp/go-version"

internal/legacy/helper/schema/provider.go1

114:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/provider.go:114:9

113 // Provider-specific checks
114 for k, _ := range sm {
115 if isReservedProviderFieldName(k) {

internal/addrs/move_endpoint_module.go1

372:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:372:3

371 case AbsResourceInstance:
372 switch eSub := eSub.(type) {
373 case AbsResourceInstance:

internal/backend/remote-state/consul/client.go1

271:2slice-preallocationpreallocate chunkPaths with capacity len(range source) before appending once per iteration

internal/backend/remote-state/consul/client.go:271:2

270 chunks := split(payload, 524288)
271 chunkPaths := make([]string, 0)
272

internal/command/cliconfig/svcauthconfig/testing.go1

37:34standard-http-method-constantreplace the HTTP method literal with http.MethodGet

internal/command/cliconfig/svcauthconfig/testing.go:37:34

36
37 fakeReq, err := http.NewRequest("GET", "http://example.com/", nil)
38 if err != nil {

internal/backend/init/testing.go1

50:2task-commentFIXME comment should be resolved or linked to an owned work item

internal/backend/init/testing.go:50:2

49func RegisterTemp(name string, f backend.InitFn) func() {
50 // FIXME: It would be better to add a map of backends to command.Meta's existing
51 // "testingOverrides" field, but at the time of writing direct calls to this

internal/addrs/check_rule.go1

69:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/check_rule.go:69:1

68
69type checkRuleKey struct {
70 ContainerKey UniqueKey

internal/addrs/instance_key.go1

167:33unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/instance_key.go:167:33

166 case iTy == IntKeyType:
167 return int(i.(IntKey)) < int(j.(IntKey))
168 case iTy == StringKeyType:

internal/flock/filesystem_lock_windows.go1

139:6unexported-namingunexported identifier should not begin with an underscore

internal/flock/filesystem_lock_windows.go:139:6

138 }
139 var _p1 uint32
140 if initialState {

internal/backend/remote-state/s3/backend_complete_test.go1

97:55unexported-returnexported function returns an unexported type

internal/backend/remote-state/s3/backend_complete_test.go:97:55

96
97func ExpectMultipleDiags(validators ...diagValidator) diagsValidator {
98 return func(t *testing.T, diags tfdiags.Diagnostics) {

internal/backend/local/backend_local.go1

563:58unused-parameterparameter mode is unused

internal/backend/local/backend_local.go:563:58

562
563func (v unparsedUnknownVariableValue) ParseVariableValue(mode configs.VariableParsingMode) (*tofu.InputValue, tfdiags.Diagnostics) {
564 return &tofu.InputValue{

internal/addrs/check.go1

66:7unused-receiverreceiver c is unused

internal/addrs/check.go:66:7

65
66func (c ConfigCheck) configCheckableSigil() {}
67

internal/backend/remote-state/consul/backend_test.go1

88:114use-anyuse any instead of interface{}

internal/backend/remote-state/consul/backend_test.go:88:114

87
88 b2 := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
89 "address": srv.HTTPAddr,

internal/backend/local/backend_local_test.go1

288:14use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:288:14

287 if s.locked {
288 return "", fmt.Errorf("already locked")
289 }

internal/command/jsonchecks/checks.go1

48:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonchecks/checks.go:48:3

47
48 sort.Slice(objects, func(i, j int) bool {
49 return objects[i].Address["to_display"].(string) < objects[j].Address["to_display"].(string)

internal/legacy/helper/schema/resource_test.go1

42:30var-declarationomit the explicit zero value from the variable declaration

internal/legacy/helper/schema/resource_test.go:42:30

41
42 var s *tofu.InstanceState = nil
43

internal/backend/remote-state/azure/backend_test.go1

319:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:319:2

318 client_id := os.Getenv("TF_AZURE_TEST_CLIENT_ID")
319 client_secret := os.Getenv("TF_AZURE_TEST_CLIENT_SECRET")
320 if client_id == "" || client_secret == "" {

internal/backend/remote-state/cos/client.go1

113:29weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/cos/client.go:113:29

112
113 check := fmt.Sprintf("%x", md5.Sum(data))
114 err = c.putObject(ctx, c.lockFile, data)

cmd/tofu/main_test.go1

80:4add-constantstring literal "-foo bar" appears more than twice; define a constant

cmd/tofu/main_test.go:80:4

79 []string{"", testCommandName, "bar"},
80 "-foo bar",
81 []string{"-foo", "bar", "bar"},

internal/command/views/apply_test.go1

31:5boolean-literal-comparisonomit the boolean literal from the logical expression

internal/command/views/apply_test.go:31:5

30
31 if hv.destroy != false {
32 t.Fatalf("unexpected destroy value")

internal/command/command_test.go1

922:4call-to-gcavoid explicit garbage collection

internal/command/command_test.go:922:4

921 if runtime.GOOS == "windows" {
922 runtime.GC()
923 }

cmd/tofu/version.go1

28:6cognitive-complexityfunction has cognitive complexity 13; maximum is 7

cmd/tofu/version.go:28:6

27// we've already performed all of the requested work.
28func logGodebugUsage() {
29 // These constants reflect the documented conventions from the

internal/backend/remote-state/consul/client.go1

567:24confusing-namingname unlock differs from Unlock only by capitalization

internal/backend/remote-state/consul/client.go:567:24

566// Only to be called while holding Client.mu
567func (c *RemoteClient) unlock(id string) error {
568 // This method can be called in two circumstances:

internal/command/arguments/extended.go1

224:130confusing-resultsadjacent unnamed results of the same type should be named

internal/command/arguments/extended.go:224:130

223
224func parseRawTargetsAndExcludes(targetsDirect, excludesDirect []string, targetFiles, excludeFiles []string) ([]addrs.Targetable, []addrs.Targetable, tfdiags.Diagnostics) {
225 var allParsedTargets, allParsedExcludes, parsedTargets []addrs.Targetable

internal/command/clistate/state.go1

176:6constructor-interface-returnNewNoopLocker returns interface Locker although its concrete result is consistently noopLocker; return the concrete type

internal/command/clistate/state.go:176:6

175// NewNoopLocker returns a valid Locker that does nothing.
176func NewNoopLocker() Locker {
177 return noopLocker{}

internal/backend/local/backend_local.go1

49:55context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend_local.go:49:55

48
49func (b *Local) localRun(ctx context.Context, stopCtx context.Context, op *backend.Operation) (*backend.LocalRun, *configload.Snapshot, statemgr.Full, tfdiags.Diagnostics) {
50 var diags tfdiags.Diagnostics

internal/cloud/cloud_integration.go1

31:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/cloud/cloud_integration.go:31:2

30 B *Cloud
31 StopContext context.Context
32 CancelContext context.Context

internal/addrs/module_instance.go1

100:6cyclomatic-complexityfunction complexity is 11; maximum is 10

internal/addrs/module_instance.go:100:6

99// This function supports module addresses with and without instance keys.
100func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Traversal, tfdiags.Diagnostics) {
101 remain := traversal

internal/cloud/backend.go1

220:4deep-exitprocess-exit calls should be confined to main or init

internal/cloud/backend.go:220:4

219 if err != nil {
220 log.Panicf("An unexpected error occurred: %s", err)
221 }

internal/cloud/tfe_client_mock.go1

509:139deprecated-api-usagegithub.com/hashicorp/go-tfe.DataRetentionPolicy is deprecated: Use DataRetentionPolicyDeleteOlder instead. This is the original representation of a data retention policy, only present in TFE v202311-1 and v202312-1

internal/cloud/tfe_client_mock.go:509:139

508
509func (m *MockOrganizations) SetDataRetentionPolicy(ctx context.Context, organization string, options tfe.DataRetentionPolicySetOptions) (*tfe.DataRetentionPolicy, error) {
510 panic("not implemented")

internal/backend/backend_test.go1

76:2discarded-error-resulterror result returned by f.Close is discarded

internal/backend/backend_test.go:76:2

75 }
76 f.Close()
77

internal/addrs/move_endpoint.go1

305:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/move_endpoint.go:305:1

304// At the time of writing, it was only ensuring that the moved blocks cannot be used against ephemeral resources.
305// This can later be expanded with more rules
306func (e *MoveEndpoint) SubjectAllowed() bool {

internal/addrs/provider_config.go1

370:3early-returninvert the condition and return early to reduce nesting

internal/addrs/provider_config.go:370:3

369 if len(remain) == 3 {
370 if tt, ok := remain[2].(hcl.TraverseAttr); ok {
371 ret.Alias = tt.Name

internal/plugin6/convert/schema.go1

242:2enforce-switch-styledefault clause should be the last switch clause

internal/plugin6/convert/schema.go:242:2

241 switch k {
242 default:
243 return configschema.StringPlain

cmd/tofu/main.go1

438:44error-stringserror string should not be capitalized or end with punctuation

cmd/tofu/main.go:438:44

437 if err != nil {
438 return unmanagedProviders, fmt.Errorf("Invalid TCP address %q for %q: %w", c.Addr.String, p, err)
439 }

internal/encryption/keyprovider/errors.go1

28:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/keyprovider/errors.go:28:6

27// ErrInvalidConfiguration indicates that the key provider configuration is incorrect.
28type ErrInvalidConfiguration struct {
29 Message string

internal/tofu/context_plan2_test.go1

5549:2excessive-blank-identifiersassignment discards three or more results; name meaningful results or simplify the return contract

internal/tofu/context_plan2_test.go:5549:2

5548 // make sure we can serialize the plan even if there were an error
5549 _, _, _, err := contextOptsForPlanViaFile(t, snap, plan)
5550 if err != nil {

internal/addrs/check.go1

25:16exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:25:16

24// address.
25func (c Check) InModule(modAddr Module) ConfigCheck {
26 return ConfigCheck{

internal/addrs/move_endpoint_module_test.go1

1:1file-length-limitfile has 1751 lines; maximum is 500

internal/addrs/move_endpoint_module_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/backend_plan_test.go1

1500:60flag-parameterboolean parameter shouldRender controls function flow

internal/cloud/backend_plan_test.go:1500:60

1499
1500func assertSRORendered(t *testing.T, b *Cloud, r *tfe.Run, shouldRender bool) {
1501 got, err := b.shouldRenderStructuredRunOutput(r)

cmd/tofu/provider_source.go2

1:1formatfile is not formatted

cmd/tofu/provider_source.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/provider_source.go`
109:6function-lengthfunction has 16 statements and 104 lines; maximum is 50 statements or 75 lines

cmd/tofu/provider_source.go:109:6

108// "exclude" argument in the direct provider source in the CLI config.
109func implicitProviderSource(
110 ctx context.Context,

internal/backend/remote-state/oss/backend.go1

634:6function-result-limitfunction returns 4 values; maximum is 3

internal/backend/remote-state/oss/backend.go:634:6

633// The related PR: https://github.com/terraform-providers/terraform-provider-alicloud/pull/731
634func getAuthCredentialByEcsRoleName(ecsRoleName string) (accessKey, secretKey, token string, err error) {
635

internal/addrs/module.go1

108:2identical-switch-branchesswitch repeats a case body

internal/addrs/module.go:108:2

107
108 case AbsResource:
109 return m.TargetContains(to.Module)

internal/backend/init/init.go1

19:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:19:2

18 backendRemote "github.com/opentofu/opentofu/internal/backend/remote"
19 backendAzure "github.com/opentofu/opentofu/internal/backend/remote-state/azure"
20 backendConsul "github.com/opentofu/opentofu/internal/backend/remote-state/consul"

internal/backend/local/backend_plan_test.go1

657:2import-shadowingidentifier addrs shadows an imported package

internal/backend/local/backend_plan_test.go:657:2

656func getAddrs(resources []*plans.ResourceInstanceChangeSrc) []string {
657 addrs := make([]string, len(resources))
658 for i, r := range resources {

internal/command/jsonstate/state.go1

283:6inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/command/jsonstate/state.go:283:6

282 if _, ok := moduleChildSet[childAddr.Parent().String()]; !ok {
283 moduleChildSet[childAddr.Parent().String()] = map[string]struct{}{}
284 }

internal/command/views/hook_ui_test.go1

975:15inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/command/views/hook_ui_test.go:975:15

974 for i, tc := range testCases {
975 testName := fmt.Sprintf("%d", i)
976 t.Run(testName, func(t *testing.T) {

internal/backend/remote-state/http/backend_test.go1

57:35insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:57:35

56 conf = map[string]cty.Value{
57 "address": cty.StringVal("http://127.0.0.1:8888/foo"),
58 "update_method": cty.StringVal("BLAH"),

internal/command/views/state.go1

24:12interface-method-limitinterface has 22 methods, exceeding the configured design limit of 10

internal/command/views/state.go:24:12

23
24type State interface {
25 Diagnostics(diags tfdiags.Diagnostics)

internal/backend/remote/backend_common.go1

149:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_common.go:149:7

148 // Stop searching when we reached the current run.
149 if w.CurrentRun != nil && w.CurrentRun.ID == item.ID {
150 break runlist

internal/cloud/tfe_client_mock.go1

841:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:841:6

840
841type MockPolicyChecks struct {
842 client *MockClient

internal/addrs/parse_target.go1

83:3modifies-parameterassignment modifies parameter remain

internal/addrs/parse_target.go:83:3

82 mode = EphemeralResourceMode
83 remain = remain[1:]
84 }

internal/backend/remote-state/kubernetes/backend.go1

222:2modifies-value-receiverassignment modifies value receiver b

internal/backend/remote-state/kubernetes/backend.go:222:2

221
222 b.kubernetesLeaseClient = client.CoordinationV1().Leases(b.namespace)
223 return b.kubernetesLeaseClient, nil

cmd/tofu/commands.go1

483:16nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/commands.go:483:16

482 <-signalCh
483 resultCh <- struct{}{}
484 }

internal/backend/remote-state/kubernetes/client.go1

58:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/kubernetes/client.go:58:4

57 if k8serrors.IsNotFound(err) {
58 return nil, nil
59 }

internal/backend/remote-state/consul/client.go1

352:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/consul/client.go:352:3

351 if pair == nil {
352 return nil, nil
353 }

internal/command/init_test.go1

3403:4no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

internal/command/init_test.go:3403:4

3402 // so we don't need to preserve them afterwards.
3403 defer close()
3404 if err != nil {

internal/backend/remote-state/gcs/client.go1

39:5no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/gcs/client.go:39:5

38 return nil, nil
39 } else {
40 return nil, fmt.Errorf("Failed to open state file at %v: %w", c.stateFileURL(), err)

internal/command/testdata/login-oauth-server/oauthserver.go1

182:6no-initreplace init with explicit initialization

internal/command/testdata/login-oauth-server/oauthserver.go:182:6

181
182func init() {
183 Handler = handler{}

internal/backend/remote-state/azure/auth/msi_auth.go1

69:2no-naked-returnreturn values must be explicit

internal/backend/remote-state/azure/auth/msi_auth.go:69:2

68 os.Unsetenv(MSI_ENDPOINT)
69 return
70}

cmd/tofu/signal_unix.go1

15:5no-package-varpackage variables introduce mutable global state

cmd/tofu/signal_unix.go:15:5

14
15var ignoreSignals = []os.Signal{os.Interrupt}
16var forwardSignals = []os.Signal{syscall.SIGTERM}

cmd/tofu/module_source.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/module_source.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/config_assumerole.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/config_assumerole.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/config_assumerole.go:6:9

5
6package aws_kms
7

internal/addrs/move_endpoint_module_test.go1

1732:11range-value-addresstaking the address of range value test can be misleading

internal/addrs/move_endpoint_module_test.go:1732:11

1731
1732 to := &MoveEndpointInModule{
1733 relSubject: test.to,

internal/legacy/tofu/resource_address.go1

528:7receiver-namingreceiver name addr is inconsistent with r

internal/legacy/tofu/resource_address.go:528:7

527// index 9, rather than after index 1.
528func (addr *ResourceAddress) Less(other *ResourceAddress) bool {
529

internal/backend/remote-state/oss/backend.go1

74:7redefines-builtin-ididentifier min shadows a predeclared identifier

internal/backend/remote-state/oss/backend.go:74:7

73 ValidateFunc: func(v interface{}, k string) ([]string, []error) {
74 min := 900
75 max := 3600

internal/addrs/instance_key_test.go1

35:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:35:4

34 {
35 StringKey("0"),
36 `["0"]`, // intentionally distinct from IntKey(0)

internal/cloud/backend_apply_test.go1

22:2redundant-import-aliasimport alias is identical to the package name

internal/cloud/backend_apply_test.go:22:2

21 version "github.com/hashicorp/go-version"
22 gomock "go.uber.org/mock/gomock"
23

internal/legacy/helper/schema/provider.go1

465:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/provider.go:465:9

464 keys := make([]string, 0, len(p.DataSourcesMap))
465 for k, _ := range p.DataSourcesMap {
466 keys = append(keys, k)

internal/addrs/move_endpoint_module.go1

403:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:403:3

402 case AbsModuleCall:
403 switch eSub.(type) {
404 case AbsModuleCall:

internal/backend/remote-state/consul/client.go1

701:5slice-preallocationpreallocate chunks with capacity len(range source) before appending once per iteration

internal/backend/remote-state/consul/client.go:701:5

700 if ok {
701 chunks := make([]string, 0)
702 for _, c := range d["chunks"].([]interface{}) {

internal/command/login.go1

273:31standard-http-method-constantreplace the HTTP method literal with http.MethodGet

internal/command/login.go:273:31

272
273 req, err := http.NewRequest("GET", motdServiceURL.String(), nil)
274 if err != nil {

internal/builtin/providers/tf/resource_data.go1

203:1task-commentTODO comment should be resolved or linked to an owned work item

internal/builtin/providers/tf/resource_data.go:203:1

202
203// TODO: This isn't very useful even for examples, because terraform_data has
204// no way to refresh the full resource value from only the import ID. This

internal/addrs/check_rule_diagnostic.go1

42:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/check_rule_diagnostic.go:42:1

41// embedded in the original diagnostic.
42type CheckRuleDiagnosticExtra struct {
43 CheckRule CheckRule

internal/addrs/instance_key.go1

169:18unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/instance_key.go:169:18

168 case iTy == StringKeyType:
169 return string(i.(StringKey)) < string(j.(StringKey))
170 default:

internal/cloud/backend.go1

1100:39unexported-returnexported function returns an unexported type

internal/cloud/backend.go:1100:39

1099
1100func (wm WorkspaceMapping) Strategy() workspaceStrategy {
1101 switch {

internal/backend/local/backend_local_test.go1

256:78unused-parameterparameter workspace is unused

internal/backend/local/backend_local_test.go:256:78

255
256func (b backendWithStateStorageThatFailsRefresh) StateMgr(_ context.Context, workspace string) (statemgr.Full, error) {
257 return &stateStorageThatFailsRefresh{}, nil

internal/addrs/check.go1

68:7unused-receiverreceiver c is unused

internal/addrs/check.go:68:7

67
68func (c ConfigCheck) CheckableKind() CheckableKind {
69 return CheckableCheck

internal/backend/remote-state/consul/backend_test.go1

104:113use-anyuse any instead of interface{}

internal/backend/remote-state/consul/backend_test.go:104:113

103 // Get the backend
104 b := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
105 "address": srv.HTTPAddr,

internal/backend/local/backend_local_test.go1

296:10use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:296:10

295 if !s.locked {
296 return fmt.Errorf("not locked")
297 }

internal/command/jsonchecks/checks.go1

59:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonchecks/checks.go:59:2

58
59 sort.Slice(jsonResults, func(i, j int) bool {
60 return jsonResults[i].Address["to_display"].(string) < jsonResults[j].Address["to_display"].(string)

internal/legacy/helper/schema/resource_test.go1

100:30var-declarationomit the explicit zero value from the variable declaration

internal/legacy/helper/schema/resource_test.go:100:30

99
100 var s *tofu.InstanceState = nil
101

internal/backend/remote-state/azure/backend_test.go1

381:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:381:2

380 res := testResourceNames(rs, "testState")
381 client_id := os.Getenv("TF_AZURE_TEST_CLIENT_ID")
382 cert_path := os.Getenv("TF_AZURE_TEST_CERT_PATH")

internal/backend/remote-state/cos/client.go1

222:29weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/cos/client.go:222:29

221
222 check := fmt.Sprintf("%x", md5.Sum(data))
223 log.Printf("[DEBUG] getObject %s: check: %s", cosFile, check)

cmd/tofu/main_test.go1

185:4add-constantstring literal "command" appears more than twice; define a constant

cmd/tofu/main_test.go:185:4

184 "targeted to this command",
185 "command",
186 EnvCLI + "_command",

internal/command/views/apply_test.go1

35:5boolean-literal-comparisonomit the boolean literal from the logical expression

internal/command/views/apply_test.go:35:5

34
35 if hv.view.runningInAutomation != true { // redundant but changed a more relevant check that was here before
36 t.Fatalf("unexpected inAutomation value")

internal/command/init_test.go1

133:4call-to-gcavoid explicit garbage collection

internal/command/init_test.go:133:4

132 if runtime.GOOS == "windows" {
133 runtime.GC()
134 }

internal/addrs/checkable.go1

96:6cognitive-complexityfunction has cognitive complexity 12; maximum is 7

internal/addrs/checkable.go:96:6

95// results between runs.
96func ParseCheckableStr(kind CheckableKind, src string) (Checkable, tfdiags.Diagnostics) {
97 var diags tfdiags.Diagnostics

internal/backend/remote-state/s3/client.go1

119:24confusing-namingname get differs from Get only by capitalization

internal/backend/remote-state/s3/client.go:119:24

118
119func (c *RemoteClient) get(ctx context.Context) (*remote.Payload, error) {
120 var output *s3.GetObjectOutput

internal/command/jsonplan/plan.go1

189:41confusing-resultsadjacent unnamed results of the same type should be named

internal/command/jsonplan/plan.go:189:41

188 schemas *tofu.Schemas,
189) (map[string]Change, []ResourceChange, []ResourceChange, []ResourceAttr, error) {
190 output := newPlan()

internal/command/views/backend.go1

39:6constructor-interface-returnNewBackendHuman returns interface Backend although its concrete result is consistently *BackendHuman; return the concrete type

internal/command/views/backend.go:39:6

38// that are only reachable from incomplete configured tests.
39func NewBackendHuman(view *View) Backend {
40 return &BackendHuman{view: view}

internal/backend/local/backend_local.go1

150:61context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend_local.go:150:61

149
150func (b *Local) localRunDirect(ctx context.Context, stopCtx context.Context, op *backend.Operation, run *backend.LocalRun, coreOpts *tofu.ContextOpts, s statemgr.Full) (*backend.LocalRun, *configload.Snapshot, tfdiags.Diagnostics) {
151 var diags tfdiags.Diagnostics

internal/cloud/cloud_integration.go1

32:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/cloud/cloud_integration.go:32:2

31 StopContext context.Context
32 CancelContext context.Context
33 Op *backend.Operation

internal/addrs/module_instance.go1

430:25cyclomatic-complexityfunction complexity is 17; maximum is 10

internal/addrs/module_instance.go:430:25

429// is contained within the receiver.
430func (m ModuleInstance) TargetContains(other Targetable) bool {
431 switch to := other.(type) {

internal/cloud/e2e/main_test.go1

37:2deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:37:2

36
37 os.Exit(code)
38}

internal/cloud/tfe_client_mock.go1

2010:93deprecated-api-usagegithub.com/hashicorp/go-tfe.DataRetentionPolicy is deprecated: Use DataRetentionPolicyDeleteOlder instead. This is the original representation of a data retention policy, only present in TFE v202311-1 and v202312-1

internal/cloud/tfe_client_mock.go:2010:93

2009
2010func (m *MockWorkspaces) ReadDataRetentionPolicy(ctx context.Context, workspaceID string) (*tfe.DataRetentionPolicy, error) {
2011 panic("not implemented")

internal/backend/backend_test.go1

83:13discarded-error-resulterror result returned by exec.Command("icacls", f.Name()).CombinedOutput is discarded

internal/backend/backend_test.go:83:13

82 }
83 acl, _ := exec.Command("icacls", f.Name()).CombinedOutput()
84 t.Logf("Before /deny %s", acl)

internal/addrs/moveable.go1

16:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/moveable.go:16:1

15// of these in configuration where the author gives an address relative to
16// the current module where the address is defined. The type MoveEndpoint
17type AbsMoveable interface {

internal/addrs/provider_function.go1

90:9early-returninvert the condition and return early to reduce nesting

internal/addrs/provider_function.go:90:9

89 pf.ProviderName = f.Namespaces[1]
90 } else if len(f.Namespaces) == 3 {
91 // provider::<name>::<alias>::<function>

cmd/tofu/main.go1

441:43error-stringserror string should not be capitalized or end with punctuation

cmd/tofu/main.go:441:43

440 default:
441 return unmanagedProviders, fmt.Errorf("Unknown address type %q for %q", c.Addr.Network, p)
442 }

internal/encryption/keyprovider/errors.go1

52:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/keyprovider/errors.go:52:6

51// ErrInvalidMetadata indicates that the key provider has received an incorrect metadata and cannot decrypt.
52type ErrInvalidMetadata struct {
53 Message string

internal/addrs/check.go1

34:16exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:34:16

33// address.
34func (c Check) Absolute(modAddr ModuleInstance) AbsCheck {
35 return AbsCheck{

internal/addrs/move_endpoint_test.go1

1:1file-length-limitfile has 690 lines; maximum is 500

internal/addrs/move_endpoint_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/backend_show.go1

23:80flag-parameterboolean parameter redacted controls function flow

internal/cloud/backend_show.go:23:80

22// show command, in order to format and display a saved cloud plan.
23func (b *Cloud) ShowPlanForRun(ctx context.Context, runID, runHostname string, redacted bool) (*cloudplan.RemotePlanJSON, error) {
24 var jsonBytes []byte

cmd/tofu/provider_source_test.go2

1:1formatfile is not formatted

cmd/tofu/provider_source_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/provider_source_test.go`
26:6function-lengthfunction has 3 statements and 139 lines; maximum is 50 statements or 75 lines

cmd/tofu/provider_source_test.go:26:6

25
26func TestProviderSource(t *testing.T) {
27 tests := []struct {

internal/command/cliconfig/provider_installation.go1

332:6function-result-limitfunction returns 4 values; maximum is 3

internal/command/cliconfig/provider_installation.go:332:6

331// from inside a provider_installation block.
332func decodeOCIMirrorInstallationMethodBlock(methodBody *hclast.ObjectType) (location ProviderInstallationLocation, include, exclude []string, diags tfdiags.Diagnostics) {
333 type BodyContent struct {

internal/addrs/module.go1

111:2identical-switch-branchesswitch repeats a case body

internal/addrs/module.go:111:2

110
111 case AbsResourceInstance:
112 return m.TargetContains(to.Module)

internal/backend/init/init.go1

20:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:20:2

19 backendAzure "github.com/opentofu/opentofu/internal/backend/remote-state/azure"
20 backendConsul "github.com/opentofu/opentofu/internal/backend/remote-state/consul"
21 backendCos "github.com/opentofu/opentofu/internal/backend/remote-state/cos"

internal/backend/remote-state/azure/backend.go1

289:2import-shadowingidentifier encryption shadows an imported package

internal/backend/remote-state/azure/backend.go:289:2

288 *schema.Backend
289 encryption encryption.StateEncryption
290

internal/command/providers_mirror.go1

333:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/command/providers_mirror.go:333:5

332 if _, ok := indexArchives[version]; !ok {
333 indexArchives[version] = map[string]interface{}{}
334 }

internal/httpclient/useragent_test.go1

37:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/httpclient/useragent_test.go:37:9

36 } {
37 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
38 if c.additional != "" {

internal/backend/remote-state/http/backend_test.go1

59:35insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:59:35

58 "update_method": cty.StringVal("BLAH"),
59 "lock_address": cty.StringVal("http://127.0.0.1:8888/bar"),
60 "lock_method": cty.StringVal("BLIP"),

internal/command/views/workspace.go1

16:16interface-method-limitinterface has 16 methods, exceeding the configured design limit of 10

internal/command/views/workspace.go:16:16

15
16type Workspace interface {
17 Diagnostics(diags tfdiags.Diagnostics)

internal/backend/remote/backend_common.go1

390:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_common.go:390:7

389 if err != nil {
390 if err != io.EOF {
391 return generalError("Failed to read logs", err)

internal/cloud/tfe_client_mock.go1

1000:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1000:6

999
1000type MockProjects struct {
1001 client *MockClient

internal/addrs/parse_target.go1

91:2modifies-parameterassignment modifies parameter remain

internal/addrs/parse_target.go:91:2

90
91 remain = remain[2:]
92 switch len(remain) {

internal/command/flags/raw_flags.go1

57:2modifies-value-receiverassignment modifies value receiver f

internal/command/flags/raw_flags.go:57:2

56func (f RawFlags) Set(str string) error {
57 *f.Items = append(*f.Items, RawFlag{
58 Name: f.Name,

cmd/tofu/main.go1

411:20nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/main.go:411:20

410 ProtocolVersion int
411 Addr struct {
412 Network string

internal/backend/remote-state/s3/client.go1

146:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/s3/client.go:146:4

145 if errors.As(err, &nk) {
146 return nil, nil
147 }

internal/backend/remote-state/cos/client.go1

54:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/cos/client.go:54:3

53 if !exists {
54 return nil, nil
55 }

internal/command/providers_lock.go1

258:3no-defer-in-loopdefer inside a loop runs at function exit, not iteration exit

internal/command/providers_lock.go:258:3

257 }
258 defer os.RemoveAll(tempDir)
259

internal/backend/remote-state/kubernetes/client.go1

182:5no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/kubernetes/client.go:182:5

181 return "", err
182 } else {
183 return info.ID, nil

internal/command/testdata/login-tfe-server/tfeserver.go1

70:6no-initreplace init with explicit initialization

internal/command/testdata/login-tfe-server/tfeserver.go:70:6

69
70func init() {
71 Handler = handler{}

internal/backend/remote-state/cos/backend.go1

203:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/backend.go:203:3

202 }
203 return
204 }

cmd/tofu/signal_unix.go1

16:5no-package-varpackage variables introduce mutable global state

cmd/tofu/signal_unix.go:16:5

15var ignoreSignals = []os.Signal{os.Interrupt}
16var forwardSignals = []os.Signal{syscall.SIGTERM}
17

cmd/tofu/plugins.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/plugins.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/config_endpoints.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/config_endpoints.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/config_endpoints.go:6:9

5
6package aws_kms
7

internal/addrs/move_endpoint_test.go1

683:9range-value-addresstaking the address of range value tt can be misleading

internal/addrs/move_endpoint_test.go:683:9

682 t.Run(name, func(t *testing.T) {
683 m := &MoveEndpoint{relSubject: tt.target}
684 if got, want := m.SubjectAllowed(), tt.want; got != want {

internal/legacy/tofu/state.go1

848:7receiver-namingreceiver name r is inconsistent with s

internal/legacy/tofu/state.go:848:7

847
848func (r *RemoteState) init() {
849 r.Lock()

internal/backend/remote-state/oss/backend.go1

75:7redefines-builtin-ididentifier max shadows a predeclared identifier

internal/backend/remote-state/oss/backend.go:75:7

74 min := 900
75 max := 3600
76 value, ok := v.(int)

internal/addrs/instance_key_test.go1

40:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:40:4

39 // Quotes must be escaped
40 StringKey(`"`),
41 `["\""]`,

internal/depsfile/locks.go1

12:2redundant-import-aliasimport alias is identical to the package name

internal/depsfile/locks.go:12:2

11
12 svchost "github.com/opentofu/svchost"
13

internal/legacy/helper/schema/resource.go1

708:10simplify-rangeomit the blank range value

internal/legacy/helper/schema/resource.go:708:10

707 tsm = schemaMap(r.Schema)
708 for k, _ := range tsm {
709 if isReservedDataSourceFieldName(k) {

internal/addrs/move_endpoint_module.go1

413:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:413:3

412 case ModuleInstance:
413 switch eSub.(type) {
414 case ModuleInstance, AbsModuleCall:

internal/backend/remote-state/consul/client_test.go1

130:3slice-preallocationpreallocate res with capacity len(range source) before appending once per iteration

internal/backend/remote-state/consul/client_test.go:130:3

129 }
130 res := make([]string, 0)
131 for _, p := range pairs {

internal/command/webbrowser/mock.go1

113:31standard-http-method-constantreplace the HTTP method literal with http.MethodGet

internal/command/webbrowser/mock.go:113:31

112 log.Printf("[DEBUG] webbrowser.MockLauncher: requesting %s", u)
113 req, err := http.NewRequest("GET", u, nil)
114 if err != nil {

internal/cloud/backend.go1

743:4task-commentTODO comment should be resolved or linked to an owned work item

internal/cloud/backend.go:743:4

742 } else {
743 // TODO: Ideally we could rely on the client to tell us what the actual
744 // problem was, but we currently can't get enough context from the error

internal/addrs/checkable.go1

46:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/checkable.go:46:1

45
46var (
47 _ Checkable = AbsResourceInstance{}

internal/addrs/instance_key.go1

169:42unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/instance_key.go:169:42

168 case iTy == StringKeyType:
169 return string(i.(StringKey)) < string(j.(StringKey))
170 default:

internal/command/e2etest/encryption_test.go1

28:31unexported-returnexported function returns an unexported type

internal/command/e2etest/encryption_test.go:28:31

27
28func (r tofuResult) Success() tofuResult {
29 if r.stderr != "" {

internal/backend/local/backend_local_test.go1

272:85unused-parameterparameter name is unused

internal/backend/local/backend_local_test.go:272:85

271
272func (b backendWithStateStorageThatFailsRefresh) DeleteWorkspace(_ context.Context, name string, force bool) error {
273 return fmt.Errorf("unimplemented")

internal/addrs/check.go1

96:7unused-receiverreceiver c is unused

internal/addrs/check.go:96:7

95
96func (c AbsCheck) checkableSigil() {}
97

internal/backend/remote-state/consul/client.go1

288:41use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client.go:288:41

287 // Then we update the link to point to the new chunks
288 payload, err = json.Marshal(map[string]interface{}{
289 "current-hash": fmt.Sprintf("%x", md5),

internal/backend/local/backend_local_test.go1

307:14use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:307:14

306func (s *stateStorageThatFailsRefresh) GetRootOutputValues(_ context.Context) (map[string]*states.OutputValue, error) {
307 return nil, fmt.Errorf("unimplemented")
308}

internal/command/jsonconfig/config.go1

601:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonconfig/config.go:601:2

600 }
601 sort.Slice(rs, func(i, j int) bool {
602 return rs[i].Address < rs[j].Address

internal/legacy/helper/schema/resource_test.go1

580:30var-declarationomit the explicit zero value from the variable declaration

internal/legacy/helper/schema/resource_test.go:580:30

579 // positive test
580 var s *tofu.InstanceState = nil
581

internal/backend/remote-state/azure/backend_test.go1

382:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:382:2

381 client_id := os.Getenv("TF_AZURE_TEST_CLIENT_ID")
382 cert_path := os.Getenv("TF_AZURE_TEST_CERT_PATH")
383 // cert_password may be empty

internal/backend/remote-state/cos/client.go1

237:50weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/cos/client.go:237:50

236 XCosMetaXXX: &http.Header{
237 "X-Cos-Meta-Md5": []string{fmt.Sprintf("%x", md5.Sum(data))},
238 },

cmd/tofu/main_test.go1

189:13add-constantstring literal "-flag" appears more than twice; define a constant

cmd/tofu/main_test.go:189:13

188 "-flag",
189 []string{"-flag", "foo", "bar"},
190 false,

internal/command/views/apply_test.go1

79:12boolean-literal-comparisonomit the boolean literal from the logical expression

internal/command/views/apply_test.go:79:12

78 t.Fatalf("unexpected return type %t", v)
79 } else if hv.view.runningInAutomation != true { // redundant but it replaces a previously more relevant check
80 t.Fatalf("unexpected inAutomation value on Operation view")

internal/command/meta_backend_test.go1

2143:4call-to-gcavoid explicit garbage collection

internal/command/meta_backend_test.go:2143:4

2142 if runtime.GOOS == "windows" {
2143 runtime.GC()
2144 }

internal/addrs/instance_key.go1

219:6cognitive-complexityfunction has cognitive complexity 14; maximum is 7

internal/addrs/instance_key.go:219:6

218// - Escaping anything that would be treated as a template interpolation or control sequence.
219func toHCLQuotedString(s string) string {
220 // This is an adaptation of a similar function inside the hclwrite package,

internal/backend/remote/backend.go1

475:18confusing-namingname workspaces differs from Workspaces only by capitalization

internal/backend/remote/backend.go:475:18

474// workspaces returns a filtered list of remote workspace names.
475func (b *Remote) workspaces() ([]string, error) {
476 options := &tfe.WorkspaceListOptions{}

internal/dag/walk.go1

315:45confusing-resultsadjacent unnamed results of the same type should be named

internal/dag/walk.go:315:45

314// The waiter is waiting on the dependency.
315func (w *Walker) edgeParts(e Edge) (Vertex, Vertex) {
316 if w.Reverse {

internal/command/views/backend_remote.go1

54:6constructor-interface-returnNewBackendRemote returns interface BackendRemote although its concrete result is consistently *BackendRemoteHuman; return the concrete type

internal/command/views/backend_remote.go:54:6

53// straightforward.
54func NewBackendRemote(view *View) BackendRemote {
55 return &BackendRemoteHuman{

internal/backend/local/backend_plan.go1

27:12context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend_plan.go:27:12

26 stopCtx context.Context,
27 cancelCtx context.Context,
28 op *backend.Operation,

internal/command/clistate/state.go1

73:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/command/clistate/state.go:73:2

72type locker struct {
73 ctx context.Context
74 timeout time.Duration

internal/addrs/move_endpoint.go1

174:6cyclomatic-complexityfunction complexity is 11; maximum is 10

internal/addrs/move_endpoint.go:174:6

173// stating the unification constraints.
174func UnifyMoveEndpoints(moduleAddr Module, relFrom, relTo *MoveEndpoint) (modFrom, modTo *MoveEndpointInModule) {
175

internal/cloud/e2e/main_test.go1

183:4deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:183:4

182 fmt.Printf("Could not create new tfe client: %v\n", err)
183 os.Exit(1)
184 }

internal/cloud/tfe_client_mock.go1

2018:98deprecated-api-usagegithub.com/hashicorp/go-tfe.DataRetentionPolicySetOptions is deprecated: Use DataRetentionPolicyDeleteOlder variations instead

internal/cloud/tfe_client_mock.go:2018:98

2017
2018func (m *MockWorkspaces) SetDataRetentionPolicy(ctx context.Context, workspaceID string, options tfe.DataRetentionPolicySetOptions) (*tfe.DataRetentionPolicy, error) {
2019 panic("not implemented")

internal/backend/backend_test.go1

91:12discarded-error-resulterror result returned by exec.Command("icacls", f.Name()).CombinedOutput is discarded

internal/backend/backend_test.go:91:12

90
91 acl, _ = exec.Command("icacls", f.Name()).CombinedOutput()
92 t.Logf("After /deny %s", acl)

internal/addrs/provider.go1

17:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/provider.go:17:1

16// Provider encapsulates a single provider type. In the future this will be
17// extended to include additional fields including Namespace and SourceHost
18type Provider = regaddr.Provider

internal/backend/remote-state/consul/client.go1

190:3early-returninvert the condition and return early to reduce nesting

internal/backend/remote-state/consul/client.go:190:3

189 if c.GZip {
190 if compressedState, err := compressState(data); err == nil {
191 payload = compressedState

internal/addrs/map_test.go1

71:12error-stringserror string should not be capitalized or end with punctuation

internal/addrs/map_test.go:71:12

70 if v, ok := m.GetOk(variableName); v != "Aisling" || !ok {
71 t.Errorf("GetOk for %q returned incorrect result (%q, %#v)", variableName, v, ok)
72 }

internal/encryption/method/errors.go1

12:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/method/errors.go:12:6

11// ErrEncryptionFailed, ErrDecryptionFailed, or ErrInvalidConfiguration.
12type ErrCryptoFailure struct {
13 Message string

internal/addrs/check.go1

41:16exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:41:16

40
41func (c Check) Equal(o Check) bool {
42 return c.Name == o.Name

internal/addrs/parse_ref_test.go1

1:1file-length-limitfile has 1037 lines; maximum is 500

internal/addrs/parse_ref_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/backend_show.go1

96:41flag-parameterboolean parameter isConfirmable controls function flow

internal/cloud/backend_show.go:96:41

95
96func statusFooter(status tfe.RunStatus, isConfirmable, locked bool) string {
97 statusText := strings.ReplaceAll(string(status), "_", " ")

cmd/tofu/registries_disco.go1

1:1formatfile is not formatted

cmd/tofu/registries_disco.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/registries_disco.go`

cmd/tofu/provider_source_test.go1

178:6function-lengthfunction has 4 statements and 109 lines; maximum is 50 statements or 75 lines

cmd/tofu/provider_source_test.go:178:6

177// into the child process instead.
178func TestInitProviderSourceForCLIConfigLocationWithRetries(t *testing.T) {
179 registryHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

internal/command/e2etest/fakeocireg/handler.go1

209:6function-result-limitfunction returns 4 values; maximum is 3

internal/command/e2etest/fakeocireg/handler.go:209:6

208
209func parseReqPath(reqPath string) (repoName, noun, arg string, ok bool) {
210 // The OCI distribution protocol uses an interesting path scheme

internal/addrs/module.go1

289:2identical-switch-branchesswitch repeats a case body

internal/addrs/module.go:289:2

288 next = tt.Name
289 case hcl.TraverseAttr:
290 next = tt.Name

internal/backend/init/init.go1

21:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:21:2

20 backendConsul "github.com/opentofu/opentofu/internal/backend/remote-state/consul"
21 backendCos "github.com/opentofu/opentofu/internal/backend/remote-state/cos"
22 backendGCS "github.com/opentofu/opentofu/internal/backend/remote-state/gcs"

internal/backend/remote-state/azure/backend_test.go1

96:10import-shadowingidentifier errors shadows an imported package

internal/backend/remote-state/azure/backend_test.go:96:10

95 config["timeout_seconds"] = tc.timeoutSeconds
96 b, _, errors := backend.TestBackendConfigWarningsAndErrors(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(config))
97 if tc.expectError {

internal/command/test.go1

476:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/command/test.go:476:5

475 if _, exists := runner.States[key]; !exists {
476 runner.States[key] = &TestFileState{
477 Run: nil,

internal/httpclient/useragent_test.go1

66:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/httpclient/useragent_test.go:66:9

65 for i, tc := range testCases {
66 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
67 t.Setenv(appendUaEnvVar, tc.envVarValue)

internal/backend/remote-state/http/backend_test.go1

61:35insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:61:35

60 "lock_method": cty.StringVal("BLIP"),
61 "unlock_address": cty.StringVal("http://127.0.0.1:8888/baz"),
62 "unlock_method": cty.StringVal("BLOOP"),

internal/configs/configload/loader.go1

27:13interface-method-limitinterface has 18 methods, exceeding the configured design limit of 10

internal/configs/configload/loader.go:27:13

26// instance directly.
27type Loader interface {
28 ImportSources(sources map[string][]byte)

internal/backend/remote/backend_context.go1

134:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/backend/remote/backend_context.go:134:7

133 if v.Category == tfe.CategoryTerraform {
134 if _, ok := op.Variables[v.Key]; !ok {
135 op.Variables[v.Key] = &remoteStoredVariableValue{

internal/cloud/tfe_client_mock.go1

1096:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1096:6

1095
1096type MockRuns struct {
1097 sync.Mutex

internal/addrs/parse_target.go1

146:3modifies-parameterassignment modifies parameter remain

internal/addrs/parse_target.go:146:3

145 mode = DataResourceMode
146 remain = remain[1:]
147 case "ephemeral":

internal/command/jsonformat/structured/unknown.go1

52:2modifies-value-receiverassignment modifies value receiver change

internal/command/jsonformat/structured/unknown.go:52:2

51 // the functions in this package to assume this means it has been deleted.
52 change.AfterExplicit = true
53

cmd/tofu/main_test.go1

38:13nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/main_test.go:38:13

37
38 cases := []struct {
39 Name string

internal/backend/remote-state/s3/client.go1

172:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote-state/s3/client.go:172:4

171 if errors.As(err, &nk) {
172 return nil, nil
173 }

internal/backend/remote-state/gcs/client.go1

38:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/gcs/client.go:38:4

37 if errors.Is(err, storage.ErrObjectNotExist) {
38 return nil, nil
39 } else {

internal/backend/remote-state/oss/backend.go1

546:6no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/oss/backend.go:546:6

545 return fmt.Errorf("retry timeout and got an error: %w", err)
546 } else {
547 time.Sleep(time.Duration(catcher.RetryWaitSeconds) * time.Second)

internal/configs/config_build.go1

345:6no-initreplace init with explicit initialization

internal/configs/config_build.go:345:6

344
345func init() {
346 DisabledModuleWalker = ModuleWalkerFunc(func(ctx context.Context, req *ModuleRequest) (*Module, *version.Version, hcl.Diagnostics) {

internal/backend/remote-state/cos/client.go1

193:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:193:3

192 err = fmt.Errorf("failed to open file at %v: %w", cosFile, err)
193 return
194 }

cmd/tofu/signal_windows.go1

14:5no-package-varpackage variables introduce mutable global state

cmd/tofu/signal_windows.go:14:5

13
14var ignoreSignals = []os.Signal{os.Interrupt}
15var forwardSignals []os.Signal

cmd/tofu/provider_source.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/provider_source.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/config_test.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/config_test.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/config_test.go:6:9

5
6package aws_kms
7

internal/backend/local/backend_local.go1

465:42range-value-addresstaking the address of range value name can be misleading

internal/backend/local/backend_local.go:465:42

464 }
465 rawValue, err := varUiInput.Input(ctx, &tofu.InputOpts{
466 Id: fmt.Sprintf("var.%s", name),

internal/legacy/tofu/state.go1

857:7receiver-namingreceiver name r is inconsistent with s

internal/legacy/tofu/state.go:857:7

856
857func (r *RemoteState) deepcopy() *RemoteState {
858 r.Lock()

internal/backend/remote-state/oss/backend.go1

249:6redefines-builtin-ididentifier min shadows a predeclared identifier

internal/backend/remote-state/oss/backend.go:249:6

248 ValidateFunc: func(v interface{}, k string) ([]string, []error) {
249 min := 900
250 max := 3600

internal/addrs/instance_key_test.go1

45:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:45:4

44 // Escape sequences must themselves be escaped
45 StringKey(`\r\n`),
46 `["\\r\\n"]`,

internal/genconfig/generate_config.go1

15:2redundant-import-aliasimport alias is identical to the package name

internal/genconfig/generate_config.go:15:2

14 "github.com/hashicorp/hcl/v2"
15 hclsyntax "github.com/hashicorp/hcl/v2/hclsyntax"
16 "github.com/hashicorp/hcl/v2/hclwrite"

internal/legacy/helper/schema/resource_data.go1

315:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/resource_data.go:315:9

314 hasDynamicAttributes := false
315 for k, _ := range d.schema {
316 if k == "__has_dynamic_attributes" {

internal/addrs/move_endpoint_module.go1

428:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:428:3

427 // A resource can only contain a resource instance.
428 switch eSub := eSub.(type) {
429 case AbsResourceInstance:

internal/backend/remote-state/inmem/backend.go1

102:6slice-preallocationpreallocate workspaces with capacity len(range source) before appending once per iteration

internal/backend/remote-state/inmem/backend.go:102:6

101
102 var workspaces []string
103

internal/communicator/ssh/http_proxy.go1

78:30standard-http-method-constantreplace the HTTP method literal with http.MethodConnect

internal/communicator/ssh/http_proxy.go:78:30

77 // Create a request object using the CONNECT method to instruct the proxy server to tunnel a protocol other than HTTP.
78 req, err := http.NewRequest("CONNECT", reqUrl.String(), nil)
79 if err != nil {

internal/cloud/backend_test.go1

449:61task-commentTODO comment should be resolved or linked to an owned work item

internal/cloud/backend_test.go:449:61

448 },
449 "with_tags_and_TF_WORKSPACE_env_var_not_matching_tags": { //TODO: once we have proper e2e backend testing we should also add the opposite test - with_tags_and_TF_WORKSPACE_env_var_matching_tags
450 workspaceToCreate: "my-workspace",

internal/addrs/input_variable.go1

46:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/input_variable.go:46:1

45// particular module instance.
46type AbsInputVariableInstance struct {
47 Module ModuleInstance

internal/addrs/move_endpoint_module.go1

520:33unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/move_endpoint_module.go:520:33

519 // just slice out the relevant parts.
520 mNewMatch = toMatch.relSubject.(ModuleInstance)
521 mSuffix = mRel[len(relSubject):]

internal/command/e2etest/encryption_test.go1

41:31unexported-returnexported function returns an unexported type

internal/command/e2etest/encryption_test.go:41:31

40
41func (r tofuResult) Failure() tofuResult {
42 if r.err == nil {

internal/backend/local/backend_local_test.go1

272:98unused-parameterparameter force is unused

internal/backend/local/backend_local_test.go:272:98

271
272func (b backendWithStateStorageThatFailsRefresh) DeleteWorkspace(_ context.Context, name string, force bool) error {
273 return fmt.Errorf("unimplemented")

internal/addrs/check.go1

119:7unused-receiverreceiver c is unused

internal/addrs/check.go:119:7

118
119func (c AbsCheck) CheckableKind() CheckableKind {
120 return CheckableCheck

internal/backend/remote-state/consul/client.go1

693:20use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client.go:693:20

692 if pair != nil {
693 var d map[string]interface{}
694 err = json.Unmarshal(pair.Value, &d)

internal/backend/local/backend_local_test.go1

311:9use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:311:9

310func (s *stateStorageThatFailsRefresh) WriteState(*states.State) error {
311 return fmt.Errorf("unimplemented")
312}

internal/command/jsonentities/diagnostic.go1

445:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonentities/diagnostic.go:445:2

444 }
445 sort.Slice(values, func(i, j int) bool {
446 return values[i].Traversal < values[j].Traversal

internal/legacy/helper/schema/shims_test.go1

145:30var-declarationomit the explicit zero value from the variable declaration

internal/legacy/helper/schema/shims_test.go:145:30

144
145 var s *tofu.InstanceState = nil
146

internal/backend/remote-state/azure/backend_test.go1

384:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:384:2

383 // cert_password may be empty
384 cert_password := os.Getenv("TF_AZURE_TEST_CERT_PASSWORD")
385 if client_id == "" || cert_path == "" {

internal/backend/remote-state/cos/client.go1

373:36weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/cos/client.go:373:36

372 cosPath := fmt.Sprintf("%s:%s", bucket, cosFile)
373 lockTagValue := fmt.Sprintf("%x", md5.Sum([]byte(cosPath)))
374

cmd/tofu/main_test.go1

336:67add-constantstring literal ".terraform.d" appears more than twice; define a constant

cmd/tofu/main_test.go:336:67

335func TestMkConfigDir_noparent(t *testing.T) {
336 tmpConfigDir := filepath.Join(t.TempDir(), "nonexistenthomedir", ".terraform.d")
337

internal/command/views/deprecation_level_test.go1

160:65boolean-literal-comparisonomit the boolean literal from the logical expression

internal/command/views/deprecation_level_test.go:160:65

159 if tt.lvl != arguments.DeprecationWarningLevelNone {
160 if got := v.DeprecationDiagnosticAllowed(tt.diag[0], seen); got == true {
161 t.Fatalf("expected duplicate diagnostic to be ignored")

internal/command/views/test_test.go1

3559:5call-to-gcavoid explicit garbage collection

internal/command/views/test_test.go:3559:5

3558 if runtime.GOOS == "windows" {
3559 runtime.GC()
3560 }

internal/addrs/map_test.go1

12:6cognitive-complexityfunction has cognitive complexity 18; maximum is 7

internal/addrs/map_test.go:12:6

11
12func TestMap(t *testing.T) {
13 variableName := InputVariable{Name: "name"}

internal/checks/state_report.go1

99:17confusing-namingname reportCheckResult differs from ReportCheckResult only by capitalization

internal/checks/state_report.go:99:17

98// ReportCheckFailure, and assumes its caller already holds the mutex.
99func (c *State) reportCheckResult(objectAddr addrs.Checkable, checkType addrs.CheckRuleType, index int, status Status) {
100 configAddr := objectAddr.ConfigCheckable()

internal/encryption/keyprovider/azure_vault/compliance_test.go1

17:42confusing-resultsadjacent unnamed results of the same type should be named

internal/encryption/keyprovider/azure_vault/compliance_test.go:17:42

16
17func getKeyAndURI(_ *testing.T) (string, string) {
18 if os.Getenv("TF_ACC") == "" || os.Getenv("TF_AZV_TEST") == "" {

internal/command/views/fmt.go1

20:6constructor-interface-returnNewFmt returns interface Fmt although its concrete result is consistently *FmtHuman; return the concrete type

internal/command/views/fmt.go:20:6

19// NewFmt returns an initialized Fmt implementation.
20func NewFmt(view *View) Fmt {
21 return &FmtHuman{view: view}

internal/backend/local/backend_refresh.go1

23:12context-as-argumentcontext.Context should be the first parameter

internal/backend/local/backend_refresh.go:23:12

22 stopCtx context.Context,
23 cancelCtx context.Context,
24 op *backend.Operation,

internal/command/meta.go1

128:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/command/meta.go:128:2

127 // will be connected to this parent context if it's present.
128 CallerContext context.Context
129

internal/addrs/move_endpoint_module.go1

340:32cyclomatic-complexityfunction complexity is 13; maximum is 10

internal/addrs/move_endpoint_module.go:340:32

339// is the "from" of another statement.
340func (e *MoveEndpointInModule) CanChainFrom(other *MoveEndpointInModule) bool {
341 eMod := e.synthModuleInstance()

internal/cloud/e2e/main_test.go1

192:3deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:192:3

191 fmt.Printf("Could not change directories: %v\n", err)
192 os.Exit(1)
193 }

internal/cloud/tfe_client_mock.go1

2018:135deprecated-api-usagegithub.com/hashicorp/go-tfe.DataRetentionPolicy is deprecated: Use DataRetentionPolicyDeleteOlder instead. This is the original representation of a data retention policy, only present in TFE v202311-1 and v202312-1

internal/cloud/tfe_client_mock.go:2018:135

2017
2018func (m *MockWorkspaces) SetDataRetentionPolicy(ctx context.Context, workspaceID string, options tfe.DataRetentionPolicySetOptions) (*tfe.DataRetentionPolicy, error) {
2019 panic("not implemented")

internal/backend/backend_test.go1

94:14discarded-error-resulterror result returned by exec.Command("icacls", f.Name(), "/remove:d", currentUser.Username).CombinedOutput is discarded

internal/backend/backend_test.go:94:14

93 defer func() {
94 acl, _ := exec.Command("icacls", f.Name(), "/remove:d", currentUser.Username).CombinedOutput()
95 t.Logf("After remove:d %s", acl)

internal/addrs/provider.go1

138:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/provider.go:138:1

137// - namespace/name
138// - hostname/namespace/name
139func ParseProviderSourceString(str string) (regaddr.Provider, tfdiags.Diagnostics) {

internal/backend/remote-state/kubernetes/backend.go1

360:3early-returninvert the condition and return early to reduce nesting

internal/backend/remote-state/kubernetes/backend.go:360:3

359 exec := &clientcmdapi.ExecConfig{}
360 if spec, ok := v.([]interface{})[0].(map[string]interface{}); ok {
361 exec.APIVersion = spec["api_version"].(string)

internal/addrs/map_test.go1

74:12error-stringserror string should not be capitalized or end with punctuation

internal/addrs/map_test.go:74:12

73 if v, ok := m.GetOk(eachKey); v != "" || ok {
74 t.Errorf("GetOk for %q returned incorrect result (%q, %#v)", eachKey, v, ok)
75 }

internal/encryption/method/errors.go1

34:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/method/errors.go:34:6

33// ErrEncryptionFailed indicates that encrypting a set of data failed.
34type ErrEncryptionFailed struct {
35 Cause error

internal/addrs/check.go1

45:16exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:45:16

44
45func (c Check) UniqueKey() UniqueKey {
46 return c // A Check is its own UniqueKey

internal/addrs/parse_target_test.go1

1:1file-length-limitfile has 546 lines; maximum is 500

internal/addrs/parse_target_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/backend_show.go1

96:56flag-parameterboolean parameter locked controls function flow

internal/cloud/backend_show.go:96:56

95
96func statusFooter(status tfe.RunStatus, isConfirmable, locked bool) string {
97 statusText := strings.ReplaceAll(string(status), "_", " ")

cmd/tofu/signal_unix.go1

1:1formatfile is not formatted

cmd/tofu/signal_unix.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/signal_unix.go`

internal/addrs/checkable.go1

96:6function-lengthfunction has 34 statements and 101 lines; maximum is 50 statements or 75 lines

internal/addrs/checkable.go:96:6

95// results between runs.
96func ParseCheckableStr(kind CheckableKind, src string) (Checkable, tfdiags.Diagnostics) {
97 var diags tfdiags.Diagnostics

internal/command/jsonplan/plan.go1

186:6function-result-limitfunction returns 5 values; maximum is 3

internal/command/jsonplan/plan.go:186:6

185// the part of the plan required by the jsonformat.Plan renderer.
186func MarshalForRenderer(
187 p *plans.Plan,

internal/addrs/module_instance.go1

489:2identical-switch-branchesswitch repeats a case body

internal/addrs/module_instance.go:489:2

488
489 case AbsResource:
490 return m.TargetContains(to.Module)

internal/backend/init/init.go1

22:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:22:2

21 backendCos "github.com/opentofu/opentofu/internal/backend/remote-state/cos"
22 backendGCS "github.com/opentofu/opentofu/internal/backend/remote-state/gcs"
23 backendHTTP "github.com/opentofu/opentofu/internal/backend/remote-state/http"

internal/backend/remote-state/consul/backend.go1

109:2import-shadowingidentifier encryption shadows an imported package

internal/backend/remote-state/consul/backend.go:109:2

108 *schema.Backend
109 encryption encryption.StateEncryption
110

internal/configs/config.go1

397:5inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/configs/config.go:397:5

396 // add to this in the loop below.
397 reqs[fqn] = nil
398 }

internal/legacy/helper/hashcode/hashcode.go1

46:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/legacy/helper/hashcode/hashcode.go:46:9

45
46 return fmt.Sprintf("%d", String(buf.String()))
47}

internal/backend/remote-state/http/backend_test.go1

110:28insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:110:28

109 conf = map[string]cty.Value{
110 "address": cty.StringVal("http://127.0.0.1:8888/foo"),
111 "headers": cty.MapVal(map[string]cty.Value{

internal/lang/data.go1

30:11interface-method-limitinterface has 11 methods, exceeding the configured design limit of 10

internal/lang/data.go:30:11

29// cty.DynamicVal is returned along with errors describing the problem.
30type Data interface {
31 StaticValidateReferences(ctx context.Context, refs []*addrs.Reference, self addrs.Referenceable, source addrs.Referenceable) tfdiags.Diagnostics

internal/cloud/backend_common.go1

126:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:126:7

125 for _, item := range rl.Items {
126 if !found {
127 if r.ID == item.ID {

internal/cloud/tfe_client_mock.go1

1360:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1360:6

1359
1360type MockRunEvents struct{}
1361

internal/addrs/parse_target.go1

149:3modifies-parameterassignment modifies parameter remain

internal/addrs/parse_target.go:149:3

148 mode = EphemeralResourceMode
149 remain = remain[1:]
150 }

internal/dag/marshal.go1

92:41modifies-value-receiverassignment modifies value receiver v

internal/dag/marshal.go:92:41

91func (v vertices) Len() int { return len(v) }
92func (v vertices) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
93

cmd/tofu/main_test.go1

164:13nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/main_test.go:164:13

163
164 cases := []struct {
165 Name string

internal/backend/remote/backend.go1

422:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote/backend.go:422:3

421 log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", b.hostname, err)
422 return "", nil
423 }

internal/backend/remote-state/http/client.go1

193:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/http/client.go:193:3

192 case http.StatusNoContent:
193 return nil, nil
194 case http.StatusNotFound:

internal/backend/remote-state/oss/client.go1

421:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/oss/client.go:421:4

420 return nil, fmt.Errorf("estimating object %s is exist got an error: %w", c.stateFile, err)
421 } else if !exist {
422 return nil, nil

internal/depsfile/testing.go1

20:6no-initreplace init with explicit initialization

internal/depsfile/testing.go:20:6

19
20func init() {
21 // For now, direct comparison of the unexported fields is good enough

internal/backend/remote-state/cos/client.go1

204:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:204:3

203 }
204 return
205 }

cmd/tofu/signal_windows.go1

15:5no-package-varpackage variables introduce mutable global state

cmd/tofu/signal_windows.go:15:5

14var ignoreSignals = []os.Signal{os.Interrupt}
15var forwardSignals []os.Signal
16

cmd/tofu/registries_disco.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/registries_disco.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/descriptor.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/descriptor.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/descriptor.go:6:9

5
6package aws_kms
7

internal/backend/remote-state/consul/client.go1

277:20range-value-addresstaking the address of range value p can be misleading

internal/backend/remote-state/consul/client.go:277:20

276 chunkPaths = append(chunkPaths, path)
277 _, err := kv.Put(&consulapi.KVPair{
278 Key: path,

internal/legacy/tofu/state.go1

871:7receiver-namingreceiver name r is inconsistent with s

internal/legacy/tofu/state.go:871:7

870
871func (r *RemoteState) Empty() bool {
872 if r == nil {

internal/backend/remote-state/oss/backend.go1

250:6redefines-builtin-ididentifier max shadows a predeclared identifier

internal/backend/remote-state/oss/backend.go:250:6

249 min := 900
250 max := 3600
251 value, ok := v.(int)

internal/addrs/instance_key_test.go1

50:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:50:4

49 // Template interpolation sequences "${" must be escaped.
50 StringKey(`${hello}`),
51 `["$${hello}"]`,

internal/getproviders/registry_client_test.go1

21:2redundant-import-aliasimport alias is identical to the package name

internal/getproviders/registry_client_test.go:21:2

20 "github.com/opentofu/svchost"
21 disco "github.com/opentofu/svchost/disco"
22)

internal/legacy/helper/schema/schema.go1

624:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/schema.go:624:9

623 keys := make([]string, 0, len(m))
624 for k, _ := range m {
625 keys = append(keys, k)

internal/addrs/move_endpoint_module.go1

725:3single-case-switchswitch with one case can be replaced by an if statement

internal/addrs/move_endpoint_module.go:725:3

724 case AbsModuleCall:
725 switch t := to.relSubject.(type) {
726 case ModuleInstance:

internal/backend/remote-state/kubernetes/backend.go1

320:2slice-preallocationpreallocate expandedPaths with capacity len(range source) before appending once per iteration

internal/backend/remote-state/kubernetes/backend.go:320:2

319
320 expandedPaths := []string{}
321 for _, p := range configPaths {

internal/cloud/e2e/helper_test.go1

276:3task-commentTODO comment should be resolved or linked to an owned work item

internal/cloud/e2e/helper_test.go:276:3

275 for {
276 // TODO: update go-tfe Read() to retrieve a tofu version by name.
277 // Currently you can only retrieve by ID.

internal/addrs/instance_key.go1

56:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/instance_key.go:56:1

55// of a configuration object that does not use "count" or "for_each" at all.
56var NoKey InstanceKey
57

internal/addrs/move_endpoint_module.go1

543:33unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/move_endpoint_module.go:543:33

542 // the same key as our call.
543 mNewMatch = toMatch.relSubject.(AbsModuleCall).Instance(callStep.InstanceKey)
544 mSuffix = mRel[len(relSubject.Module)+1:]

internal/command/e2etest/encryption_test.go1

60:48unexported-returnexported function returns an unexported type

internal/command/e2etest/encryption_test.go:60:48

59
60func (r tofuResult) StderrContains(msg string) tofuResult {
61 stdErrSanitized := SanitizeStderr(r.stderr)

internal/backend/local/backend_local_test.go1

286:64unused-parameterparameter info is unused

internal/backend/local/backend_local_test.go:286:64

285
286func (s *stateStorageThatFailsRefresh) Lock(_ context.Context, info *statemgr.LockInfo) (string, error) {
287 if s.locked {

internal/addrs/check.go1

132:7unused-receiverreceiver k is unused

internal/addrs/check.go:132:7

131
132func (k configCheckUniqueKey) uniqueKeySigil() {}
133

internal/backend/remote-state/consul/client.go1

702:38use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client.go:702:38

701 chunks := make([]string, 0)
702 for _, c := range d["chunks"].([]interface{}) {
703 chunks = append(chunks, c.(string))

internal/backend/local/backend_local_test.go1

315:9use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:315:9

314func (s *stateStorageThatFailsRefresh) MutateState(fn func(*states.State) *states.State) error {
315 return fmt.Errorf("unimplemented")
316}

internal/command/jsonplan/plan.go1

394:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonplan/plan.go:394:2

393 sortedResources = append(sortedResources, resources...)
394 sort.Slice(sortedResources, func(i, j int) bool {
395 if !sortedResources[i].Addr.Equal(sortedResources[j].Addr) {

internal/legacy/helper/schema/shims_test.go1

214:30var-declarationomit the explicit zero value from the variable declaration

internal/legacy/helper/schema/shims_test.go:214:30

213
214 var s *tofu.InstanceState = nil
215

internal/backend/remote-state/azure/backend_test.go1

389:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/backend_test.go:389:2

388 // Make sure we can open and read the file
389 cert_file, err := os.Open(cert_path)
390 if err != nil {

internal/backend/remote-state/cos/client.go1

383:36weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/cos/client.go:383:36

382 cosPath := fmt.Sprintf("%s:%s", bucket, cosFile)
383 lockTagValue := fmt.Sprintf("%x", md5.Sum([]byte(cosPath)))
384

cmd/tofu/provider_source_test.go1

244:20add-constantstring literal "/providers/v1/test/exists_0.0.0.zip giving up after 2 attempt(s)" appears more than twice; define a constant

cmd/tofu/provider_source_test.go:244:20

243 },
244 expectedErrMsg: "/providers/v1/test/exists_0.0.0.zip giving up after 2 attempt(s)",
245 },

internal/command/views/plan_test.go1

30:12boolean-literal-comparisonomit the boolean literal from the logical expression

internal/command/views/plan_test.go:30:12

29 t.Fatalf("unexpected return type %t", v)
30 } else if hv.view.runningInAutomation != true { // redundant but it replaces a previously more relevant check
31 t.Fatalf("unexpected inAutomation value on Operation view")

internal/initwd/from_module_test.go1

316:4call-to-gcavoid explicit garbage collection

internal/initwd/from_module_test.go:316:4

315 if runtime.GOOS == "windows" {
316 runtime.GC()
317 }

internal/addrs/module.go1

84:17cognitive-complexityfunction has cognitive complexity 8; maximum is 7

internal/addrs/module.go:84:17

83// is contained within the receiver.
84func (m Module) TargetContains(other Targetable) bool {
85 switch to := other.(type) {

internal/cloud/state.go1

386:17confusing-namingname refreshState differs from RefreshState only by capitalization

internal/cloud/state.go:386:17

385// the s.mu lock.
386func (s *State) refreshState(ctx context.Context) error {
387 payload, err := s.getStatePayload()

internal/getproviders/didyoumean.go1

181:130confusing-resultsadjacent unnamed results of the same type should be named

internal/getproviders/didyoumean.go:181:130

180// in a future OpenTofu version.
181func (s *RegistrySource) lookupLegacyProviderNamespace(ctx context.Context, hostname svchost.Hostname, typeName string) (string, string, error) {
182 client, err := s.registryClient(ctx, hostname)

internal/command/views/graph.go1

23:6constructor-interface-returnNewGraph returns interface Graph although its concrete result is consistently *GraphHuman; return the concrete type

internal/command/views/graph.go:23:6

22// NewGraph returns an initialized Graph implementation for the given ViewType.
23func NewGraph(view *View) Graph {
24 return &GraphHuman{view: view}

internal/backend/remote-state/s3/backend_test.go1

1821:48context-as-argumentcontext.Context should be the first parameter

internal/backend/remote-state/s3/backend_test.go:1821:48

1820
1821func numberOfObjectsInBucket(t *testing.T, ctx context.Context, s3Client *s3.Client, bucketName string) int {
1822 resp, err := s3Client.ListObjects(ctx, &s3.ListObjectsInput{Bucket: &bucketName})

internal/command/test.go1

376:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/command/test.go:376:2

375 // respond to external calls from the test command.
376 StoppedCtx context.Context
377 CancelledCtx context.Context

internal/addrs/move_endpoint_module.go1

384:32cyclomatic-complexityfunction complexity is 14; maximum is 10

internal/addrs/move_endpoint_module.go:384:32

383// select.
384func (e *MoveEndpointInModule) NestedWithin(other *MoveEndpointInModule) bool {
385 eMod := e.synthModuleInstance()

internal/cloud/e2e/main_test.go1

201:3deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:201:3

200 fmt.Printf("Could not create temp directory: %v\n", err)
201 os.Exit(1)
202 }

internal/encryption/keyprovider/gcp_kms/config.go1

115:37deprecated-api-usagegoogle.golang.org/api/option.WithCredentialsJSON is deprecated: This function is being deprecated because of a potential security risk.

internal/encryption/keyprovider/gcp_kms/config.go:115:37

114 // closely as possible.
115 credOptions = append(credOptions, option.WithCredentialsJSON([]byte(contents)))
116 }

internal/backend/backend_test.go1

156:3discarded-error-resulterror result returned by os.Remove is discarded

internal/backend/backend_test.go:156:3

155 t.Cleanup(func() {
156 os.Remove(f.Name())
157 })

internal/addrs/provider.go1

209:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/provider.go:209:1

208
209// IsProviderPartNormalized compares a given string to the result of ParseProviderPart(string)
210func IsProviderPartNormalized(str string) (bool, error) {

internal/backend/remote-state/oss/backend.go1

596:2early-returninvert the condition and return early to reduce nesting

internal/backend/remote-state/oss/backend.go:596:2

595 mode := ""
596 if v, ok := providerConfig["mode"]; ok {
597 mode = v.(string)

internal/addrs/module_source_test.go1

392:13error-stringserror string should not be capitalized or end with punctuation

internal/addrs/module_source_test.go:392:13

391 if remote.Subdir != "foo" {
392 t.Errorf("FromRegistry modified the receiver; should be pure function")
393 }

internal/encryption/method/errors.go1

50:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/method/errors.go:50:6

49// ErrDecryptionFailed indicates that decrypting a set of data failed.
50type ErrDecryptionFailed struct {
51 Cause error

internal/addrs/check.go1

55:6exported-declaration-commentexported type should have a comment beginning with its name

internal/addrs/check.go:55:6

54// a check block within the entire configuration.
55type ConfigCheck struct {
56 Module Module

internal/addrs/provider_test.go1

1:1file-length-limitfile has 566 lines; maximum is 500

internal/addrs/provider_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/errors.go1

56:60flag-parameterboolean parameter ignoreVersionConflict controls function flow

internal/cloud/errors.go:56:60

55
56func incompatibleWorkspaceTerraformVersion(message string, ignoreVersionConflict bool) tfdiags.Diagnostic {
57 severity := tfdiags.Error

cmd/tofu/signal_windows.go1

1:1formatfile is not formatted

cmd/tofu/signal_windows.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/signal_windows.go`

internal/addrs/map_test.go1

12:6function-lengthfunction has 48 statements and 77 lines; maximum is 50 statements or 75 lines

internal/addrs/map_test.go:12:6

11
12func TestMap(t *testing.T) {
13 variableName := InputVariable{Name: "name"}

internal/command/show.go1

371:23function-result-limitfunction returns 5 values; maximum is 3

internal/command/show.go:371:23

370// directory or a statefile.
371func (c *ShowCommand) getPlanFromPath(ctx context.Context, path string, enc encryption.Encryption, rootCall configs.StaticModuleCall) (*plans.Plan, *cloudplan.RemotePlanJSON, *statefile.File, *configs.Config, error) {
372 var err error

internal/addrs/module_instance.go1

492:2identical-switch-branchesswitch repeats a case body

internal/addrs/module_instance.go:492:2

491
492 case AbsResourceInstance:
493 return m.TargetContains(to.Module)

internal/backend/init/init.go1

23:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:23:2

22 backendGCS "github.com/opentofu/opentofu/internal/backend/remote-state/gcs"
23 backendHTTP "github.com/opentofu/opentofu/internal/backend/remote-state/http"
24 backendInmem "github.com/opentofu/opentofu/internal/backend/remote-state/inmem"

internal/backend/remote-state/consul/client.go1

116:2import-shadowingidentifier md5 shadows an imported package

internal/backend/remote-state/consul/client.go:116:2

115
116 md5 := md5.Sum(payload)
117

internal/configs/config.go1

441:4inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/configs/config.go:441:4

440 if _, exists := reqs[fqn]; !exists {
441 reqs[fqn] = nil
442 qualifs.AddImplicitProvider(i.Provider, getproviders.ResourceRef{

internal/legacy/helper/schema/resource_test.go1

1670:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/legacy/helper/schema/resource_test.go:1670:9

1669 for i, s := range testStates {
1670 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
1671 newState, err := r.Refresh(s, nil)

internal/backend/remote-state/http/backend_test.go1

131:21insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:131:21

130 conf := map[string]string{
131 "address": "http://127.0.0.1:8888/foo",
132 "update_method": "BLAH",

internal/lang/eval/internal/evalglue/module_instance.go1

42:29interface-method-limitinterface has 14 methods, exceeding the configured design limit of 10

internal/lang/eval/internal/evalglue/module_instance.go:42:29

41// successfully.
42type CompiledModuleInstance interface {
43 // CheckAll collects diagnostics for everything in this module instance

internal/cloud/backend_common.go1

127:8max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:127:8

126 if !found {
127 if r.ID == item.ID {
128 found = true

internal/cloud/tfe_client_mock.go1

1385:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1385:6

1384
1385type MockStateVersions struct {
1386 client *MockClient

internal/addrs/parse_target.go1

157:2modifies-parameterassignment modifies parameter remain

internal/addrs/parse_target.go:157:2

156
157 remain = remain[2:]
158 switch len(remain) {

internal/dag/marshal.go1

92:47modifies-value-receiverassignment modifies value receiver v

internal/dag/marshal.go:92:47

91func (v vertices) Len() int { return len(v) }
92func (v vertices) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
93

cmd/tofu/provider_source.go1

138:37nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/provider_source.go:138:37

137 // finally add at the end.
138 foundLocally := map[addrs.Provider]struct{}{}
139

internal/backend/remote/backend_state.go1

44:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/backend/remote/backend_state.go:44:4

43 // If no state exists, then return nil.
44 return nil, nil
45 }

internal/backend/remote-state/http/client.go1

195:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/http/client.go:195:3

194 case http.StatusNotFound:
195 return nil, nil
196 case http.StatusUnauthorized:

internal/backend/remote-state/pg/backend_test.go1

255:6no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/pg/backend_test.go:255:6

254 return
255 } else if diags.HasErrors() {
256 t.Fatal(diags.ErrWithWarnings())

internal/encryption/default_registry.go1

23:6no-initreplace init with explicit initialization

internal/encryption/default_registry.go:23:6

22
23func init() {
24 if err := DefaultRegistry.RegisterKeyProvider(pbkdf2.New()); err != nil {

internal/backend/remote-state/cos/client.go1

211:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:211:3

210 err = fmt.Errorf("failed to open file at %v: checksum %s invalid", cosFile, checksum)
211 return
212 }

cmd/tofu/testing.go1

16:5no-package-varpackage variables introduce mutable global state

cmd/tofu/testing.go:16:5

15// e2e testing features are not available.
16var e2eTestingFeatures string
17

cmd/tofu/signal_unix.go1

8:9package-commentspackage should have a documentation comment

cmd/tofu/signal_unix.go:8:9

7
8package main
9

internal/encryption/keyprovider/aws_kms/mock_test.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/mock_test.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/mock_test.go:6:9

5
6package aws_kms
7

internal/backend/remote-state/cos/backend_test.go1

56:9range-value-addresstaking the address of range value c can be misleading

internal/backend/remote-state/cos/backend_test.go:56:9

55 t.Run(fmt.Sprintf("%s %s %s", c.prefix, c.key, c.stateName), func(t *testing.T) {
56 b := &Backend{
57 prefix: c.prefix,

internal/legacy/tofu/state.go1

881:7receiver-namingreceiver name r is inconsistent with s

internal/legacy/tofu/state.go:881:7

880
881func (r *RemoteState) Equals(other *RemoteState) bool {
882 r.Lock()

internal/backend/remote-state/s3/validate.go1

253:35redefines-builtin-ididentifier min shadows a predeclared identifier

internal/backend/remote-state/s3/validate.go:253:35

252
253func validateDuration(val string, min, max time.Duration, path cty.Path, diags *tfdiags.Diagnostics) {
254 d, err := time.ParseDuration(val)

internal/addrs/instance_key_test.go1

55:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:55:4

54 // Template control sequences "%{" must be escaped.
55 StringKey(`%{ for something in something }%{ endfor }`),
56 `["%%{ for something in something }%%{ endfor }"]`,

internal/getproviders/registry_source.go1

15:2redundant-import-aliasimport alias is identical to the package name

internal/getproviders/registry_source.go:15:2

14 "github.com/opentofu/svchost"
15 disco "github.com/opentofu/svchost/disco"
16

internal/legacy/helper/schema/schema.go1

1494:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/schema.go:1494:9

1493 raws := make([]interface{}, rawV.Len())
1494 for i, _ := range raws {
1495 raws[i] = rawV.Index(i).Interface()

internal/cloud/tfe_client_mock.go1

1301:4single-case-switchswitch with one case can be replaced by an if statement

internal/cloud/tfe_client_mock.go:1301:4

1300 for _, n := range options.Include {
1301 switch n {
1302 case tfe.RunWorkspace:

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

159:6slice-preallocationpreallocate lines with capacity len(range source) before appending once per iteration

internal/builtin/provisioners/remote-exec/resource_provisioner.go:159:6

158func generateScripts(inline cty.Value) ([]string, error) {
159 var lines []string
160 for _, l := range inline.AsValueSlice() {

internal/cloud/tfe_client_mock.go1

704:2task-commentTODO comment should be resolved or linked to an owned work item

internal/cloud/tfe_client_mock.go:704:2

703func (m *MockTaskStages) Read(ctx context.Context, taskStageID string, options *tfe.TaskStageReadOptions) (*tfe.TaskStage, error) {
704 //TODO implement me
705 panic("implement me")

internal/addrs/local_value.go1

38:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/local_value.go:38:1

37// AbsLocalValue is the absolute address of a local value within a module instance.
38type AbsLocalValue struct {
39 Module ModuleInstance

internal/addrs/move_endpoint_module.go1

614:37unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/move_endpoint_module.go:614:37

613 // by the "to" relative address in toMatch.
614 toRelSubject := toMatch.relSubject.(AbsResource)
615 var mNew ModuleInstance

internal/command/e2etest/encryption_test.go1

69:42unexported-returnexported function returns an unexported type

internal/command/e2etest/encryption_test.go:69:42

68
69func (r tofuResult) Contains(msg string) tofuResult {
70 if !strings.Contains(r.stdout, msg) {

internal/backend/local/backend_local_test.go1

294:66unused-parameterparameter id is unused

internal/backend/local/backend_local_test.go:294:66

293
294func (s *stateStorageThatFailsRefresh) Unlock(_ context.Context, id string) error {
295 if !s.locked {

internal/addrs/check.go1

136:7unused-receiverreceiver k is unused

internal/addrs/check.go:136:7

135
136func (k absCheckUniqueKey) uniqueKeySigil() {}
137

internal/backend/remote-state/consul/client_test.go1

44:115use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:44:115

43 // Get the backend
44 b := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
45 "address": srv.HTTPAddr,

internal/backend/local/backend_local_test.go1

319:9use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:319:9

318func (s *stateStorageThatFailsRefresh) RefreshState(_ context.Context) error {
319 return fmt.Errorf("intentionally failing for testing purposes")
320}

internal/command/jsonplan/plan.go1

791:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonplan/plan.go:791:2

790 // deterministic. Our own equivalence tests rely on it.
791 sort.Slice(p.RelevantAttributes, func(i, j int) bool {
792 return p.RelevantAttributes[i].Resource < p.RelevantAttributes[j].Resource

internal/legacy/tofu/resource.go1

446:29var-declarationomit the explicit zero value from the variable declaration

internal/legacy/tofu/resource.go:446:29

445 var current interface{} = raw
446 var previous interface{} = nil
447 for i, part := range parts {

internal/backend/remote-state/azure/client_test.go1

220:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/client_test.go:220:2

219
220 client_id := os.Getenv("TF_AZURE_TEST_CLIENT_ID")
221 client_secret := os.Getenv("TF_AZURE_TEST_CLIENT_SECRET")

internal/backend/remote-state/http/client.go1

75:11weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/http/client.go:75:11

74 // Generate the MD5
75 hash := md5.Sum(data)
76 b64 := base64.StdEncoding.EncodeToString(hash[:])

cmd/tofu/provider_source_test.go1

304:5add-constantstring literal "TF_PROVIDER_DOWNLOAD_RETRY" appears more than twice; define a constant

cmd/tofu/provider_source_test.go:304:5

303 envVars: map[string]string{
304 "TF_PROVIDER_DOWNLOAD_RETRY": "7",
305 },

internal/getproviders/types_test.go1

134:7boolean-literal-comparisonomit the boolean literal from the logical expression

internal/getproviders/types_test.go:134:7

133 if err != nil {
134 if test.Err == false {
135 t.Errorf("unexpected error: %s", err.Error())

internal/addrs/module.go1

226:6cognitive-complexityfunction has cognitive complexity 12; maximum is 7

internal/addrs/module.go:226:6

225// error if it encounters one.
226func parseModulePrefix(traversal hcl.Traversal) (Module, hcl.Traversal, tfdiags.Diagnostics) {
227 remain := traversal

internal/cloud/tfe_client_mock.go1

416:25confusing-namingname read differs from Read only by capitalization

internal/cloud/tfe_client_mock.go:416:25

415
416func (m *mockLogReader) read(l []byte) (int, error) {
417 done, err := m.done()

internal/getproviders/didyoumean.go1

196:104confusing-resultsadjacent unnamed results of the same type should be named

internal/getproviders/didyoumean.go:196:104

195// depend on it.
196func (c *registryClient) legacyProviderDefaultNamespace(ctx context.Context, typeName string) (string, string, error) {
197 endpointPath, err := url.Parse(path.Join("-", typeName, "versions"))

internal/command/views/json/hook.go1

45:6constructor-interface-returnNewApplyStart returns interface Hook although its concrete result is consistently *applyStart; return the concrete type

internal/command/views/json/hook.go:45:6

44
45func NewApplyStart(addr addrs.AbsResourceInstance, action plans.Action, idKey string, idValue string) Hook {
46 hook := &applyStart{

internal/backend/remote/backend_apply.go1

24:66context-as-argumentcontext.Context should be the first parameter

internal/backend/remote/backend_apply.go:24:66

23
24func (b *Remote) opApply(ctx context.Context, stopCtx, cancelCtx context.Context, op *backend.Operation, w *tfe.Workspace) (*tfe.Run, error) {
25 log.Printf("[INFO] backend/remote: starting Apply operation")

internal/command/test.go1

377:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/command/test.go:377:2

376 StoppedCtx context.Context
377 CancelledCtx context.Context
378

internal/addrs/move_endpoint_module.go1

477:25cyclomatic-complexityfunction complexity is 14; maximum is 10

internal/addrs/move_endpoint_module.go:477:25

476// must have matching object types. If not, MoveDestination will panic.
477func (m ModuleInstance) MoveDestination(fromMatch, toMatch *MoveEndpointInModule) (ModuleInstance, bool) {
478 // NOTE: This implementation assumes the invariant that fromMatch and

internal/cloud/e2e/main_test.go1

208:3deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:208:3

207 fmt.Printf("Could not get current directory: %v\n", err)
208 os.Exit(1)
209 }

internal/lang/funcs/crypto.go1

187:15deprecated-api-usagecrypto/rsa.DecryptPKCS1v15 is deprecated: PKCS #1 v1.5 encryption is dangerous and should not be used. Whether this function returns an error or not discloses secret information. If an attacker can cause this function to run repeatedly and learn whether each instance returned an error then they can decrypt and forge signatures as if they had the private key. See [draft-irtf-cfrg-rsa-guidance-05] for more information. Use [EncryptOAEP] and [DecryptOAEP] instead.

internal/lang/funcs/crypto.go:187:15

186
187 out, err := rsa.DecryptPKCS1v15(nil, privateKey, b)
188 if err != nil {

internal/backend/local/backend_test.go1

52:2discarded-error-resulterror result returned by f.Close is discarded

internal/backend/local/backend_test.go:52:2

51 state, err := statefile.Read(f, encryption.StateEncryptionDisabled())
52 f.Close()
53 if err != nil {

internal/addrs/provider_config.go1

460:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/provider_config.go:460:1

459// - module.module-name.provider["example.com/namespace/name"]
460// - module.module-name.provider["example.com/namespace/name"].alias
461func (pc AbsProviderConfig) String() string {

internal/backend/remote-state/oss/backend_state.go1

87:3early-returninvert the condition and return early to reduce nesting

internal/backend/remote-state/oss/backend_state.go:87:3

86 }
87 if resp.IsTruncated {
88 if len(options) == 3 {

internal/addrs/module_source_test.go1

395:13error-stringserror string should not be capitalized or end with punctuation

internal/addrs/module_source_test.go:395:13

394 if registry.Subdir != "bar" {
395 t.Errorf("FromRegistry modified the given address; should be pure function")
396 }

internal/encryption/method/errors.go1

66:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/method/errors.go:66:6

65// ErrDecryptionKeyUnavailable indicates that no decryption key is available.
66type ErrDecryptionKeyUnavailable struct {
67}

internal/addrs/check.go1

62:22exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:62:22

61
62func (c ConfigCheck) UniqueKey() UniqueKey {
63 return configCheckUniqueKey(c.String())

internal/addrs/resource.go1

1:1file-length-limitfile has 598 lines; maximum is 500

internal/addrs/resource.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/state.go1

115:59flag-parameterboolean parameter force controls function flow

internal/cloud/state.go:115:59

114// WriteStateForMigration is part of our implementation of statemgr.Migrator.
115func (s *State) WriteStateForMigration(f *statefile.File, force bool) error {
116 s.mu.Lock()

cmd/tofu/webbrowser.go1

1:1formatfile is not formatted

cmd/tofu/webbrowser.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/webbrowser.go`

internal/addrs/module_source_test.go1

16:6function-lengthfunction has 5 statements and 364 lines; maximum is 50 statements or 75 lines

internal/addrs/module_source_test.go:16:6

15
16func TestParseModuleSource(t *testing.T) {
17

internal/command/show.go1

435:6function-result-limitfunction returns 4 values; maximum is 3

internal/command/show.go:435:6

434// getDataFromPlanfileReader returns a plan, statefile, and config, extracted from a local plan file.
435func getDataFromPlanfileReader(ctx context.Context, planReader *planfile.Reader, rootCall configs.StaticModuleCall) (*plans.Plan, *statefile.File, *configs.Config, error) {
436 // Get plan

internal/addrs/move_endpoint_module.go1

173:2identical-switch-branchesswitch repeats a case body

internal/addrs/move_endpoint_module.go:173:2

172 return relSubject.Resource.Absolute(retModAddr)
173 case AbsResource:
174 retModAddr := make(ModuleInstance, 0, len(modInst)+len(relSubject.Module))

internal/backend/init/init.go1

24:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:24:2

23 backendHTTP "github.com/opentofu/opentofu/internal/backend/remote-state/http"
24 backendInmem "github.com/opentofu/opentofu/internal/backend/remote-state/inmem"
25 backendKubernetes "github.com/opentofu/opentofu/internal/backend/remote-state/kubernetes"

internal/backend/remote-state/consul/client.go1

269:2import-shadowingidentifier md5 shadows an imported package

internal/backend/remote-state/consul/client.go:269:2

268
269 md5 := md5.Sum(data)
270 chunks := split(payload, 524288)

internal/configs/config.go1

573:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/configs/config.go:573:3

572 // add to this in the loop below.
573 reqs[fqn] = nil
574 }

internal/legacy/tofu/diff_test.go1

1201:9inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/legacy/tofu/diff_test.go:1201:9

1200 for i, tc := range cases {
1201 t.Run(fmt.Sprintf("%d", i), func(t *testing.T) {
1202 same, reason := tc.One.Same(tc.Two)

internal/backend/remote-state/http/backend_test.go1

133:21insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:133:21

132 "update_method": "BLAH",
133 "lock_address": "http://127.0.0.1:8888/bar",
134 "lock_method": "BLIP",

internal/legacy/tofu/resource_provider.go1

13:23interface-method-limitinterface has 15 methods, exceeding the configured design limit of 10

internal/legacy/tofu/resource_provider.go:13:23

12// named "providers".
13type ResourceProvider interface {
14 /*********************************************************************

internal/cloud/backend_common.go1

134:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:134:7

133 // If the run is in a final state, ignore it and continue.
134 switch item.Status {
135 case tfe.RunApplied, tfe.RunCanceled, tfe.RunDiscarded, tfe.RunErrored:

internal/cloud/tfe_client_mock.go1

1520:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1520:6

1519
1520type MockStateVersionOutputs struct {
1521 client *MockClient

internal/backend/backend.go1

364:3modifies-parameterassignment modifies parameter op

internal/backend/backend.go:364:3

363 if diags.HasErrors() {
364 op.Result = OperationFailure
365 } else {

internal/dag/marshal.go1

119:38modifies-value-receiverassignment modifies value receiver e

internal/dag/marshal.go:119:38

118func (e edges) Len() int { return len(e) }
119func (e edges) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
120

cmd/tofu/provider_source.go1

158:28nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/provider_source.go:158:28

157 for found := range available {
158 foundLocally[found] = struct{}{}
159 }

internal/cloud/backend.go1

519:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/cloud/backend.go:519:3

518 log.Printf("[WARN] Failed to get credentials for %s: %s (ignoring)", b.hostname, err)
519 return "", nil
520 }

internal/backend/remote-state/http/client.go1

223:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/http/client.go:223:3

222 if len(payload.Data) == 0 {
223 return nil, nil
224 }

internal/backend/remote-state/pg/backend_test.go1

284:6no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/pg/backend_test.go:284:6

283 return
284 } else if len(confDiags) != 0 {
285 confDiags = confDiags.InConfigBody(config, "")

internal/experiments/experiment.go1

28:6no-initreplace init with explicit initialization

internal/experiments/experiment.go:28:6

27
28func init() {
29 // Each experiment constant defined above must be registered here as either

internal/backend/remote-state/cos/client.go1

219:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:219:3

218 err = fmt.Errorf("failed to open file at %v: %w", cosFile, err)
219 return
220 }

cmd/tofu/version.go1

17:5no-package-varpackage variables introduce mutable global state

cmd/tofu/version.go:17:5

16
17var Version = version.Version
18

cmd/tofu/signal_windows.go1

8:9package-commentspackage should have a documentation comment

cmd/tofu/signal_windows.go:8:9

7
8package main
9

internal/encryption/keyprovider/aws_kms/provider.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/provider.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/provider.go:6:9

5
6package aws_kms
7

internal/backend/remote-state/gcs/backend_test.go1

81:8range-value-addresstaking the address of range value c can be misleading

internal/backend/remote-state/gcs/backend_test.go:81:8

80 for _, c := range cases {
81 b := &Backend{
82 prefix: c.prefix,

internal/legacy/tofu/state.go1

1006:7receiver-namingreceiver name m is inconsistent with s

internal/legacy/tofu/state.go:1006:7

1005// Equal tests whether one module state is equal to another.
1006func (m *ModuleState) Equal(other *ModuleState) bool {
1007 m.Lock()

internal/backend/remote-state/s3/validate.go1

253:40redefines-builtin-ididentifier max shadows a predeclared identifier

internal/backend/remote-state/s3/validate.go:253:40

252
253func validateDuration(val string, min, max time.Duration, path cty.Path, diags *tfdiags.Diagnostics) {
254 d, err := time.ParseDuration(val)

internal/addrs/instance_key_test.go1

60:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:60:4

59 // Dollar signs that aren't followed by { are not interpolation sequences
60 StringKey(`$hello`),
61 `["$hello"]`,

internal/legacy/helper/schema/schema.go1

1580:9simplify-rangeomit the blank range value

internal/legacy/helper/schema/schema.go:1580:9

1579 raws := make([]interface{}, rawV.Len())
1580 for i, _ := range raws {
1581 raws[i] = rawV.Index(i).Interface()

internal/configs/configschema/path.go1

18:3single-case-switchswitch with one case can be replaced by an if statement

internal/configs/configschema/path.go:18:3

17 for i, step := range path {
18 switch step := step.(type) {
19 case cty.GetAttrStep:

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

186:7slice-preallocationpreallocate r with capacity len(range source) before appending once per iteration

internal/builtin/provisioners/remote-exec/resource_provisioner.go:186:7

185
186 var r []io.ReadCloser
187 for _, script := range scripts {

internal/cloud/tfe_client_mock.go1

709:2task-commentTODO comment should be resolved or linked to an owned work item

internal/cloud/tfe_client_mock.go:709:2

708func (m *MockTaskStages) List(ctx context.Context, runID string, options *tfe.TaskStageListOptions) (*tfe.TaskStageList, error) {
709 //TODO implement me
710 panic("implement me")

internal/addrs/module.go1

34:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/module.go:34:1

33// represented by RootModuleInstance.
34var RootModule Module
35

internal/addrs/move_endpoint_module.go1

696:38unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/move_endpoint_module.go:696:38

695 // by the "to" relative address in toMatch.
696 toRelSubject := toMatch.relSubject.(AbsResourceInstance)
697 var mNew ModuleInstance

internal/e2e/e2e.go1

41:61unexported-returnexported function returns an unexported type

internal/e2e/e2e.go:41:61

40// function always succeeds.
41func NewBinary(t *testing.T, binaryPath, workingDir string) *binary {
42 tmpDir, err := filepath.EvalSymlinks(t.TempDir())

internal/backend/local/backend_local_test.go1

314:52unused-parameterparameter fn is unused

internal/backend/local/backend_local_test.go:314:52

313
314func (s *stateStorageThatFailsRefresh) MutateState(fn func(*states.State) *states.State) error {
315 return fmt.Errorf("unimplemented")

internal/addrs/check_rule.go1

75:7unused-receiverreceiver k is unused

internal/addrs/check_rule.go:75:7

74
75func (k checkRuleKey) uniqueKeySigil() {}
76

internal/backend/remote-state/consul/client_test.go1

69:113use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:69:113

68 // Get the backend
69 b := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
70 "address": srv.HTTPAddr,

internal/backend/local/backend_local_test.go1

323:9use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_local_test.go:323:9

322func (s *stateStorageThatFailsRefresh) PersistState(_ context.Context, schemas *tofu.Schemas) error {
323 return fmt.Errorf("unimplemented")
324}

internal/command/jsonplan/plan_test.go1

344:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonplan/plan_test.go:344:3

343 // Sort the slices based on the number of elements in each path
344 sort.Slice(pathsA, func(i, j int) bool {
345 return len(pathsA[i]) < len(pathsA[j])

internal/backend/remote-state/azure/client_test.go1

221:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/azure/client_test.go:221:2

220 client_id := os.Getenv("TF_AZURE_TEST_CLIENT_ID")
221 client_secret := os.Getenv("TF_AZURE_TEST_CLIENT_SECRET")
222 if client_id == "" || client_secret == "" {

internal/backend/remote-state/http/client.go1

237:11weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/http/client.go:237:11

236 // Generate the MD5
237 hash := md5.Sum(payload.Data)
238 payload.MD5 = hash[:]

internal/addrs/check_rule_diagnostic_test.go1

40:13add-constantstring literal "extra" appears more than twice; define a constant

internal/addrs/check_rule_diagnostic_test.go:40:13

39 Detail: "this is an error",
40 Extra: "extra",
41 })

internal/tofu/context_apply_test.go1

3236:5boolean-literal-comparisonomit the boolean literal from the logical expression

internal/tofu/context_apply_test.go:3236:5

3235 defer callLock.Unlock()
3236 if called != true {
3237 t.Fatalf("err: configure never called")

internal/addrs/module_instance.go1

100:6cognitive-complexityfunction has cognitive complexity 21; maximum is 7

internal/addrs/module_instance.go:100:6

99// This function supports module addresses with and without instance keys.
100func parseModuleInstancePrefix(traversal hcl.Traversal) (ModuleInstance, hcl.Traversal, tfdiags.Diagnostics) {
101 remain := traversal

internal/command/cliconfig/cliconfig.go1

287:6confusing-namingname envConfig differs from EnvConfig only by capitalization

internal/command/cliconfig/cliconfig.go:287:6

286
287func envConfig(env map[string]string) *Config {
288 config := &Config{}

internal/initwd/module_install.go1

1103:56confusing-resultsadjacent unnamed results of the same type should be named

internal/initwd/module_install.go:1103:56

1102
1103func splitAddrSubdir(addr addrs.ModuleSource) (string, string) {
1104 switch addr := addr.(type) {

internal/command/views/json/hook.go1

77:6constructor-interface-returnNewApplyProgress returns interface Hook although its concrete result is consistently *applyProgress; return the concrete type

internal/command/views/json/hook.go:77:6

76
77func NewApplyProgress(addr addrs.AbsResourceInstance, action plans.Action, elapsed time.Duration) Hook {
78 return &applyProgress{

internal/backend/remote/backend_context.go1

31:56context-as-argumentcontext.Context should be the first parameter

internal/backend/remote/backend_context.go:31:56

30// Refer to the comments of backend.Local for more details about ctx vs stopCtx.
31func (b *Remote) LocalRun(ctx context.Context, stopCtx context.Context, op *backend.Operation) (*backend.LocalRun, statemgr.Full, tfdiags.Diagnostics) {
32 var diags tfdiags.Diagnostics

internal/command/webbrowser/mock.go1

67:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/command/webbrowser/mock.go:67:2

66 // would naturally complete.
67 Context context.Context
68

internal/addrs/move_endpoint_module.go1

567:22cyclomatic-complexityfunction complexity is 12; maximum is 10

internal/addrs/move_endpoint_module.go:567:22

566// must have matching object types. If not, MoveDestination will panic.
567func (r AbsResource) MoveDestination(fromMatch, toMatch *MoveEndpointInModule) (AbsResource, bool) {
568 switch fromMatch.ObjectKind() {

internal/cloud/e2e/main_test.go1

229:3deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:229:3

228 fmt.Printf("Could not run exec command: %v\n", err)
229 os.Exit(1)
230 }

internal/legacy/helper/acctest/random.go1

28:2deprecated-api-usagemath/rand.Seed is deprecated: As of Go 1.20 there is no reason to call Seed with a random value. Programs that call Seed with a known value to get a specific sequence of results should use New(NewSource(seed)) to obtain a local random generator.

internal/legacy/helper/acctest/random.go:28:2

27func init() {
28 rand.Seed(time.Now().UTC().UnixNano())
29}

internal/backend/local/testing.go1

225:17discarded-error-resulterror result returned by b.StateMgr is discarded

internal/backend/local/testing.go:225:17

224 t.Helper()
225 stateMgr, _ := b.StateMgr(t.Context(), backend.DefaultStateName)
226 lockId, err := stateMgr.Lock(t.Context(), statemgr.NewLockInfo())

internal/addrs/remove_endpoint.go1

22:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/remove_endpoint.go:22:1

21// To obtain a full address from a RemoveEndpoint we need to combine it
22// with any ancestor modules in the configuration
23type RemoveEndpoint struct {

internal/backend/remote/backend.go1

234:2early-returninvert the condition and return early to reduce nesting

internal/backend/remote/backend.go:234:2

233 // Get the hostname.
234 if val := obj.GetAttr("hostname"); !val.IsNull() && val.AsString() != "" {
235 b.hostname = val.AsString()

internal/addrs/module_source_test.go1

411:13error-stringserror string should not be capitalized or end with punctuation

internal/addrs/module_source_test.go:411:13

410 if remote.Subdir != "foo" {
411 t.Errorf("FromRegistry modified the receiver; should be pure function")
412 }

internal/encryption/method/errors.go1

74:6error-type-namingerror implementation type should have an Error suffix

internal/encryption/method/errors.go:74:6

73// ErrInvalidConfiguration indicates that the method configuration is incorrect.
74type ErrInvalidConfiguration struct {
75 Cause error

internal/addrs/check.go1

68:22exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:68:22

67
68func (c ConfigCheck) CheckableKind() CheckableKind {
69 return CheckableCheck

internal/addrs/resource_test.go1

1:1file-length-limitfile has 684 lines; maximum is 500

internal/addrs/resource_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/state.go1

510:24flag-parameterboolean parameter force controls function flow

internal/cloud/state.go:510:24

509// Delete the remote state.
510func (s *State) Delete(force bool) error {
511

cmd/tofu/webbrowser_nonunix.go1

1:1formatfile is not formatted

cmd/tofu/webbrowser_nonunix.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt cmd/tofu/webbrowser_nonunix.go`

internal/addrs/module_source_test.go1

491:6function-lengthfunction has 3 statements and 170 lines; maximum is 50 statements or 75 lines

internal/addrs/module_source_test.go:491:6

490
491func TestParseModuleSourceRegistry(t *testing.T) {
492 // We test parseModuleSourceRegistry alone here, in addition to testing

internal/configs/named_values.go1

287:6function-result-limitfunction returns 4 values; maximum is 3

internal/configs/named_values.go:287:6

286
287func decodeVariableType(expr hcl.Expression) (cty.Type, *typeexpr.Defaults, VariableParsingMode, hcl.Diagnostics) {
288 if exprIsNativeQuotedString(expr) {

internal/addrs/move_endpoint_module.go1

203:2identical-switch-branchesswitch repeats a case body

internal/addrs/move_endpoint_module.go:203:2

202 steps = []ModuleInstanceStep(relSubject.Module)
203 case AbsResourceInstance:
204 steps = []ModuleInstanceStep(relSubject.Module)

internal/backend/init/init.go1

25:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:25:2

24 backendInmem "github.com/opentofu/opentofu/internal/backend/remote-state/inmem"
25 backendKubernetes "github.com/opentofu/opentofu/internal/backend/remote-state/kubernetes"
26 backendOSS "github.com/opentofu/opentofu/internal/backend/remote-state/oss"

internal/backend/remote-state/consul/client_test.go1

149:3import-shadowingidentifier remote shadows an imported package

internal/backend/remote-state/consul/client_test.go:149:3

148
149 remote, err := c.Get(t.Context())
150 if err != nil {

internal/encryption/keyprovider.go1

32:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/encryption/keyprovider.go:32:3

31 if _, ok := v[first]; !ok {
32 v[first] = make(map[string]cty.Value)
33 }

internal/registry/client_test.go1

561:37inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/registry/client_test.go:561:37

560 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
561 w.Header().Set("Content-Length", fmt.Sprintf("%d", len(zipContent)))
562 w.WriteHeader(http.StatusOK)

internal/backend/remote-state/http/backend_test.go1

135:21insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/backend_test.go:135:21

134 "lock_method": "BLIP",
135 "unlock_address": "http://127.0.0.1:8888/baz",
136 "unlock_method": "BLOOP",

internal/providers/provider.go1

87:17interface-method-limitinterface has 21 methods, exceeding the configured design limit of 10

internal/providers/provider.go:87:17

86// having been called.
87type Configured interface {
88 // A configured provider can do anything a unconfigured provider can.

internal/cloud/backend_common.go1

138:8max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:138:8

137 case tfe.RunPlanned:
138 if op.Type == backend.OperationTypePlan {
139 continue

internal/cloud/tfe_client_mock.go1

1563:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1563:6

1562
1563type MockVariables struct {
1564 client *MockClient

internal/backend/backend.go1

366:3modifies-parameterassignment modifies parameter op

internal/backend/backend.go:366:3

365 } else {
366 op.Result = OperationSuccess
367 }

internal/dag/marshal.go1

119:44modifies-value-receiverassignment modifies value receiver e

internal/dag/marshal.go:119:44

118func (e edges) Len() int { return len(e) }
119func (e edges) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
120

cmd/tofu/provider_source_test.go1

27:13nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/provider_source_test.go:27:13

26func TestProviderSource(t *testing.T) {
27 tests := []struct {
28 name string

internal/cloud/state.go1

428:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/cloud/state.go:428:4

427 // If no state exists, then return nil.
428 return nil, nil
429 }

internal/backend/remote-state/inmem/client.go1

25:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/inmem/client.go:25:3

24 if c.Data == nil {
25 return nil, nil
26 }

internal/backend/remote-state/s3/backend.go1

1005:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/s3/backend.go:1005:4

1004 return "", false
1005 } else {
1006 return val.AsString(), true

internal/legacy/helper/acctest/random.go1

27:6no-initreplace init with explicit initialization

internal/legacy/helper/acctest/random.go:27:6

26
27func init() {
28 rand.Seed(time.Now().UTC().UnixNano())

internal/backend/remote-state/cos/client.go1

226:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:226:3

225 err = fmt.Errorf("failed to open file at %v: checksum mismatch, %s != %s", cosFile, check, checksum)
226 return
227 }

cmd/tofu/version.go1

19:5no-package-varpackage variables introduce mutable global state

cmd/tofu/version.go:19:5

18
19var VersionPrerelease = version.Prerelease
20

cmd/tofu/testing.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/testing.go:6:9

5
6package main
7

internal/encryption/keyprovider/aws_kms/provider_test.go2

6:9package-directory-mismatchpackage aws_kms does not match directory aws_kms

internal/encryption/keyprovider/aws_kms/provider_test.go:6:9

5
6package aws_kms
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/aws_kms/provider_test.go:6:9

5
6package aws_kms
7

internal/backend/remote-state/http/client_test.go1

366:14range-value-addresstaking the address of range value tt can be misleading

internal/backend/remote-state/http/client_test.go:366:14

365
366 client := &httpClient{
367 UnlockURL: unlockURL,

internal/legacy/tofu/state.go1

1057:7receiver-namingreceiver name m is inconsistent with s

internal/legacy/tofu/state.go:1057:7

1056// IsRoot says whether or not this module diff is for the root module.
1057func (m *ModuleState) IsRoot() bool {
1058 m.Lock()

internal/backend/remote/backend_common.go1

44:14redefines-builtin-ididentifier min shadows a predeclared identifier

internal/backend/remote/backend_common.go:44:14

43// limited by the provided min and max (in milliseconds) durations.
44func backoff(min, max float64, iter int) time.Duration {
45 backoff := math.Pow(2, float64(iter)/5) * min

internal/addrs/instance_key_test.go1

65:4redundant-conversionconversion from StringKey to the identical type is redundant

internal/addrs/instance_key_test.go:65:4

64 // Percent signs that aren't followed by { are not control sequences
65 StringKey(`%hello`),
66 `["%hello"]`,

internal/legacy/helper/schema/schema.go1

1704:13simplify-rangeomit the blank range value

internal/legacy/helper/schema/schema.go:1704:13

1703 if m, ok := raw.(map[string]interface{}); ok {
1704 for subk, _ := range m {
1705 if _, ok := schema[subk]; !ok {

internal/configs/configschema/path.go1

47:3single-case-switchswitch with one case can be replaced by an if statement

internal/configs/configschema/path.go:47:3

46 for i, step := range path {
47 switch step := step.(type) {
48 case cty.GetAttrStep:

internal/builtin/provisioners/remote-exec/resource_provisioner.go1

218:6slice-preallocationpreallocate fhs with capacity len(range source) before appending once per iteration

internal/builtin/provisioners/remote-exec/resource_provisioner.go:218:6

217 // Open all the scripts
218 var fhs []io.ReadCloser
219 for _, s := range scripts {

internal/command/apply.go1

89:2task-commentFIXME comment should be resolved or linked to an owned work item

internal/command/apply.go:89:2

88
89 // FIXME: the -input flag value is needed to initialize the backend and the
90 // operation, but there is no clear path to pass this value down, so we

internal/addrs/module_call.go1

55:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/module_call.go:55:1

54// module block declares.
55type AbsModuleCall struct {
56 Module ModuleInstance

internal/addrs/parse_ref.go1

399:33unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/parse_ref.go:399:33

398 // depending on what we find after this introducer.
399 callInstance := callRef.Subject.(ModuleCallInstance) //nolint:errcheck // This was constructed directly above by call to parseSingleAttrRef
400 callRange := callRef.SourceRange

internal/engine/planning/execgraph_managed.go1

34:3unexported-returnexported function returns an unexported type

internal/engine/planning/execgraph_managed.go:34:3

33 effectiveReplaceOrder resourceInstanceReplaceOrder,
34) resourceInstanceObjectSubgraph {
35 // Before we go any further we'll just make sure what we've been given

internal/backend/local/backend_local_test.go1

322:72unused-parameterparameter schemas is unused

internal/backend/local/backend_local_test.go:322:72

321
322func (s *stateStorageThatFailsRefresh) PersistState(_ context.Context, schemas *tofu.Schemas) error {
323 return fmt.Errorf("unimplemented")

internal/addrs/count_attr.go1

23:7unused-receiverreceiver ca is unused

internal/addrs/count_attr.go:23:7

22
23func (ca CountAttr) uniqueKeySigil() {}
24

internal/backend/remote-state/consul/client_test.go1

84:112use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:84:112

83 // create a new backend with gzip
84 b = backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
85 "address": srv.HTTPAddr,

internal/backend/local/backend_plan.go1

153:25use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/backend_plan.go:153:25

152 // to set PlanOutPath without also setting PlanOutBackend.
153 diags = diags.Append(fmt.Errorf(
154 "PlanOutPath set without also setting PlanOutBackend (this is a bug in OpenTofu)"),

internal/command/jsonplan/plan_test.go1

347:3use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonplan/plan_test.go:347:3

346 })
347 sort.Slice(pathsB, func(i, j int) bool {
348 return len(pathsB[i]) < len(pathsB[j])

internal/backend/remote-state/cos/backend.go1

30:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/cos/backend.go:30:2

29const (
30 PROVIDER_SECRET_ID = "TENCENTCLOUD_SECRET_ID"
31 PROVIDER_SECRET_KEY = "TENCENTCLOUD_SECRET_KEY"

internal/backend/remote-state/inmem/client.go1

35:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/inmem/client.go:35:9

34func (c *RemoteClient) Put(_ context.Context, data []byte) error {
35 md5 := md5.Sum(data)
36

internal/addrs/check_rule_diagnostic_test.go1

57:13add-constantstring literal "original error" appears more than twice; define a constant

internal/addrs/check_rule_diagnostic_test.go:57:13

56 Severity: hcl.DiagError,
57 Summary: "original error",
58 Detail: "this is an error",

internal/tofu/context_eval_test.go1

73:5boolean-literal-comparisonomit the boolean literal from the logical expression

internal/tofu/context_eval_test.go:73:5

72 // should be allowed by the scope.
73 if scope.PureOnly == true {
74 t.Fatal("wrong result: eval should allow impure funcs")

internal/addrs/module_instance.go1

430:25cognitive-complexityfunction has cognitive complexity 28; maximum is 7

internal/addrs/module_instance.go:430:25

429// is contained within the receiver.
430func (m ModuleInstance) TargetContains(other Targetable) bool {
431 switch to := other.(type) {

internal/command/cliconfig/credentials.go1

89:18confusing-namingname credentialsSource differs from CredentialsSource only by capitalization

internal/command/cliconfig/credentials.go:89:18

88// a temporary file location when testing.
89func (c *Config) credentialsSource(helperType string, helper svcauth.CredentialsStore, credentialsFilePath string) *CredentialsSource {
90 configured := map[svchost.Hostname]cty.Value{}

internal/legacy/helper/acctest/random.go1

69:46confusing-resultsadjacent unnamed results of the same type should be named

internal/legacy/helper/acctest/random.go:69:46

68// returned in OpenSSH format, and the private key is PEM encoded.
69func RandSSHKeyPair(comment string) (string, string, error) {
70 privateKey, privateKeyPEM, err := genPrivateKey()

internal/command/views/json/hook.go1

112:6constructor-interface-returnNewApplyComplete returns interface Hook although its concrete result is consistently *applyComplete; return the concrete type

internal/command/views/json/hook.go:112:6

111
112func NewApplyComplete(addr addrs.AbsResourceInstance, action plans.Action, idKey, idValue string, elapsed time.Duration) Hook {
113 return &applyComplete{

internal/cloud/backend_context.go1

31:55context-as-argumentcontext.Context should be the first parameter

internal/cloud/backend_context.go:31:55

30// Refer to the comments of backend.Local for more details about ctx vs stopCtx.
31func (b *Cloud) LocalRun(ctx context.Context, stopCtx context.Context, op *backend.Operation) (*backend.LocalRun, statemgr.Full, tfdiags.Diagnostics) {
32 var diags tfdiags.Diagnostics

internal/encryption/keyprovider/aws_kms/provider.go1

34:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/encryption/keyprovider/aws_kms/provider.go:34:2

33 svc kmsClient
34 ctx context.Context
35}

internal/addrs/move_endpoint_module.go1

640:30cyclomatic-complexityfunction complexity is 16; maximum is 10

internal/addrs/move_endpoint_module.go:640:30

639// must have matching object types. If not, MoveDestination will panic.
640func (r AbsResourceInstance) MoveDestination(fromMatch, toMatch *MoveEndpointInModule) (AbsResourceInstance, bool) {
641 switch fromMatch.ObjectKind() {

internal/cloud/e2e/main_test.go1

248:3deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:248:3

247 fmt.Printf("Could not create file: %v\n", err)
248 os.Exit(1)
249 }

internal/legacy/tofu/state.go1

828:15deprecated-api-usagegithub.com/hashicorp/errwrap.Wrapf is deprecated: Use fmt.Errorf()

internal/legacy/tofu/state.go:828:15

827 if err != nil {
828 return nil, errwrap.Wrapf("failed to decode backend config: {{err}}", err)
829 }

internal/backend/local/testing.go1

234:6discarded-error-resulterror result returned by stateMgr.Unlock is discarded

internal/backend/local/testing.go:234:6

233 // in a clean state
234 _ = stateMgr.Unlock(t.Context(), lockId)
235 return true

internal/addrs/resource.go1

95:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/resource.go:95:1

94// ImpliedProvider returns the implied provider type name, for e.g. the "aws" in
95// "aws_instance"
96func (r Resource) ImpliedProvider() string {

internal/backend/unparsed_value.go1

118:3early-returninvert the condition and return early to reduce nesting

internal/backend/unparsed_value.go:118:3

117
118 if declared {
119 mode = config.ParsingMode

internal/addrs/module_source_test.go1

414:13error-stringserror string should not be capitalized or end with punctuation

internal/addrs/module_source_test.go:414:13

413 if registry.Subdir != "" {
414 t.Errorf("FromRegistry modified the given address; should be pure function")
415 }

internal/getmodules/file_detector.go1

64:6error-type-namingerror implementation type should have an Error suffix

internal/getmodules/file_detector.go:64:6

63// to use one of the other schemes and thus not a filesystem path at all.
64type MaybeRelativePathErr struct {
65 Addr string

internal/addrs/check.go1

85:6exported-declaration-commentexported type should have a comment beginning with its name

internal/addrs/check.go:85:6

84// evaluated on the containing module.
85type AbsCheck struct {
86 Module ModuleInstance

internal/backend/local/backend.go1

1:1file-length-limitfile has 511 lines; maximum is 500

internal/backend/local/backend.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/cloud/testing.go1

409:51flag-parameterboolean parameter enabled controls function flow

internal/cloud/testing.go:409:51

408
409func testServerWithSnapshotsEnabled(t *testing.T, enabled bool) *httptest.Server {
410 skipIfTFENotEnabled(t)

internal/addrs/check_rule.go1

1:1formatfile is not formatted

internal/addrs/check_rule.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt internal/addrs/check_rule.go`

internal/addrs/move_endpoint_module.go1

477:25function-lengthfunction has 32 statements and 78 lines; maximum is 50 statements or 75 lines

internal/addrs/move_endpoint_module.go:477:25

476// must have matching object types. If not, MoveDestination will panic.
477func (m ModuleInstance) MoveDestination(fromMatch, toMatch *MoveEndpointInModule) (ModuleInstance, bool) {
478 // NOTE: This implementation assumes the invariant that fromMatch and

internal/configs/parser_config_dir.go1

134:17function-result-limitfunction returns 4 values; maximum is 3

internal/configs/parser_config_dir.go:134:17

133// paths to any test files within the module.
134func (p Parser) ConfigDirFilesWithTests(dir string, testDirectory string) (primary, override, tests []string, diags hcl.Diagnostics) {
135 return p.dirFiles(dir, testDirectory)

internal/addrs/move_endpoint_module.go1

205:2identical-switch-branchesswitch repeats a case body

internal/addrs/move_endpoint_module.go:205:2

204 steps = []ModuleInstanceStep(relSubject.Module)
205 case AbsResource:
206 steps = []ModuleInstanceStep(relSubject.Module)

internal/backend/init/init.go1

26:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:26:2

25 backendKubernetes "github.com/opentofu/opentofu/internal/backend/remote-state/kubernetes"
26 backendOSS "github.com/opentofu/opentofu/internal/backend/remote-state/oss"
27 backendPg "github.com/opentofu/opentofu/internal/backend/remote-state/pg"

internal/backend/remote-state/cos/backend.go1

42:2import-shadowingidentifier encryption shadows an imported package

internal/backend/remote-state/cos/backend.go:42:2

41 *schema.Backend
42 encryption encryption.StateEncryption
43 credential *common.Credential

internal/getproviders/package_authentication.go1

271:6inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/getproviders/package_authentication.go:271:6

270 if _, ok := hashes[hash]; !ok {
271 hashes[hash] = &HashDisposition{
272 ReportedByTrustedMirror: true,

internal/registry/client_test.go1

603:37inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/registry/client_test.go:603:37

602 // Claim more bytes than we actually send
603 w.Header().Set("Content-Length", fmt.Sprintf("%d", len(zipContent)+100))
604 w.WriteHeader(http.StatusOK)

internal/backend/remote-state/http/client_test.go1

234:16insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/http/client_test.go:234:16

233 name: "Locking enabled when UnlockURL is set",
234 unlockURL: "http://http-endpoint.com:3333",
235 wantResult: true,

internal/providers/provider.go1

160:16interface-method-limitinterface has 21 methods, exceeding the configured design limit of 10

internal/providers/provider.go:160:16

159// component parts (Unconfigured, Configured) for added safety and clarity.
160type Interface interface {
161 Configured

internal/cloud/backend_common.go1

147:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:147:7

146 // Stop searching when we reached the current run.
147 if w.CurrentRun != nil && w.CurrentRun.ID == item.ID {
148 break runlist

internal/cloud/tfe_client_mock.go1

1627:6max-public-structsfile declares more than 5 exported structs

internal/cloud/tfe_client_mock.go:1627:6

1626
1627type MockWorkspaces struct {
1628 client *MockClient

internal/backend/init/init.go1

118:3modifies-parameterassignment modifies parameter name

internal/backend/init/init.go:118:3

117 if alias, ok := backendAliases[name]; ok {
118 name = alias
119 }

internal/dag/set.go1

29:2modifies-value-receiverassignment modifies value receiver s

internal/dag/set.go:29:2

28func (s Set) Add(v interface{}) {
29 s[hashcode(v)] = v
30}

cmd/tofu/provider_source_test.go1

190:22nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/provider_source_test.go:190:22

189 })
190 cases := map[string]struct {
191 methodType cliconfig.ProviderInstallationLocation

internal/command/cliconfig/oci_credentials.go1

109:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/command/cliconfig/oci_credentials.go:109:3

108 log.Printf("[WARN] Problems during OCI registry ambient credentials discovery:\n%s", err.Error())
109 return nil, nil
110 }

internal/backend/remote-state/kubernetes/backend.go1

378:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/kubernetes/backend.go:378:4

377 log.Printf("[INFO] Unable to load config file as it doesn't exist at %q", pathErr.Path)
378 return nil, nil
379 }

internal/backend/remote-state/s3/backend.go1

1021:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/s3/backend.go:1021:4

1020 return def
1021 } else {
1022 return v

internal/logging/logging.go1

50:6no-initreplace init with explicit initialization

internal/logging/logging.go:50:6

49
50func init() {
51 logger = newHCLogger("")

internal/backend/remote-state/cos/client.go1

229:2no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:229:2

228
229 return
230}

internal/addrs/instance_key.go1

56:5no-package-varpackage variables introduce mutable global state

internal/addrs/instance_key.go:56:5

55// of a configuration object that does not use "count" or "for_each" at all.
56var NoKey InstanceKey
57

cmd/tofu/version.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/version.go:6:9

5
6package main
7

internal/encryption/keyprovider/azure_vault/compliance_test.go2

6:9package-directory-mismatchpackage azure_vault does not match directory azure_vault

internal/encryption/keyprovider/azure_vault/compliance_test.go:6:9

5
6package azure_vault
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/azure_vault/compliance_test.go:6:9

5
6package azure_vault
7

internal/backend/remote-state/http/helper_test.go1

51:12range-value-addresstaking the address of range value tt can be misleading

internal/backend/remote-state/http/helper_test.go:51:12

50 t.Run(tt.name, func(t *testing.T) {
51 resp := &http.Response{
52 Body: io.NopCloser(bytes.NewBufferString(tt.responseBody)),

internal/legacy/tofu/state.go1

1064:7receiver-namingreceiver name m is inconsistent with s

internal/legacy/tofu/state.go:1064:7

1063// IsDescendent returns true if other is a descendent of this module.
1064func (m *ModuleState) IsDescendent(other *ModuleState) bool {
1065 m.Lock()

internal/backend/remote/backend_common.go1

44:19redefines-builtin-ididentifier max shadows a predeclared identifier

internal/backend/remote/backend_common.go:44:19

43// limited by the provided min and max (in milliseconds) durations.
44func backoff(min, max float64, iter int) time.Duration {
45 backoff := math.Pow(2, float64(iter)/5) * min

internal/addrs/module_source.go1

42:22redundant-conversionconversion from ModuleSourceLocal to the identical type is redundant

internal/addrs/module_source.go:42:22

41
42var _ ModuleSource = ModuleSourceLocal("")
43var _ ModuleSource = ModuleSourceRegistry{}

internal/legacy/tofu/diff.go1

321:12simplify-rangeomit the blank range value

internal/legacy/tofu/diff.go:321:12

320 names := make([]string, 0, len(d.Resources))
321 for name, _ := range d.Resources {
322 names = append(names, name)

internal/lang/funcs/datetime.go1

153:3single-case-switchswitch with one case can be replaced by an if statement

internal/lang/funcs/datetime.go:153:3

152 if err != nil {
153 switch err := err.(type) {
154 case *time.ParseError:

internal/cloud/backend.go1

1212:6slice-preallocationpreallocate tags with capacity len(range source) before appending once per iteration

internal/cloud/backend.go:1212:6

1211func (wm WorkspaceMapping) tfeTags() []*tfe.Tag {
1212 var tags []*tfe.Tag
1213

internal/command/apply.go1

94:2task-commentFIXME comment should be resolved or linked to an owned work item

internal/command/apply.go:94:2

93
94 // FIXME: the -parallelism flag is used to control the concurrency of
95 // OpenTofu operations. At the moment, this value is used both to

internal/addrs/module_instance.go1

30:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/module_instance.go:30:1

29
30var (
31 _ Targetable = ModuleInstance(nil)

internal/addrs/sync_map.go1

64:13unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/sync_map.go:64:13

63 }
64 return elem.(MapElem[K, V]).Value
65}

internal/engine/planning/plan_context.go1

86:51unexported-returnexported function returns an unexported type

internal/engine/planning/plan_context.go:86:51

85// not be used anymore.
86func (p *planContext) Close(ctx context.Context) (*planContextResult, tfdiags.Diagnostics) {
87 var diags tfdiags.Diagnostics

internal/backend/local/backend_test.go1

24:21unused-parameterparameter t is unused

internal/backend/local/backend_test.go:24:21

23
24func TestLocal_impl(t *testing.T) {
25 var _ backend.Enhanced = New(encryption.StateEncryptionDisabled())

internal/addrs/for_each_attr.go1

23:7unused-receiverreceiver f is unused

internal/addrs/for_each_attr.go:23:7

22
23func (f ForEachAttr) uniqueKeySigil() {}
24

internal/backend/remote-state/consul/client_test.go1

109:113use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:109:113

108
109 b := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
110 "address": srv.HTTPAddr,

internal/backend/local/hook_state_test.go1

306:10use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/hook_state_test.go:306:10

305 if schemas == nil {
306 return fmt.Errorf("no schemas")
307 }

internal/command/jsonplan/values.go1

173:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonplan/values.go:173:2

172 }
173 sort.Slice(childModules, func(i, j int) bool {
174 return childModules[i].Address < childModules[j].Address

internal/backend/remote-state/cos/backend.go1

31:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/cos/backend.go:31:2

30 PROVIDER_SECRET_ID = "TENCENTCLOUD_SECRET_ID"
31 PROVIDER_SECRET_KEY = "TENCENTCLOUD_SECRET_KEY"
32 PROVIDER_SECURITY_TOKEN = "TENCENTCLOUD_SECURITY_TOKEN"

internal/backend/remote-state/kubernetes/client.go1

77:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/kubernetes/client.go:77:9

76
77 md5 := md5.Sum(state)
78

internal/addrs/check_rule_diagnostic_test.go1

58:13add-constantstring literal "this is an error" appears more than twice; define a constant

internal/addrs/check_rule_diagnostic_test.go:58:13

57 Summary: "original error",
58 Detail: "this is an error",
59 Extra: &CheckRuleDiagnosticExtra{

version/version_test.go1

17:60boolean-literal-comparisonomit the boolean literal from the logical expression

version/version_test.go:17:60

16func TestVersion(t *testing.T) {
17 if match, _ := regexp.MatchString("[^\\d+\\.]", Version); match != false {
18 t.Fatalf("Version should contain only the main version")

internal/addrs/module_source_resolve.go1

18:6cognitive-complexityfunction has cognitive complexity 8; maximum is 7

internal/addrs/module_source_resolve.go:18:6

17// combination of two other source addresses, if possible.
18func ResolveRelativeModuleSource(a, b ModuleSource) (ModuleSource, error) {
19 bLocal, ok := b.(ModuleSourceLocal)

internal/command/cliconfig/oci_credentials.go1

39:18confusing-namingname ociCredentialsPolicy differs from OCICredentialsPolicy only by capitalization

internal/command/cliconfig/oci_credentials.go:39:18

38// the discovery environment as an argument so that we can fake it for testing purposes.
39func (c *Config) ociCredentialsPolicy(ctx context.Context, discoEnv ociauthconfig.ConfigDiscoveryEnvironment) (ociauthconfig.CredentialsConfigs, error) {
40 var cfgs []ociauthconfig.CredentialsConfig

internal/legacy/helper/acctest/random.go1

85:43confusing-resultsadjacent unnamed results of the same type should be named

internal/legacy/helper/acctest/random.go:85:43

84// private key, and returns both the cert and the private key PEM encoded.
85func RandTLSCert(orgName string) (string, string, error) {
86 template := &x509.Certificate{

internal/command/views/json/hook.go1

144:6constructor-interface-returnNewApplyErrored returns interface Hook although its concrete result is consistently *applyErrored; return the concrete type

internal/command/views/json/hook.go:144:6

143
144func NewApplyErrored(addr addrs.AbsResourceInstance, action plans.Action, elapsed time.Duration) Hook {
145 return &applyErrored{

internal/command/test.go1

925:66context-as-argumentcontext.Context should be the first parameter

internal/command/test.go:925:66

924
925func (runner *TestFileRunner) wait(ctx *tofu.Context, runningCtx context.Context, run *moduletest.Run, file *moduletest.File, created []*plans.ResourceInstanceChangeSrc) (diags tfdiags.Diagnostics, cancelled bool) {
926 var identifier string

internal/encryption/keyprovider/azure_vault/provider.go1

36:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/encryption/keyprovider/azure_vault/provider.go:36:2

35 svc keyManagementClient
36 ctx context.Context
37 keyName string

internal/addrs/parse_ref.go1

164:6cyclomatic-complexityfunction complexity is 19; maximum is 10

internal/addrs/parse_ref.go:164:6

163
164func parseRef(traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) {
165 var diags tfdiags.Diagnostics

internal/cloud/e2e/main_test.go1

253:3deep-exitprocess-exit calls should be confined to main or init

internal/cloud/e2e/main_test.go:253:3

252 fmt.Printf("Could not write credentials: %v\n", err)
253 os.Exit(1)
254 }

internal/backend/local/testing.go1

243:17discarded-error-resulterror result returned by b.StateMgr is discarded

internal/backend/local/testing.go:243:17

242 t.Helper()
243 stateMgr, _ := b.StateMgr(t.Context(), backend.DefaultStateName)
244 lockId, err := stateMgr.Lock(t.Context(), statemgr.NewLockInfo())

internal/addrs/sync_map_test.go1

15:1doc-comment-perioddocumentation comment should end with punctuation

internal/addrs/sync_map_test.go:15:1

14// Note: this is mostly identical to the Map test in
15// map_test.go
16func TestSyncMap(t *testing.T) {

internal/cloud/backend_taskStages.go1

138:4early-returninvert the condition and return early to reduce nesting

internal/cloud/backend_taskStages.go:138:4

137 cont, err := b.processStageOverrides(ctx, output, stage.ID)
138 if err != nil {
139 errs = multierror.Append(errs, err)

internal/addrs/module_source_test.go1

430:13error-stringserror string should not be capitalized or end with punctuation

internal/addrs/module_source_test.go:430:13

429 if remote.Subdir != "" {
430 t.Errorf("FromRegistry modified the receiver; should be pure function")
431 }

internal/getproviders/errors.go1

19:6error-type-namingerror implementation type should have an Error suffix

internal/getproviders/errors.go:19:6

18// in a provider address does not support the provider registry protocol.
19type ErrHostNoProviders struct {
20 Hostname svchost.Hostname

internal/addrs/check.go1

92:19exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:92:19

91
92func (c AbsCheck) UniqueKey() UniqueKey {
93 return absCheckUniqueKey(c.String())

internal/backend/local/backend_apply_test.go1

1:1file-length-limitfile has 536 lines; maximum is 500

internal/backend/local/backend_apply_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/command/arguments/taint.go1

38:17flag-parameterboolean parameter isTaint controls function flow

internal/command/arguments/taint.go:38:17

37// the best effort interpretation of the arguments.
38func ParseTaint(isTaint bool, args []string) (*Taint, func(), tfdiags.Diagnostics) {
39 var diags tfdiags.Diagnostics

internal/addrs/check_rule_diagnostic.go1

1:1formatfile is not formatted

internal/addrs/check_rule_diagnostic.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt internal/addrs/check_rule_diagnostic.go`

internal/addrs/move_endpoint_module_test.go1

18:6function-lengthfunction has 3 statements and 293 lines; maximum is 50 statements or 75 lines

internal/addrs/move_endpoint_module_test.go:18:6

17
18func TestModuleInstanceMoveDestination(t *testing.T) {
19 tests := []struct {

internal/configs/parser_config_dir.go1

175:18function-result-limitfunction returns 4 values; maximum is 3

internal/configs/parser_config_dir.go:175:18

174// main direction and as the location for additional test files.
175func (p *Parser) dirFiles(dir string, testsDir string) (primary, override, tests []string, diags hcl.Diagnostics) {
176 includeTests := len(testsDir) > 0

internal/addrs/move_endpoint_module.go1

239:2identical-switch-branchesswitch repeats a case body

internal/addrs/move_endpoint_module.go:239:2

238 inst = append(inst, sub.Module...)
239 case AbsResourceInstance:
240 inst = append(inst, sub.Module...)

internal/backend/init/init.go1

27:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:27:2

26 backendOSS "github.com/opentofu/opentofu/internal/backend/remote-state/oss"
27 backendPg "github.com/opentofu/opentofu/internal/backend/remote-state/pg"
28 backendS3 "github.com/opentofu/opentofu/internal/backend/remote-state/s3"

internal/backend/remote-state/gcs/backend.go1

33:2import-shadowingidentifier encryption shadows an imported package

internal/backend/remote-state/gcs/backend.go:33:2

32 *schema.Backend
33 encryption encryption.StateEncryption
34

internal/initwd/module_install.go1

753:3inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/initwd/module_install.go:753:3

752 span.SetAttributes(traceattrs.OpenTofuModuleSource(packageLocation.UILabel()))
753 i.registryPackageSources[moduleAddr] = packageLocation
754 }

internal/registry/client_test.go1

664:37inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/registry/client_test.go:664:37

663 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
664 w.Header().Set("Content-Length", fmt.Sprintf("%d", len(zipContent)))
665 w.WriteHeader(http.StatusOK)

internal/backend/remote-state/oss/backend.go1

429:90insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/oss/backend.go:429:90

428 b.otsEndpoint = otsEndpoint
429 parts := strings.Split(strings.TrimPrefix(strings.TrimPrefix(otsEndpoint, "https://"), "http://"), ".")
430 b.otsClient = tablestore.NewClientWithConfig(otsEndpoint, parts[0], accessKey, secretKey, securityToken, tablestore.NewDefaultTableStoreConfig())

internal/tofu/eval_context.go1

28:18interface-method-limitinterface has 25 methods, exceeding the configured design limit of 10

internal/tofu/eval_context.go:28:18

27// EvalContext is the interface that is given to eval nodes to execute.
28type EvalContext interface {
29 // Stopped returns a channel that is closed when evaluation is stopped

internal/cloud/backend_common.go1

361:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:361:7

360 if err != nil {
361 if err != io.EOF {
362 return generalError("Failed to read logs", err)

internal/command/cliconfig/provider_installation.go1

588:6max-public-structsfile declares more than 5 exported structs

internal/command/cliconfig/provider_installation.go:588:6

587// a provider_installation block.
588type ProviderInstallationMethod struct {
589 Location ProviderInstallationLocation

internal/backend/local/backend.go1

332:2modifies-parameterassignment modifies parameter op

internal/backend/local/backend.go:332:2

331
332 op.StateLocker = op.StateLocker.WithContext(stopCtx)
333

internal/dag/set.go1

51:3modifies-value-receiverassignment modifies value receiver s

internal/dag/set.go:51:3

50 if other.Len() < s.Len() {
51 s, other = other, s
52 }

cmd/tofu/provider_source_test.go1

289:13nested-structsmove nested anonymous struct types to named declarations

cmd/tofu/provider_source_test.go:289:13

288func TestConfigureProviderDownloadRetry(t *testing.T) {
289 tests := []struct {
290 name string

internal/command/views/hook_ui.go1

237:3nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/command/views/hook_ui.go:237:3

236 // Errors are collected and printed in ApplyCommand, no need to duplicate
237 return tofu.HookActionContinue, nil
238 }

internal/backend/remote-state/kubernetes/client.go1

58:4nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/kubernetes/client.go:58:4

57 if k8serrors.IsNotFound(err) {
58 return nil, nil
59 }

internal/backend/remote-state/s3/backend.go1

1059:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/s3/backend.go:1059:4

1058 return nil, false
1059 } else {
1060 return v, true

internal/plugin/discovery/version_set.go1

52:6no-initreplace init with explicit initialization

internal/plugin/discovery/version_set.go:52:6

51
52func init() {
53 AllVersions = Constraints{

internal/backend/remote-state/cos/client.go1

292:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:292:3

291 err = fmt.Errorf("bucket %s not exists", c.bucket)
292 return
293 }

internal/addrs/module.go1

34:5no-package-varpackage variables introduce mutable global state

internal/addrs/module.go:34:5

33// represented by RootModuleInstance.
34var RootModule Module
35

cmd/tofu/webbrowser.go1

6:9package-commentspackage should have a documentation comment

cmd/tofu/webbrowser.go:6:9

5
6package main
7

internal/encryption/keyprovider/azure_vault/config.go2

6:9package-directory-mismatchpackage azure_vault does not match directory azure_vault

internal/encryption/keyprovider/azure_vault/config.go:6:9

5
6package azure_vault
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/azure_vault/config.go:6:9

5
6package azure_vault
7

internal/backend/remote-state/http/helper_test.go1

120:12range-value-addresstaking the address of range value tt can be misleading

internal/backend/remote-state/http/helper_test.go:120:12

119 t.Run(tt.name, func(t *testing.T) {
120 resp := &http.Response{
121 Header: tt.headers,

internal/legacy/tofu/state.go1

1075:7receiver-namingreceiver name m is inconsistent with s

internal/legacy/tofu/state.go:1075:7

1074// represent the state of resources that are orphans.
1075func (m *ModuleState) Orphans(c *configs.Module) []addrs.ResourceInstance {
1076 m.Lock()

internal/cloud/backend_common.go1

42:14redefines-builtin-ididentifier min shadows a predeclared identifier

internal/cloud/backend_common.go:42:14

41// limited by the provided min and max (in milliseconds) durations.
42func backoff(min, max float64, iter int) time.Duration {
43 backoff := math.Pow(2, float64(iter)/5) * min

internal/addrs/module_source_test.go1

29:11redundant-conversionconversion from ModuleSourceLocal to the identical type is redundant

internal/addrs/module_source_test.go:29:11

28 input: "./child",
29 want: ModuleSourceLocal("./child"),
30 },

internal/legacy/tofu/diff.go1

353:12simplify-rangeomit the blank range value

internal/legacy/tofu/diff.go:353:12

352 keys := make([]string, 0, len(rdiffAttrs))
353 for key, _ := range rdiffAttrs {
354 if key == "id" {

internal/legacy/helper/schema/field_reader_config.go1

331:2single-case-switchswitch with one case can be replaced by an if statement

internal/legacy/helper/schema/field_reader_config.go:331:2

330
331 switch t := schema.Elem.(type) {
332 case *Resource:

internal/cloud/tfe_client_mock.go1

1757:6slice-preallocationpreallocate tags with capacity len(range source) before appending once per iteration

internal/cloud/tfe_client_mock.go:1757:6

1756
1757 var tags []*tfe.Tag
1758 for _, tag := range options.Tags {

internal/command/cliconfig/cliconfig.go1

344:2task-commentFIXME comment should be resolved or linked to an owned work item

internal/command/cliconfig/cliconfig.go:344:2

343
344 // FIXME: Right now our config parsing doesn't retain enough information
345 // to give proper source references to any errors. We should improve

internal/addrs/module_package.go1

52:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/module_package.go:52:1

51// series of steps in the module installer, with the help of the type checker.
52type ModuleRegistryPackage = regaddr.ModulePackage
53

internal/addrs/sync_map.go1

76:13unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/sync_map.go:76:13

75 }
76 return elem.(MapElem[K, V]).Value, ok
77}

internal/engine/planning/plan_resource_instance.go1

212:80unexported-returnexported function returns an unexported type

internal/engine/planning/plan_resource_instance.go:212:80

211// The caller must not mutate anything accessible through the returned pointer.
212func (rios *resourceInstanceObjects) Get(addr addrs.AbsResourceInstanceObject) *resourceInstanceObject {
213 return rios.objects.Get(addr)

internal/backend/local/backend_test.go1

198:59unused-parameterparameter name is unused

internal/backend/local/backend_test.go:198:59

197
198func (b *testDelegateBackend) StateMgr(_ context.Context, name string) (statemgr.Full, error) {
199 if b.stateErr {

internal/addrs/input_variable.go1

26:7unused-receiverreceiver v is unused

internal/addrs/input_variable.go:26:7

25
26func (v InputVariable) uniqueKeySigil() {}
27

internal/backend/remote-state/consul/client_test.go1

195:112use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:195:112

194 // Test with gzip and chunks
195 b = backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
196 "address": srv.HTTPAddr,

internal/backend/local/hook_state_test.go1

338:10use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/local/hook_state_test.go:338:10

337 if schemas == nil {
338 return fmt.Errorf("no schemas")
339 }

internal/command/jsonplan/values.go1

268:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonplan/values.go:268:2

267
268 sort.Slice(ret, func(i, j int) bool {
269 return ret[i].Address < ret[j].Address

internal/backend/remote-state/cos/backend.go1

32:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/cos/backend.go:32:2

31 PROVIDER_SECRET_KEY = "TENCENTCLOUD_SECRET_KEY"
32 PROVIDER_SECURITY_TOKEN = "TENCENTCLOUD_SECURITY_TOKEN"
33 PROVIDER_REGION = "TENCENTCLOUD_REGION"

internal/backend/remote-state/oss/client.go1

126:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/oss/client.go:126:9

125
126 sum := md5.Sum(data)
127 if err := c.putMD5(sum[:]); err != nil {

internal/addrs/checkable.go1

137:15add-constantstring literal "Invalid checkable address" appears more than twice; define a constant

internal/addrs/checkable.go:137:15

136 Severity: hcl.DiagError,
137 Summary: "Invalid checkable address",
138 Detail: fmt.Sprintf("%s address must follow the module address with the keyword '%s'.", cases.Title(language.English, cases.NoLower).String(keyword), keyword),

version/version_test.go1

21:62boolean-literal-comparisonomit the boolean literal from the logical expression

version/version_test.go:21:62

20
21 if match, _ := regexp.MatchString("[^a-z\\d]", Prerelease); match != false {
22 t.Fatalf("Prerelease should contain only letters and numbers")

internal/addrs/move_endpoint_module.go1

256:32cognitive-complexityfunction has cognitive complexity 10; maximum is 7

internal/addrs/move_endpoint_module.go:256:32

255// the given module to see if they match.
256func (e *MoveEndpointInModule) SelectsModule(addr ModuleInstance) bool {
257 synthInst := e.synthModuleInstance()

internal/command/clistate/local_state.go1

85:22confusing-namingname writeState differs from WriteState only by capitalization

internal/command/clistate/local_state.go:85:22

84}
85func (s *LocalState) writeState(state *CLIState) error {
86 if s.stateFileOut == nil {

internal/legacy/helper/schema/resource_data.go1

91:60confusing-resultsadjacent unnamed results of the same type should be named

internal/legacy/helper/schema/resource_data.go:91:60

90// fields which have a zero value of false.
91func (d *ResourceData) GetChange(key string) (interface{}, interface{}) {
92 o, n := d.getChange(key, getSourceState, getSourceDiff)

internal/command/views/json/hook.go1

170:6constructor-interface-returnNewProvisionStart returns interface Hook although its concrete result is consistently *provisionStart; return the concrete type

internal/command/views/json/hook.go:170:6

169
170func NewProvisionStart(addr addrs.AbsResourceInstance, provisioner string) Hook {
171 return &provisionStart{

internal/tracing/context_probe.go1

44:41context-as-argumentcontext.Context should be the first parameter

internal/tracing/context_probe.go:44:41

43// record the call in the probe.
44func NewContextProbe(t testing.TB, base context.Context) (context.Context, *ContextProbe) {
45 if existing := base.Value(contextProbeKey); existing != nil {

internal/encryption/keyprovider/gcp_kms/provider.go1

33:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/encryption/keyprovider/gcp_kms/provider.go:33:2

32 svc keyManagementClient
33 ctx context.Context
34 keyName string

internal/addrs/parse_ref.go1

283:6cyclomatic-complexityfunction complexity is 11; maximum is 10

internal/addrs/parse_ref.go:283:6

282
283func parseResourceRef(mode ResourceMode, startRange hcl.Range, traversal hcl.Traversal) (*Reference, tfdiags.Diagnostics) {
284 var diags tfdiags.Diagnostics

internal/cloud/remote_test.go1

29:2deep-exitprocess-exit calls should be confined to main or init

internal/cloud/remote_test.go:29:2

28
29 os.Exit(m.Run())
30}

internal/backend/local/testing.go1

251:6discarded-error-resulterror result returned by stateMgr.Unlock is discarded

internal/backend/local/testing.go:251:6

250 // leave the workdir in a clean state
251 _ = stateMgr.Unlock(t.Context(), lockId)
252 t.Error("unexpected success locking state")

internal/backend/backend.go1

127:1doc-comment-perioddocumentation comment should end with punctuation

internal/backend/backend.go:127:1

126// HostAlias describes a list of aliases that should be used when initializing an
127// Enhanced Backend
128type HostAlias struct {

internal/command/e2etest/providers_tamper_test.go1

677:2early-returninvert the condition and return early to reduce nesting

internal/command/e2etest/providers_tamper_test.go:677:2

676 }
677 if lock := locks.Provider(addrs.MustParseProviderSourceString("registry.terraform.io/hashicorp/null")); lock != nil {
678 if got, want := lock.Version(), getproviders.MustParseVersion("3.2.0"); got != want {

internal/addrs/module_source_test.go1

433:13error-stringserror string should not be capitalized or end with punctuation

internal/addrs/module_source_test.go:433:13

432 if registry.Subdir != "bar" {
433 t.Errorf("FromRegistry modified the given address; should be pure function")
434 }

internal/getproviders/errors.go1

45:6error-type-namingerror implementation type should have an Error suffix

internal/getproviders/errors.go:45:6

44// the service discovery protocol.
45type ErrHostUnreachable struct {
46 Hostname svchost.Hostname

internal/addrs/check.go1

103:19exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:103:19

102// CheckAssertion rules within a check block.
103func (c AbsCheck) CheckRule(typ CheckRuleType, i int) CheckRule {
104 return CheckRule{

internal/backend/local/backend_local.go1

1:1file-length-limitfile has 569 lines; maximum is 500

internal/backend/local/backend_local.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/command/arguments/types.go1

71:64flag-parameterboolean parameter input controls function flow

internal/command/arguments/types.go:71:64

70// Commands that only support -json (not -json-into) should pass jsonInto=false.
71func (v *ViewOptions) AddGranularFlags(cmdFlags *flag.FlagSet, input bool, jsonInto bool) {
72 if input {

internal/addrs/check_rule_diagnostic_test.go1

1:1formatfile is not formatted

internal/addrs/check_rule_diagnostic_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt internal/addrs/check_rule_diagnostic_test.go`

internal/addrs/move_endpoint_module_test.go1

312:6function-lengthfunction has 3 statements and 396 lines; maximum is 50 statements or 75 lines

internal/addrs/move_endpoint_module_test.go:312:6

311
312func TestAbsResourceInstanceMoveDestination(t *testing.T) {
313 tests := []struct {

internal/encryption/keyprovider/pbkdf2/config.go1

282:6function-result-limitfunction returns 4 values; maximum is 3

internal/encryption/keyprovider/pbkdf2/config.go:282:6

281// seen by hcl as a valid reference but as a raw string.
282func extractChainTraversal(body hcl.Body) (hcl.Traversal, hcl.Body, *hcl.Attribute, hcl.Diagnostics) {
283 var diags hcl.Diagnostics

internal/addrs/parse_ref.go1

300:2identical-switch-branchesswitch repeats a case body

internal/addrs/parse_ref.go:300:2

299 typeName = tt.Name
300 case hcl.TraverseAttr:
301 typeName = tt.Name

internal/backend/init/init.go1

28:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:28:2

27 backendPg "github.com/opentofu/opentofu/internal/backend/remote-state/pg"
28 backendS3 "github.com/opentofu/opentofu/internal/backend/remote-state/s3"
29 backendCloud "github.com/opentofu/opentofu/internal/cloud"

internal/backend/remote-state/gcs/backend_state.go1

32:2import-shadowingidentifier states shadows an imported package

internal/backend/remote-state/gcs/backend_state.go:32:2

31func (b *Backend) Workspaces(ctx context.Context) ([]string, error) {
32 states := []string{backend.DefaultStateName}
33

internal/lang/eval.go1

388:6inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/lang/eval.go:388:6

387 if !fnDiags.HasErrors() {
388 hclCtx.Functions[subj.String()] = *fn
389 }

internal/registry/client_test.go1

777:37inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/registry/client_test.go:777:37

776 receivedAuthHeader = r.Header.Get("Authorization")
777 w.Header().Set("Content-Length", fmt.Sprintf("%d", len(zipContent)))
778 w.WriteHeader(http.StatusOK)

internal/backend/remote-state/oss/backend.go1

627:23insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/oss/backend.go:627:23

626
627var securityCredURL = "http://100.100.100.200/latest/meta-data/ram/security-credentials/"
628

internal/tofu/hook.go1

37:11interface-method-limitinterface has 28 methods, exceeding the configured design limit of 10

internal/tofu/hook.go:37:11

36// nothing. Then, override only the functions you want to implement.
37type Hook interface {
38 // PreApply and PostApply are called before and after an action for a

internal/cloud/backend_common.go1

411:6max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_common.go:411:6

410 if err != errRunOverridden {
411 if _, err = b.client.PolicyChecks.Override(stopCtx, pc.ID); err != nil {
412 return generalError(fmt.Sprintf("Failed to override policy check.\n%s", runUrl), err)

internal/command/cliconfig/provider_installation.go1

650:6max-public-structsfile declares more than 5 exported structs

internal/command/cliconfig/provider_installation.go:650:6

649// Provider Mirror Protocol.
650type ProviderInstallationOCIMirror struct {
651 // RepositoryMapping is a function that translates from an OpenTofu-style

internal/backend/local/backend_apply.go1

88:2modifies-parameterassignment modifies parameter op

internal/backend/local/backend_apply.go:88:2

87 stateHook := new(StateHook)
88 op.Hooks = append(op.Hooks, stateHook)
89

internal/encryption/keyprovider.go1

32:3modifies-value-receiverassignment modifies value receiver v

internal/encryption/keyprovider.go:32:3

31 if _, ok := v[first]; !ok {
32 v[first] = make(map[string]cty.Value)
33 }

internal/addrs/instance_key_test.go1

14:13nested-structsmove nested anonymous struct types to named declarations

internal/addrs/instance_key_test.go:14:13

13func TestInstanceKeyString(t *testing.T) {
14 tests := []struct {
15 Key InstanceKey

internal/configs/configload/module_mgr.go1

50:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/configs/configload/module_mgr.go:50:4

49 m.manifest = make(modsdir.Manifest)
50 return nil
51 }

internal/backend/remote-state/kubernetes/client.go1

67:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/kubernetes/client.go:67:3

66 // The secret exists but there is no state in it
67 return nil, nil
68 }

internal/backend/remote-state/s3/backend.go1

1067:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/s3/backend.go:1067:4

1066 return ""
1067 } else {
1068 return v

internal/registry/test/mock_registry.go1

132:6no-initreplace init with explicit initialization

internal/registry/test/mock_registry.go:132:6

131
132func init() {
133 // Add provider aliases

internal/backend/remote-state/cos/client.go1

299:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:299:3

298 err = fmt.Errorf("bucket %s not exists", c.bucket)
299 return
300 }

internal/addrs/module_instance.go1

207:5no-package-varpackage variables introduce mutable global state

internal/addrs/module_instance.go:207:5

206// module, which is also the zero value of ModuleInstance.
207var RootModuleInstance ModuleInstance
208

cmd/tofu/webbrowser_nonunix.go1

8:9package-commentspackage should have a documentation comment

cmd/tofu/webbrowser_nonunix.go:8:9

7
8package main
9

internal/encryption/keyprovider/azure_vault/config_test.go2

6:9package-directory-mismatchpackage azure_vault does not match directory azure_vault

internal/encryption/keyprovider/azure_vault/config_test.go:6:9

5
6package azure_vault
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/azure_vault/config_test.go:6:9

5
6package azure_vault
7

internal/backend/remote-state/oss/client_test.go1

407:14range-value-addresstaking the address of range value tt can be misleading

internal/backend/remote-state/oss/client_test.go:407:14

406 t.Run(tt.name, func(t *testing.T) {
407 client := &RemoteClient{
408 otsTable: tt.otsTable,

internal/legacy/tofu/state.go1

1139:7receiver-namingreceiver name m is inconsistent with s

internal/legacy/tofu/state.go:1139:7

1138// View returns a view with the given resource prefix.
1139func (m *ModuleState) View(id string) *ModuleState {
1140 if m == nil {

internal/cloud/backend_common.go1

42:19redefines-builtin-ididentifier max shadows a predeclared identifier

internal/cloud/backend_common.go:42:19

41// limited by the provided min and max (in milliseconds) durations.
42func backoff(min, max float64, iter int) time.Duration {
43 backoff := math.Pow(2, float64(iter)/5) * min

internal/addrs/module_source_test.go1

33:11redundant-conversionconversion from ModuleSourceLocal to the identical type is redundant

internal/addrs/module_source_test.go:33:11

32 input: "./nope/../child",
33 want: ModuleSourceLocal("./child"),
34 },

internal/legacy/tofu/diff.go1

1260:12simplify-rangeomit the blank range value

internal/legacy/tofu/diff.go:1260:12

1259 prefix := k[:len(k)-1]
1260 for k2, _ := range d.Attributes {
1261 if strings.HasPrefix(k2, prefix) {

internal/legacy/helper/schema/schema.go1

895:3single-case-switchswitch with one case can be replaced by an if statement

internal/legacy/helper/schema/schema.go:895:3

894 for attrK, attrV := range unsuppressedDiff.Attributes {
895 switch rd := d.(type) {
896 case *ResourceData:

internal/command/arguments/apply_test.go1

408:4slice-preallocationpreallocate targetFileArguments with capacity len(range source) before appending once per iteration

internal/command/arguments/apply_test.go:408:4

407 t.Run(name, func(t *testing.T) {
408 targetFileArguments := []string{}
409 wantDiags := tfdiags.Diagnostics{}

internal/command/cliconfig/config_unix.go1

65:3task-commentFIXME comment should be resolved or linked to an owned work item

internal/command/cliconfig/config_unix.go:65:3

64 if home := os.Getenv("HOME"); home != "" {
65 // FIXME: homeDir gets called from globalPluginDirs during init, before
66 // the logging is set up. We should move meta initialization outside of

internal/addrs/module_source.go1

42:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/module_source.go:42:1

41
42var _ ModuleSource = ModuleSourceLocal("")
43var _ ModuleSource = ModuleSourceRegistry{}

internal/addrs/sync_map.go1

92:12unchecked-type-assertionuse the checked two-result form of the type assertion

internal/addrs/sync_map.go:92:12

91 m.elems.Range(func(_, v any) bool {
92 elem := v.(MapElem[K, V])
93 return f(elem.Key, elem.Value)

internal/engine/planning/plan_resource_instance.go1

361:85unexported-returnexported function returns an unexported type

internal/engine/planning/plan_resource_instance.go:361:85

360
361func (b *resourceInstanceObjectsBuilder) Get(addr addrs.AbsResourceInstanceObject) (*resourceInstanceObject, bool) {
362 b.mu.Lock()

internal/backend/local/backend_test.go1

213:66unused-parameterparameter name is unused

internal/backend/local/backend_test.go:213:66

212
213func (b *testDelegateBackend) DeleteWorkspace(_ context.Context, name string, force bool) error {
214 if b.deleteErr {

internal/addrs/input_variable.go1

76:7unused-receiverreceiver v is unused

internal/addrs/input_variable.go:76:7

75
76func (v AbsInputVariableInstance) checkableSigil() {}
77

internal/backend/remote-state/consul/client_test.go1

257:121use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:257:121

256 // create 2 instances to get 2 remote.Clients
257 sA, err := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
258 "address": srv.HTTPAddr,

internal/backend/remote-state/azure/backend.go1

120:27use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/remote-state/azure/backend.go:120:27

119 if !ok || value < 0 {
120 return nil, []error{fmt.Errorf("timeout_seconds expected to be a non-negative integer")}
121 }

internal/command/jsonstate/state.go1

342:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonstate/state.go:342:2

341 // sort the child modules by address for consistency.
342 sort.Slice(ret, func(i, j int) bool {
343 return ret[i].Address < ret[j].Address

internal/backend/remote-state/cos/backend.go1

33:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/cos/backend.go:33:2

32 PROVIDER_SECURITY_TOKEN = "TENCENTCLOUD_SECURITY_TOKEN"
33 PROVIDER_REGION = "TENCENTCLOUD_REGION"
34 PROVIDER_ASSUME_ROLE_ARN = "TENCENTCLOUD_ASSUME_ROLE_ARN"

internal/backend/remote-state/oss/client.go1

435:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/oss/client.go:435:9

434 }
435 sum := md5.Sum(buf.Bytes())
436 payload := &remote.Payload{

internal/addrs/map_test.go1

41:12add-constantstring literal "key set does not include %s" appears more than twice; define a constant

internal/addrs/map_test.go:41:12

40 if want := pathModule; !keySet.Has(want) {
41 t.Errorf("key set does not include %s", want)
42 }

internal/addrs/move_endpoint_module.go1

317:6cognitive-complexityfunction has cognitive complexity 9; maximum is 7

internal/addrs/move_endpoint_module.go:317:6

316// The length of modA must be equal or shorter than the length of modB.
317func moduleInstanceCanMatch(modA, modB ModuleInstance) bool {
318 for i, step := range modA {

internal/command/e2etest/providers_mirror_test.go1

32:6confusing-namingname testOpenTofuProvidersMirror differs from TestOpenTofuProvidersMirror only by capitalization

internal/command/e2etest/providers_mirror_test.go:32:6

31
32func testOpenTofuProvidersMirror(t *testing.T, fixture string) {
33 // This test reaches out to registry.opentofu.org to download the

internal/legacy/helper/schema/resource_data.go1

483:26confusing-resultsadjacent unnamed results of the same type should be named

internal/legacy/helper/schema/resource_data.go:483:26

482func (d *ResourceData) diffChange(
483 k string) (interface{}, interface{}, bool, bool, bool) {
484 // Get the change between the state and the config.

internal/command/views/json/hook.go1

194:6constructor-interface-returnNewProvisionProgress returns interface Hook although its concrete result is consistently *provisionProgress; return the concrete type

internal/command/views/json/hook.go:194:6

193
194func NewProvisionProgress(addr addrs.AbsResourceInstance, provisioner string, output string) Hook {
195 return &provisionProgress{

internal/legacy/helper/schema/provider.go1

81:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/legacy/helper/schema/provider.go:81:2

80 stopMu sync.Mutex
81 stopCtx context.Context
82 stopCtxCancel context.CancelFunc

internal/addrs/provider_config.go1

130:6cyclomatic-complexityfunction complexity is 14; maximum is 10

internal/addrs/provider_config.go:130:6

129// allows an instance key after the alias.
130func ParseAbsProviderConfigInstance(traversal hcl.Traversal) (AbsProviderConfig, InstanceKey, tfdiags.Diagnostics) {
131 modInst, remain, diags := parseModuleInstancePrefix(traversal)

internal/command/cliconfig/svcauthconfig/testdata/helperprog/main.go1

71:2deep-exitprocess-exit calls should be confined to main or init

internal/command/cliconfig/svcauthconfig/testdata/helperprog/main.go:71:2

70 fmt.Fprintf(os.Stderr, f, args...)
71 os.Exit(1)
72}

internal/backend/remote-state/azure/auth/msi_auth.go1

66:2discarded-error-resulterror result returned by os.Setenv is discarded

internal/backend/remote-state/azure/auth/msi_auth.go:66:2

65func (credWrapper *msiTokenCredentialWrapper) GetToken(ctx context.Context, options policy.TokenRequestOptions) (token azcore.AccessToken, err error) {
66 os.Setenv(MSI_ENDPOINT, credWrapper.Endpoint)
67 token, err = credWrapper.cred.GetToken(ctx, options)

internal/backend/local/backend_plan_test.go1

120:1doc-comment-perioddocumentation comment should end with punctuation

internal/backend/local/backend_plan_test.go:120:1

119// This test validates the state lacking behavior when the inner call to
120// Context() fails
121func TestLocal_plan_context_error(t *testing.T) {

internal/command/meta_backend.go1

140:3early-returninvert the condition and return early to reduce nesting

internal/command/meta_backend.go:140:3

139 if err != nil {
140 if errs := providerPluginErrors(nil); errors.As(err, &errs) {
141 // This is a special type returned by m.providerFactories, which

internal/addrs/provider_config_test.go1

187:14error-stringserror string should not be capitalized or end with punctuation

internal/addrs/provider_config_test.go:187:14

186 if test.WantKey != key {
187 t.Errorf("Wanted key %s, got key %s", test.WantKey, key)
188 }

internal/getproviders/errors.go1

63:6error-type-namingerror implementation type should have an Error suffix

internal/getproviders/errors.go:63:6

62// error response when we tried to access it.
63type ErrUnauthorized struct {
64 Hostname svchost.Hostname

internal/addrs/check.go1

119:19exported-declaration-commentexported function or method should have a comment beginning with its name

internal/addrs/check.go:119:19

118
119func (c AbsCheck) CheckableKind() CheckableKind {
120 return CheckableCheck

internal/backend/local/backend_plan_test.go1

1:1file-length-limitfile has 910 lines; maximum is 500

internal/backend/local/backend_plan_test.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0

internal/command/arguments/types.go1

71:76flag-parameterboolean parameter jsonInto controls function flow

internal/command/arguments/types.go:71:76

70// Commands that only support -json (not -json-into) should pass jsonInto=false.
71func (v *ViewOptions) AddGranularFlags(cmdFlags *flag.FlagSet, input bool, jsonInto bool) {
72 if input {

internal/addrs/checkable.go1

1:1formatfile is not formatted

internal/addrs/checkable.go:1:1

1// Copyright (c) The OpenTofu Authors
2// SPDX-License-Identifier: MPL-2.0
  • Fix (safe): run `strider fmt internal/addrs/checkable.go`

internal/addrs/move_endpoint_module_test.go1

709:6function-lengthfunction has 3 statements and 373 lines; maximum is 50 statements or 75 lines

internal/addrs/move_endpoint_module_test.go:709:6

708
709func TestAbsResourceMoveDestination(t *testing.T) {
710 tests := []struct {

internal/engine/applying/operations.go1

72:6function-result-limitfunction returns 4 values; maximum is 3

internal/engine/applying/operations.go:72:6

71
72func compileExecutionGraph(ctx context.Context, plan *plans.Plan, oracle *eval.ApplyOracle, plugins plugins.Plugins) (*execgraph.Graph, *execgraph.CompiledGraph, *execOperations, tfdiags.Diagnostics) {
73 var diags tfdiags.Diagnostics

internal/addrs/parse_target.go1

199:2identical-switch-branchesswitch repeats a case body

internal/addrs/parse_target.go:199:2

198 typeName = tt.Name
199 case hcl.TraverseAttr:
200 typeName = tt.Name

internal/backend/init/init.go1

29:2import-alias-namingimport alias should contain lower-case letters and digits

internal/backend/init/init.go:29:2

28 backendS3 "github.com/opentofu/opentofu/internal/backend/remote-state/s3"
29 backendCloud "github.com/opentofu/opentofu/internal/cloud"
30 "github.com/opentofu/opentofu/internal/encryption"

internal/backend/remote-state/http/backend.go1

160:2import-shadowingidentifier encryption shadows an imported package

internal/backend/remote-state/http/backend.go:160:2

159 *schema.Backend
160 encryption encryption.StateEncryption
161

internal/lang/exprs/evaluate.go1

99:7inefficient-map-lookupreuse the map value obtained by the comma-ok lookup

internal/lang/exprs/evaluate.go:99:7

98 if _, ok := currentChildren[step.Name]; !ok {
99 currentChildren[step.Name] = &symbolTableTempNode{
100 children: make(map[string]*symbolTableTempNode),

internal/registry/client_test.go1

820:37inefficient-sprintffmt.Sprintf is unnecessary for this conversion; use strconv.Itoa

internal/registry/client_test.go:820:37

819 receivedAuthHeader = r.Header.Get("Authorization")
820 w.Header().Set("Content-Length", fmt.Sprintf("%d", len(zipContent)))
821 w.WriteHeader(http.StatusOK)

internal/backend/remote-state/oss/backend_test.go1

268:22insecure-url-schemeURL uses insecure http scheme

internal/backend/remote-state/oss/backend_test.go:268:22

267 name: "should set proxy using http_proxy environment variable",
268 rawUrl: "http://example.com",
269 httpProxy: "http://foo.bar:3128",

internal/cloud/backend_context.go1

135:7max-control-nestingcontrol-flow nesting exceeds 5 levels

internal/cloud/backend_context.go:135:7

134 if v.Category == tfe.CategoryTerraform {
135 if _, ok := op.Variables[v.Key]; !ok {
136 op.Variables[v.Key] = &remoteStoredVariableValue{

internal/command/jsonentities/diagnostic.go1

126:6max-public-structsfile declares more than 5 exported structs

internal/command/jsonentities/diagnostic.go:126:6

125// being included as part of a diagnostic snippet.
126type DiagnosticFunctionCall struct {
127 // CalledAs is the full name that was used to call this function,

internal/backend/local/backend_apply.go1

103:4modifies-parameterassignment modifies parameter runningOp

internal/backend/local/backend_apply.go:103:4

102 op.View.Diagnostics(diags)
103 runningOp.Result = backend.OperationFailure
104 }

internal/encryption/keyprovider.go1

34:2modifies-value-receiverassignment modifies value receiver v

internal/encryption/keyprovider.go:34:2

33 }
34 v[first][second] = value
35}

internal/addrs/module_instance_test.go1

35:17nested-structsmove nested anonymous struct types to named declarations

internal/addrs/module_instance_test.go:35:17

34func TestModuleInstanceEqual_false(t *testing.T) {
35 testCases := []struct {
36 left string

internal/copy/copy_dir.go1

160:4nil-error-returnthis branch proves an error is non-nil but returns nil in an error result

internal/copy/copy_dir.go:160:4

159 if os.IsNotExist(err) {
160 return false, nil
161 }

internal/backend/remote-state/kubernetes/client.go1

255:3nil-value-with-nil-errornil payload is returned with a nil error; return a meaningful value or a descriptive error

internal/backend/remote-state/kubernetes/client.go:255:3

254 if len(lockData) == 0 || !ok {
255 return nil, nil
256 }

internal/backend/remote-state/s3/backend.go1

1080:4no-else-after-returnremove else and unindent its body after the return

internal/backend/remote-state/s3/backend.go:1080:4

1079 return "", false
1080 } else {
1081 return v, true

internal/tfdiags/rpc_friendly.go1

67:6no-initreplace init with explicit initialization

internal/tfdiags/rpc_friendly.go:67:6

66
67func init() {
68 gob.Register((*rpcFriendlyDiag)(nil))

internal/backend/remote-state/cos/client.go1

303:3no-naked-returnreturn values must be explicit

internal/backend/remote-state/cos/client.go:303:3

302 if err != nil {
303 return
304 }

internal/addrs/module_source.go1

46:5no-package-varpackage variables introduce mutable global state

internal/addrs/module_source.go:46:5

45
46var moduleSourceLocalPrefixes = []string{
47 "./",

cmd/tofu/webbrowser_unix.go1

8:9package-commentspackage should have a documentation comment

cmd/tofu/webbrowser_unix.go:8:9

7
8package main
9

internal/encryption/keyprovider/azure_vault/descriptor.go2

6:9package-directory-mismatchpackage azure_vault does not match directory azure_vault

internal/encryption/keyprovider/azure_vault/descriptor.go:6:9

5
6package azure_vault
7
6:9package-namingpackage name should be short, lower-case, and contain no separators

internal/encryption/keyprovider/azure_vault/descriptor.go:6:9

5
6package azure_vault
7

internal/backend/remote-state/s3/backend_test.go1

1060:107range-value-addresstaking the address of range value tc can be misleading

internal/backend/remote-state/s3/backend_test.go:1060:107

1059 case false:
1060 gotProxyURL, err := b.(*Backend).awsConfig.HTTPClient.(*awshttp.BuildableClient).GetTransport().Proxy(&http.Request{
1061 URL: newURL(tc.calledURL),

internal/legacy/tofu/state.go1

1156:7receiver-namingreceiver name m is inconsistent with s

internal/legacy/tofu/state.go:1156:7

1155
1156func (m *ModuleState) init() {
1157 m.Lock()

internal/cloud/cloudplan/saved_plan_test.go1

74:5redefines-builtin-ididentifier error shadows a predeclared identifier

internal/cloud/cloudplan/saved_plan_test.go:74:5

73 // os.Stat() wants path to file
74 _, error := os.Stat(tmpFile.Name())
75 if error != nil {

internal/addrs/module_source_test.go1

37:11redundant-conversionconversion from ModuleSourceLocal to the identical type is redundant

internal/addrs/module_source_test.go:37:11

36 input: "../sibling",
37 want: ModuleSourceLocal("../sibling"),
38 },

internal/legacy/tofu/diff.go1

1300:9simplify-rangeomit the blank range value

internal/legacy/tofu/diff.go:1300:9

1299 checkNew := make(map[string]struct{})
1300 for k, _ := range d.Attributes {
1301 checkOld[k] = struct{}{}

internal/tofu/node_resource_abstract_instance.go1

454:3single-case-switchswitch with one case can be replaced by an if statement

internal/tofu/node_resource_abstract_instance.go:454:3

453 for _, ref := range preventDestroyRefs {
454 switch addr := ref.Subject.(type) {
455 case addrs.ForEachAttr, addrs.CountAttr:

internal/command/arguments/apply_test.go1

586:4slice-preallocationpreallocate excludeFileArguments with capacity len(range source) before appending once per iteration

internal/command/arguments/apply_test.go:586:4

585 t.Run(name, func(t *testing.T) {
586 excludeFileArguments := []string{}
587 wantDiags := tfdiags.Diagnostics{}

internal/command/cliconfig/oci_credentials.go1

552:3task-commentFIXME comment should be resolved or linked to an owned work item

internal/command/cliconfig/oci_credentials.go:552:3

551 case oauth:
552 // FIXME: Is refresh_roken actually required? We could potentially allow setting
553 // only access_token and let the request just immediately fail if the token has expired.

internal/addrs/move_endpoint_kind.go1

16:1top-level-declaration-ordertop-level declarations should be ordered as const, var, type, then func

internal/addrs/move_endpoint_kind.go:16:1

15
16const (
17 // MoveEndpointModule indicates that a move endpoint either refers to

internal/backend/remote-state/azure/backend.go1

263:28unchecked-type-assertionuse the checked two-result form of the type assertion

internal/backend/remote-state/azure/backend.go:263:28

262 ValidateFunc: func(v any, _ string) ([]string, []error) {
263 _, err := newCPKInfo(v.(string))
264 if err != nil {

internal/engine/planning/plan_resource_instance.go1

402:50unexported-returnexported function returns an unexported type

internal/engine/planning/plan_resource_instance.go:402:50

401
402func (b *resourceInstanceObjectsBuilder) Close() *resourceInstanceObjects {
403 b.mu.Lock()

internal/backend/local/backend_test.go1

213:79unused-parameterparameter force is unused

internal/backend/local/backend_test.go:213:79

212
213func (b *testDelegateBackend) DeleteWorkspace(_ context.Context, name string, force bool) error {
214 if b.deleteErr {

internal/addrs/input_variable.go1

93:7unused-receiverreceiver v is unused

internal/addrs/input_variable.go:93:7

92
93func (v AbsInputVariableInstance) CheckableKind() CheckableKind {
94 return CheckableInputVariable

internal/backend/remote-state/consul/client_test.go1

265:121use-anyuse any instead of interface{}

internal/backend/remote-state/consul/client_test.go:265:121

264
265 sB, err := backend.TestBackendConfig(t, New(encryption.StateEncryptionDisabled()), backend.TestWrapConfig(map[string]interface{}{
266 "address": srv.HTTPAddr,

internal/backend/remote-state/azure/backend_state.go1

49:10use-errors-newreplace fmt.Errorf with errors.New for a static message

internal/backend/remote-state/azure/backend_state.go:49:10

48 if name == backend.DefaultStateName || name == "" {
49 return fmt.Errorf("can't delete default state")
50 }

internal/command/jsonstate/state.go1

356:2use-slices-sortuse slices.Sort or slices.SortFunc when possible

internal/command/jsonstate/state.go:356:2

355 }
356 sort.Slice(sortedResources, func(i, j int) bool {
357 return sortedResources[i].Addr.Less(sortedResources[j].Addr)

internal/backend/remote-state/cos/backend.go1

34:2var-namingidentifier should use MixedCaps rather than underscores

internal/backend/remote-state/cos/backend.go:34:2

33 PROVIDER_REGION = "TENCENTCLOUD_REGION"
34 PROVIDER_ASSUME_ROLE_ARN = "TENCENTCLOUD_ASSUME_ROLE_ARN"
35 PROVIDER_ASSUME_ROLE_SESSION_NAME = "TENCENTCLOUD_ASSUME_ROLE_SESSION_NAME"

internal/backend/remote-state/oss/client_test.go1

245:9weak-cryptographydeprecated cryptographic primitive crypto/md5.Sum should not protect new data

internal/backend/remote-state/oss/client_test.go:245:9

244
245 sum := md5.Sum([]byte("test"))
246

internal/addrs/map_test.go1

56:37add-constantstring literal "hello" appears more than twice; define a constant

internal/addrs/map_test.go:56:37

55 }
56 if got, want := m.Get(localHello), "hello"; got != want {
57 t.Errorf("unexpected value %q for %s; want %q", got, localHello, want)

internal/addrs/move_endpoint_module.go1

340:32cognitive-complexityfunction has cognitive complexity 9; maximum is 7

internal/addrs/move_endpoint_module.go:340:32

339// is the "from" of another statement.
340func (e *MoveEndpointInModule) CanChainFrom(other *MoveEndpointInModule) bool {
341 eMod := e.synthModuleInstance()

internal/command/jsonconfig/config.go1

144:6confusing-namingname marshal differs from Marshal only by capitalization

internal/command/jsonconfig/config.go:144:6

143// treatment through the centralized doc comment.
144func marshal(c *configs.Config, schemas *tofu.Schemas) ([]byte, error) {
145 var output config

internal/legacy/helper/schema/resource_data.go1

483:45confusing-resultsadjacent unnamed results of the same type should be named

internal/legacy/helper/schema/resource_data.go:483:45

482func (d *ResourceData) diffChange(
483 k string) (interface{}, interface{}, bool, bool, bool) {
484 // Get the change between the state and the config.

internal/command/views/json/hook.go1

218:6constructor-interface-returnNewProvisionComplete returns interface Hook although its concrete result is consistently *provisionComplete; return the concrete type

internal/command/views/json/hook.go:218:6

217
218func NewProvisionComplete(addr addrs.AbsResourceInstance, provisioner string) Hook {
219 return &provisionComplete{

internal/legacy/helper/schema/provisioner.go1

53:2context-stored-in-structdo not store context.Context in a struct; pass it explicitly to each operation

internal/legacy/helper/schema/provisioner.go:53:2

52
53 stopCtx context.Context
54 stopCtxCancel context.CancelFunc

internal/addrs/sync_map_test.go1

16:6cyclomatic-complexityfunction complexity is 21; maximum is 10

internal/addrs/sync_map_test.go:16:6

15// map_test.go
16func TestSyncMap(t *testing.T) {
17 variableName := InputVariable{Name: "name"}

internal/command/command_test.go1

92:2deep-exitprocess-exit calls should be confined to main or init

internal/command/command_test.go:92:2

91
92 os.Exit(m.Run())
93}