From cc14d3cc13828b514554c2d53b25db750613ff8d Mon Sep 17 00:00:00 2001 From: 4meepo Date: Thu, 19 Oct 2023 13:29:48 +0800 Subject: [PATCH] fix index out of range --- tagalign.go | 12 ++++++++++-- testdata/bad_syntax_tag/example.go | 8 ++++---- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/tagalign.go b/tagalign.go index cf441a8..4734b56 100644 --- a/tagalign.go +++ b/tagalign.go @@ -221,7 +221,7 @@ func (w *Helper) Process(pass *analysis.Pass) { //nolint:gocognit if err != nil { // if tag value is not a valid string, report it directly w.report(pass, field, column, errTagValueSyntax, field.Tag.Value) - fields = append(fields[:i], fields[i+1:]...) + fields = removeField(fields, i) continue } @@ -229,7 +229,7 @@ func (w *Helper) Process(pass *analysis.Pass) { //nolint:gocognit if err != nil { // if tag value is not a valid struct tag, report it directly w.report(pass, field, column, err.Error(), field.Tag.Value) - fields = append(fields[:i], fields[i+1:]...) + fields = removeField(fields, i) continue } @@ -449,3 +449,11 @@ func max(a, b int) int { } return b } + +func removeField(fields []*ast.Field, index int) []*ast.Field { + if index < 0 || index >= len(fields) { + return fields + } + + return append(fields[:index], fields[index+1:]...) +} diff --git a/testdata/bad_syntax_tag/example.go b/testdata/bad_syntax_tag/example.go index bbbcd27..1422449 100644 --- a/testdata/bad_syntax_tag/example.go +++ b/testdata/bad_syntax_tag/example.go @@ -10,8 +10,8 @@ type FooBar struct { type FooBar2 struct { Foo int `json:"foo" validate:"required"` - Bar string `json:bar` // want `bad syntax for struct tag value` - - FooFoo int8 `json:"foo_foo"` - BarBar int `json:"bar_bar" validate:"required"` + FooFoo int8 `json:"foo_foo"` + BarBar int `json:"bar_bar" validate:"required"` + XXX int `json:"xxx" validate:"required"` + Bar string `json:bar` // want `bad syntax for struct tag value` }