Skip to content

Commit 5da2582

Browse files
authored
chore: lint parity with CLI (#356)
1 parent 4ebafec commit 5da2582

40 files changed

+408
-391
lines changed

tools/cli/.golangci.yml

Lines changed: 51 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,15 @@ linters-settings:
1818
- name: blank-imports
1919
- name: context-as-argument
2020
- name: context-keys-type
21+
- name: defer
2122
- name: dot-imports
2223
- name: error-return
2324
- name: error-strings
2425
- name: error-naming
26+
- name: early-return
2527
- name: errorf
2628
- name: exported
29+
- name: import-shadowing
2730
- name: indent-error-flow
2831
- name: if-return
2932
- name: increment-decrement
@@ -42,6 +45,14 @@ linters-settings:
4245
- name: unused-parameter
4346
- name: unreachable-code
4447
- name: redefines-builtin-id
48+
- name: unused-receiver
49+
- name: constant-logical-expr
50+
- name: confusing-naming
51+
- name: unnecessary-stmt
52+
- name: use-any
53+
- name: imports-blocklist
54+
arguments:
55+
- "github.com/pkg/errors"
4556
misspell:
4657
locale: US
4758
lll:
@@ -52,42 +63,49 @@ linters-settings:
5263
funlen:
5364
lines: 360
5465
statements: 120
66+
gci:
67+
sections:
68+
- standard
69+
- default
5570
linters:
5671
disable-all: true
5772
enable:
58-
- dogsled
59-
- errcheck
60-
- funlen
61-
- gocritic
62-
- gofmt
63-
- goimports
64-
- revive
65-
- goprintffuncname
66-
- gosec
67-
- gosimple
68-
- govet
69-
- ineffassign
70-
- lll
71-
- misspell
72-
- nakedret
73-
- nolintlint
74-
- rowserrcheck
75-
- copyloopvar
76-
- staticcheck
77-
- stylecheck
78-
- typecheck
79-
- unconvert
80-
- unused
81-
- whitespace
82-
- thelper
83-
- testifylint
84-
- exhaustive
85-
- makezero
86-
- noctx
87-
- tenv
88-
- prealloc
89-
- predeclared
90-
- whitespace
73+
- copyloopvar # copyloopvar is a linter detects places where loop variables are copied
74+
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
75+
- errcheck # errcheck is a program for checking for unchecked errors in Go code. These unchecked errors can be critical bugs in some cases
76+
- errorlint # Errorlint is a linter that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
77+
- exhaustive # check exhaustiveness of enum switch statements
78+
- copyloopvar # copyloopvar is a linter detects places where loop variables are copied. Replaces exportloopref since Go1.22
79+
- funlen # Tool for detection of long functions
80+
- gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false]
81+
- gocritic # Provides diagnostics that check for bugs, performance and style issues.
82+
- godot # Check if comments end in a period [fast: true, auto-fix: true]
83+
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
84+
- goimports # Check import statements are formatted according to the 'goimport' command. Reformat imports in autofix mode.
85+
- goprintffuncname # Checks that printf-like functions are named with `f` at the end.
86+
- gosec # Inspects source code for security problems
87+
- gosimple # Linter for Go source code that specializes in simplifying code
88+
- govet # Vet examines Go source code and reports suspicious constructs. It is roughly the same as 'go vet' and uses its passes.
89+
- ineffassign # Detects when assignments to existing variables are not used
90+
- lll # Reports long lines
91+
- makezero # Finds slice declarations with non-zero initial length
92+
- misspell # Finds commonly misspelled English words
93+
- nakedret # Checks that functions with naked returns are not longer than a maximum size (can be zero).
94+
- noctx # Finds sending http request without context.Context
95+
- nolintlint # Reports ill-formed or insufficient nolint directives
96+
- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative.
97+
- prealloc # Finds slice declarations that could potentially be pre-allocated
98+
- predeclared # find code that shadows one of Go's predeclared identifiers
99+
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
100+
- rowserrcheck # checks whether Rows.Err of rows is checked successfully
101+
- staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint.
102+
- stylecheck # Stylecheck is a replacement for golint
103+
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
104+
- testifylint # Checks usage of github.com/stretchr/testify.
105+
- thelper # thelper detects tests helpers which is not start with t.Helper() method.
106+
- unconvert # Remove unnecessary type conversions
107+
- unused # Checks Go code for unused constants, variables, functions and types
108+
- whitespace # Whitespace is a linter that checks for unnecessary newlines at the start and end of functions, if, for, etc.
91109

