Skip to content

Commit 49090b4

Browse files
committed
refactor: modernize go codebase per golangci-lint recommendations
Apply Go 1.18+ improvements and performance optimizations: - replace interface{} with any for modern Go syntax - use strings.Builder instead of += in loops for better performance - replace reflect.TypeOf with reflect.TypeFor for type safety - use strings.CutPrefix instead of HasPrefix + TrimPrefix - simplify conditionals using max() builtin - replace manual loops with slices.Contains These changes improve code readability, performance, and align with current Go best practices.
1 parent ae53062 commit 49090b4

File tree

9 files changed

+38
-45
lines changed

9 files changed

+38
-45
lines changed

main.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -239,13 +239,13 @@ func allKeys(in ...map[string]string) []string {
239239
return result
240240
}
241241

242-
func logf(format string, args ...interface{}) {
242+
func logf(format string, args ...any) {
243243
fmt.Fprint(os.Stderr, "go-jsonschema: ")
244244
fmt.Fprintf(os.Stderr, format, args...)
245245
fmt.Fprint(os.Stderr, "\n")
246246
}
247247

248-
func verboseLogf(format string, args ...interface{}) {
248+
func verboseLogf(format string, args ...any) {
249249
if verbose {
250250
logf(format, args...)
251251
}

pkg/codegen/emitter.go

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,7 @@ func (e *Emitter) Indent(n int32) {
3939

4040
func (e *Emitter) Comment(s string) {
4141
if s != "" {
42-
limit := e.maxLineLength - e.indent
43-
if limit < 0 {
44-
limit = 0
45-
}
42+
limit := max(e.maxLineLength-e.indent, 0)
4643

4744
//nolint:gosec // limit is guarded against negative values
4845
lines := strings.Split(wordwrap.WrapString(s, uint(limit)), "\n")
@@ -53,13 +50,10 @@ func (e *Emitter) Comment(s string) {
5350
}
5451
}
5552

56-
func (e *Emitter) Commentf(s string, args ...interface{}) {
53+
func (e *Emitter) Commentf(s string, args ...any) {
5754
s = fmt.Sprintf(s, args...)
5855
if s != "" {
59-
limit := e.maxLineLength - e.indent
60-
if limit < 0 {
61-
limit = 0
62-
}
56+
limit := max(e.maxLineLength-e.indent, 0)
6357

6458
//nolint:gosec // limit is guarded against negative values
6559
lines := strings.Split(wordwrap.WrapString(s, uint(limit)), "\n")
@@ -70,13 +64,13 @@ func (e *Emitter) Commentf(s string, args ...interface{}) {
7064
}
7165
}
7266

73-
func (e *Emitter) Printf(format string, args ...interface{}) {
67+
func (e *Emitter) Printf(format string, args ...any) {
7468
e.checkIndent()
7569
fmt.Fprintf(&e.sb, format, args...)
7670
e.start = false
7771
}
7872

79-
func (e *Emitter) Printlnf(format string, args ...interface{}) {
73+
func (e *Emitter) Printlnf(format string, args ...any) {
8074
e.Printf(format, args...)
8175
e.Newline()
8276
}

pkg/codegen/model.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ func (p *Package) Generate(out *Emitter) error {
146146
type Var struct {
147147
Type Type
148148
Name string
149-
Value interface{}
149+
Value any
150150
}
151151

152152
func (v *Var) GetName() string {
@@ -171,7 +171,7 @@ func (v *Var) Generate(out *Emitter) error {
171171
type Constant struct {
172172
Type Type
173173
Name string
174-
Value interface{}
174+
Value any
175175
}
176176

177177
func (c *Constant) GetName() string {
@@ -427,7 +427,7 @@ func (NullType) Generate(out *Emitter) error {
427427
type StructType struct {
428428
Fields []StructField
429429
RequiredJSONFields []string
430-
DefaultValue interface{}
430+
DefaultValue any
431431
}
432432

433433
func (*StructType) IsNillable() bool { return false }
@@ -468,7 +468,7 @@ type StructField struct {
468468
Comment string
469469
Tags string
470470
JSONName string
471-
DefaultValue interface{}
471+
DefaultValue any
472472
SchemaType *schemas.Type
473473
}
474474

pkg/generator/schema_generator.go

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package generator
33
import (
44
"errors"
55
"fmt"
6+
"slices"
67
"strings"
78

89
"github.com/google/go-cmp/cmp"
@@ -812,19 +813,19 @@ func (g *schemaGenerator) addStructField(
812813
SchemaType: prop,
813814
}
814815

815-
tags := ""
816+
var tags strings.Builder
816817

817818
if isRequired || g.DisableOmitempty() {
818819
for _, tag := range g.config.Tags {
819-
tags += fmt.Sprintf(`%s:"%s" `, tag, name)
820+
tags.WriteString(fmt.Sprintf(`%s:"%s" `, tag, name))
820821
}
821822
} else {
822823
for _, tag := range g.config.Tags {
823-
tags += fmt.Sprintf(`%s:"%s,omitempty" `, tag, name)
824+
tags.WriteString(fmt.Sprintf(`%s:"%s,omitempty" `, tag, name))
824825
}
825826
}
826827

827-
structField.Tags = strings.TrimSpace(tags)
828+
structField.Tags = strings.TrimSpace(tags.String())
828829

829830
if structField.Comment == "" {
830831
structField.Comment = fmt.Sprintf("%s corresponds to the JSON schema field %q.",
@@ -1350,10 +1351,8 @@ func (g *schemaGenerator) isTypeNullable(t *schemas.Type) (int, bool) {
13501351
return 0, true
13511352
}
13521353

1353-
for _, tt := range t.Type {
1354-
if tt == schemas.TypeNameNull {
1355-
return -1, true
1356-
}
1354+
if slices.Contains(t.Type, schemas.TypeNameNull) {
1355+
return -1, true
13571356
}
13581357

13591358
return -1, false

pkg/generator/validator.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ type defaultValidator struct {
153153
jsonName string
154154
fieldName string
155155
defaultValueType codegen.Type
156-
defaultValue interface{}
156+
defaultValue any
157157
}
158158

159159
func (v *defaultValidator) generate(out *codegen.Emitter, format string) error {
@@ -176,14 +176,14 @@ func (v *defaultValidator) dumpDefaultValueAssignment(out *codegen.Emitter) (any
176176
if nt, ok := v.defaultValueType.(*codegen.NamedType); ok {
177177
dvm, ok := v.defaultValue.(map[string]any)
178178
if ok {
179-
namedFields := ""
179+
var namedFields strings.Builder
180180
for _, k := range sortedKeys(dvm) {
181-
namedFields += fmt.Sprintf("\n%s: %s,", upperFirst(k), litter.Sdump(dvm[k]))
181+
namedFields.WriteString(fmt.Sprintf("\n%s: %s,", upperFirst(k), litter.Sdump(dvm[k])))
182182
}
183183

184-
namedFields += "\n"
184+
namedFields.WriteString("\n")
185185

186-
defaultValue := fmt.Sprintf(`%s{%s}`, nt.Decl.GetName(), namedFields)
186+
defaultValue := fmt.Sprintf(`%s{%s}`, nt.Decl.GetName(), namedFields.String())
187187

188188
return fmt.Sprintf(`%s = %s`, getPlainName(v.fieldName), defaultValue), nil
189189
}
@@ -246,7 +246,7 @@ func (v *defaultValidator) tryDumpDefaultSlice(maxLineLen int32) (string, error)
246246
kind := reflect.ValueOf(v.defaultValue).Kind()
247247

248248
if kind == reflect.Slice {
249-
df, ok := v.defaultValue.([]interface{})
249+
df, ok := v.defaultValue.([]any)
250250
if !ok {
251251
return "", ErrInvalidDefaultValue
252252
}

pkg/schemas/model.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -175,18 +175,18 @@ type Type struct {
175175
Properties map[string]*Type `json:"properties,omitempty"` // Section 5.16.
176176
PatternProperties map[string]*Type `json:"patternProperties,omitempty"` // Section 5.17.
177177
AdditionalProperties *Type `json:"additionalProperties,omitempty"` // Section 5.18.
178-
Enum []interface{} `json:"enum,omitempty"` // Section 5.20.
178+
Enum []any `json:"enum,omitempty"` // Section 5.20.
179179
Type TypeList `json:"type,omitempty"` // Section 5.21.
180180
// RFC draft-bhutton-json-schema-01, section 10.
181181
AllOf []*Type `json:"allOf,omitempty"` // Section 10.2.1.1.
182182
AnyOf []*Type `json:"anyOf,omitempty"` // Section 10.2.1.2.
183183
OneOf []*Type `json:"oneOf,omitempty"` // Section 10.2.1.3.
184184
Not *Type `json:"not,omitempty"` // Section 10.2.1.4.
185185
// RFC draft-wright-json-schema-validation-00, section 6, 7.
186-
Title string `json:"title,omitempty"` // Section 6.1.
187-
Description string `json:"description,omitempty"` // Section 6.1.
188-
Default interface{} `json:"default,omitempty"` // Section 6.2.
189-
Format string `json:"format,omitempty"` // Section 7.
186+
Title string `json:"title,omitempty"` // Section 6.1.
187+
Description string `json:"description,omitempty"` // Section 6.1.
188+
Default any `json:"default,omitempty"` // Section 6.2.
189+
Format string `json:"format,omitempty"` // Section 7.
190190
// RFC draft-wright-json-schema-hyperschema-00, section 4.
191191
Media *Type `json:"media,omitempty"` // Section 4.3.
192192
BinaryEncoding string `json:"binaryEncoding,omitempty"` // Section 4.3.
@@ -393,7 +393,7 @@ func updateAllRefsValues(structValue *reflect.Value, refPath string) error {
393393
type typeListTransformer struct{}
394394

395395
func (t typeListTransformer) Transformer(typ reflect.Type) func(dst, src reflect.Value) error {
396-
if typ == reflect.TypeOf(TypeList{}) {
396+
if typ == reflect.TypeFor[TypeList]() {
397397
return func(dst, src reflect.Value) error {
398398
return nil
399399
}

pkg/schemas/parse.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ func FromYAMLFile(fileName string) (*Schema, error) {
4848

4949
func FromYAMLReader(r io.Reader) (*Schema, error) {
5050
// Marshal to JSON first because YAML decoder doesn't understand JSON tags.
51-
var m map[string]interface{}
51+
var m map[string]any
5252

5353
if err := yaml.NewDecoder(r).Decode(&m); err != nil {
5454
return nil, fmt.Errorf("failed to unmarshal YAML: %w", err)

pkg/schemas/types.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,8 @@ func IsPrimitiveType(t string) bool {
2424
}
2525

2626
func CleanNameForSorting(name string) string {
27-
if strings.HasPrefix(name, PrefixEnumValue) {
28-
return strings.TrimPrefix(name, PrefixEnumValue) + "_enumValues" // Append a string for sorting properly.
27+
if after, found := strings.CutPrefix(name, PrefixEnumValue); found {
28+
return after + "_enumValues" // Append a string for sorting properly.
2929
}
3030

3131
return name

pkg/yamlutils/yaml.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,24 +3,24 @@ package yamlutils
33
import "fmt"
44

55
// FixMapKeys fixes non-string keys that occur in nested YAML unmarshalling results.
6-
func FixMapKeys(m map[string]interface{}) {
6+
func FixMapKeys(m map[string]any) {
77
for k, v := range m {
88
m[k] = fixMapKeysIn(v)
99
}
1010
}
1111

1212
// Fix non-string keys that occur in nested YAML unmarshalling results.
13-
func fixMapKeysIn(value interface{}) interface{} {
13+
func fixMapKeysIn(value any) any {
1414
switch t := value.(type) {
15-
case []interface{}:
15+
case []any:
1616
for i, elem := range t {
1717
t[i] = fixMapKeysIn(elem)
1818
}
1919

2020
return t
2121

22-
case map[interface{}]interface{}:
23-
m := map[string]interface{}{}
22+
case map[any]any:
23+
m := map[string]any{}
2424

2525
for k, v := range t {
2626
ks, ok := k.(string)

0 commit comments

Comments
 (0)