92110
# don't enable:
93111
# - deadcode

tools/cli/internal/apiversion/version.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ func FindLatestContentVersionMatched(op *openapi3.Operation, requestedVersion *A
178178
return latestVersionMatch
179179
}
180180

181-
// Sort versions
181+
// Sort versions.
182182
func Sort(versions []*APIVersion) {
183183
for i := 0; i < len(versions); i++ {
184184
for j := i + 1; j < len(versions); j++ {

tools/cli/internal/apiversion/version_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ func TestParseVersion(t *testing.T) {
5858

5959
for _, tt := range testCases {
6060
t.Run(tt.name, func(t *testing.T) {
61+
t.Parallel()
6162
match, err := Parse(tt.contentType)
6263
if tt.wantErr {
6364
assert.Error(t, err)
@@ -127,8 +128,8 @@ func TestNewAPIVersionFromContentType(t *testing.T) {
127128

128129
for _, tt := range testCases {
129130
t.Run(tt.name, func(t *testing.T) {
130-
version, err := New(WithContent(tt.contentType))
131131
t.Parallel()
132+
version, err := New(WithContent(tt.contentType))
132133
if tt.wantErr {
133134
assert.Error(t, err)
134135
} else {

tools/cli/internal/breakingchanges/exemptions.go

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package breakingchanges
1616

1717
import (
18+
"errors"
1819
"fmt"
1920
"log"
2021
"strings"
@@ -57,7 +58,7 @@ func isWithinExpirationDate(exemption Exemption) bool {
5758

5859
func validateExemption(exemption Exemption) error {
5960
if _, err := time.Parse("2006-01-02", exemption.ExemptUntil); err != nil {
60-
return fmt.Errorf("validation error: %v. Exemption: %s", err, exemption)
61+
return fmt.Errorf("validation error: %w. Exemption: %s", err, exemption)
6162
}
6263

6364
if err := validateField(exemption.Reason, "reason", exemption); err != nil {
@@ -80,34 +81,34 @@ func validateField(fieldValue, fieldName string, exemption Exemption) error {
8081

8182
func transformComponentEntry(breakingChangeDescription string) string {
8283
if strings.Contains(breakingChangeDescription, "api-schema-removed") && !strings.Contains(breakingChangeDescription, "in components") {
83-
return fmt.Sprintf("in components %s", breakingChangeDescription)
84+
return "in components " + breakingChangeDescription
8485
}
8586
return breakingChangeDescription
8687
}
8788

8889
// GetValidExemptionsList returns a list of exemptions. If ignoreExpiration is set to true, it will return all exemptions.
8990
func GetValidExemptionsList(exemptionsPath string, ignoreExpiration bool, fs afero.Fs) ([]Exemption, error) {
9091
if exemptionsPath == "" {
91-
return nil, fmt.Errorf("could not find exemptions file path")
92+
return nil, errors.New("could not find exemptions file path")
9293
}
9394

9495
log.Printf("Generating exemptions from file in %s", exemptionsPath)
9596
exemptionsFile, err := fs.Open(exemptionsPath)
9697
if err != nil {
97-
return nil, fmt.Errorf("could not open exemptions file: %v", err)
98+
return nil, fmt.Errorf("could not open exemptions file: %w", err)
9899
}
99100
defer exemptionsFile.Close()
100101
data, err := afero.ReadAll(exemptionsFile)
101102
if err != nil {
102-
return nil, fmt.Errorf("could not read exemptions file: %v", err)
103+
return nil, fmt.Errorf("could not read exemptions file: %w", err)
103104
}
104105

105106
var exemptions []Exemption
106107
if err := yaml.Unmarshal(data, &exemptions); err != nil {
107-
return nil, fmt.Errorf("could not unmarshal exemptions: %v", err)
108+
return nil, fmt.Errorf("could not unmarshal exemptions: %w", err)
108109
}
109110

110-
var validExemptions []Exemption
111+
validExemptions := make([]Exemption, 0, len(exemptions))
111112
for _, exemption := range exemptions {
112113
if err := validateExemption(exemption); err != nil {
113114
return nil, err
@@ -126,10 +127,10 @@ func GetValidExemptionsList(exemptionsPath string, ignoreExpiration bool, fs afe
126127
func CreateExemptionsFile(outputPath, exemptionsPath string, ignoreExpiration bool, fs afero.Fs) error {
127128
validExemptions, err := GetValidExemptionsList(exemptionsPath, ignoreExpiration, fs)
128129
if err != nil {
129-
return fmt.Errorf("could not get valid exemptions list: %v", err)
130+
return fmt.Errorf("could not get valid exemptions list: %w", err)
130131
}
131132

132-
var transformedExemptions = []string{}
133+
transformedExemptions := make([]string, 0, len(validExemptions))
133134
for _, validExemption := range validExemptions {
134135
exemptionLine := transformComponentEntry(validExemption.BreakingChangeDescription)
135136
transformedExemptions = append(transformedExemptions, exemptionLine)
@@ -138,13 +139,13 @@ func CreateExemptionsFile(outputPath, exemptionsPath string, ignoreExpiration bo
138139

139140
file, err := fs.Create(outputPath)
140141
if err != nil {
141-
return fmt.Errorf("could not create exemptions file: %v", err)
142+
return fmt.Errorf("could not create exemptions file: %w", err)
142143
}
143144
defer file.Close()
144145

145146
for _, exemption := range transformedExemptions {
146147
if _, err := fmt.Fprintf(file, "%s\n", exemption); err != nil {
147-
return fmt.Errorf("could not write to exemptions file: %v", err)
148+
return fmt.Errorf("could not write to exemptions file: %w", err)
148149
}
149150
}
150151
log.Printf("Exemptions file generated in %s\n", outputPath)

tools/cli/internal/changelog/changelog.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ func findChangelogEntry(changelog []*Entry, date, operationID, version, changeCo
474474
return nil
475475
}
476476

477-
func newStringFromStruct(data interface{}) string {
477+
func newStringFromStruct(data any) string {
478478
bytes, err := json.MarshalIndent(data, "", " ")
479479
if err != nil {
480480
return ""
@@ -489,7 +489,7 @@ func newStringFromStruct(data interface{}) string {
489489
// 1. Remove all entries with hideFromChangelog
490490
// 2. Remove all empty versions
491491
// 3. Remove all empty paths
492-
// 4. Shift changelog entry if it turns out empty
492+
// 4. Shift changelog entry if it turns out empty.
493493
func NewNotHiddenEntries(changelog []*Entry) ([]*Entry, error) {
494494
if len(changelog) == 0 {
495495
return changelog, nil

tools/cli/internal/changelog/manual_entry_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ func TestDetectManualEntriesAndMergeChangelog(t *testing.T) {
6464
HTTPMethod: "POST",
6565
Tag: "Multi-Cloud Clusters",
6666
Sunset: "",
67-
ManualChangelogEntries: map[string]interface{}{
67+
ManualChangelogEntries: map[string]any{
6868
previousRunDate: "change info 1", // Already in the changelog
6969
runDate: "change info 2", // Should be added to the changelog
7070
theDayAfterRunDate: "change info 3", // Should not be added to the changelog

tools/cli/internal/changelog/merge.go

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ func newChangeTypeOverrides() map[string]string {
5050
}
5151
}
5252

53-
// NewEntriesFromSunsetAndManualEntry merges the base changelog with the new changes from manual entries and sunset endpoints
53+
// NewEntriesFromSunsetAndManualEntry merges the base changelog with the new changes from manual entries and sunset endpoints.
5454
func (m *Changelog) NewEntriesFromSunsetAndManualEntry() ([]*Entry, error) {
5555
conf := outputfilter.NewOperationConfigs(nil, m.Revision)
5656
if _, err := m.newEntriesFromSunsetEndpoints(conf); err != nil {
@@ -116,7 +116,7 @@ func (m *Changelog) newManualEntries(conf map[string]*outputfilter.OperationConf
116116
return m.BaseChangelog, nil
117117
}
118118

119-
// newEntryFromOasDiff merges the base changelog with the new changes from a Base and Revision OpenAPI specs
119+
// newEntryFromOasDiff merges the base changelog with the new changes from a Base and Revision OpenAPI specs.
120120
func (m *Changelog) newEntryFromOasDiff() ([]*Entry, error) {
121121
changes, err := m.newOasDiffEntries()
122122
if err != nil {
@@ -143,7 +143,7 @@ func (m *Changelog) newEntryFromOasDiff() ([]*Entry, error) {
143143
// Logic:
144144
// 1. If the entry already exists in the changelog for the Run Date, use that entry or create it (newEntryAtRunDate)
145145
// 2. Get the paths from the changes and add them to the entry
146-
// 3. Sort the changelog by date DESC, path + httpMethod ASC, version DESC
146+
// 3. Sort the changelog by date DESC, path + httpMethod ASC, version DESC.
147147
func (m *Changelog) mergeChangelog(
148148
changeType string,
149149
changes []*outputfilter.OasDiffEntry,
@@ -167,7 +167,7 @@ func (m *Changelog) mergeChangelog(
167167
// 1. Get the deprecated paths from the changes
168168
// 2. Get the updated paths with the deprecated changes from newPathsFromDeprecatedChanges
169169
// 3. Get the revision paths from the changes
170-
// 4. Get the updated paths with the revision changes from newPathsFromRevisionChanges
170+
// 4. Get the updated paths with the revision changes from newPathsFromRevisionChanges.
171171
func (m *Changelog) newPathsFromChanges(
172172
changes []*outputfilter.OasDiffEntry,
173173
changeType string, entry *Entry,
@@ -185,7 +185,7 @@ func (m *Changelog) newPathsFromChanges(
185185
return paths, nil
186186
}
187187

188-
// newPathsFromRevisionChanges creates new paths from revision changes
188+
// newPathsFromRevisionChanges creates new paths from revision changes.
189189
func (m *Changelog) newPathsFromRevisionChanges(
190190
changes []*outputfilter.OasDiffEntry,
191191
changeType string, changelogPath *[]*Path,
@@ -194,7 +194,7 @@ func (m *Changelog) newPathsFromRevisionChanges(
194194
return newMergedChanges(revisionChanges, changeType, m.RevisionMetadata.ActiveVersion, changelogPath, conf)
195195
}
196196

197-
// newPathsFromDeprecatedChanges creates new paths from deprecated changes
197+
// newPathsFromDeprecatedChanges creates new paths from deprecated changes.
198198
func (m *Changelog) newPathsFromDeprecatedChanges(
199199
changes []*outputfilter.OasDiffEntry,
200200
changelogPath *[]*Path,
@@ -219,7 +219,7 @@ func (m *Changelog) newOasDiffEntries() ([]*outputfilter.OasDiffEntry, error) {
219219
return outputfilter.NewChangelogEntries(changes, diffResult.SpecInfoPair, m.ExemptionFilePath)
220220
}
221221

222-
// sortChangelog sorts changelog by date DESC, path + httpMethod ASC, version DESC
222+
// sortChangelog sorts changelog by date DESC, path + httpMethod ASC, version DESC.
223223
func sortChangelog(changelog []*Entry) []*Entry {
224224
sort.Slice(changelog, func(i, j int) bool {
225225
return changelog[i].Date > changelog[j].Date
@@ -242,7 +242,7 @@ func sortChangelog(changelog []*Entry) []*Entry {
242242
return changelog
243243
}
244244

245-
// newMergedChanges merges the OasDiff changes into the changelog []paths
245+
// newMergedChanges merges the OasDiff changes into the changelog []paths.
246246
func newMergedChanges(changes []*outputfilter.OasDiffEntry,
247247
changeType, version string, changelogPath *[]*Path,
248248
operationConfig map[string]*outputfilter.OperationConfigs) ([]*Path, error) {
@@ -372,7 +372,7 @@ func newEntryVersion(versions *[]*Version, specVersion string) *Version {
372372
}
373373

374374
// newPathEntry returns the index and the path entry if it already exists in the changelog
375-
// otherwise it returns -1 and a new path entry
375+
// otherwise it returns -1 and a new path entry.
376376
func newPathEntry(paths *[]*Path, path, operation string) *Path {
377377
for _, p := range *paths {
378378
if p.URI == path && p.HTTPMethod == operation {

0 commit comments

Comments
 (0)