Skip to content

Commit

Permalink
optimize code and fix error offset in golangci-lint mode
Browse files Browse the repository at this point in the history
  • Loading branch information
4meepo committed Oct 19, 2023
1 parent 79876a7 commit 8a15bce
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 17 deletions.
24 changes: 9 additions & 15 deletions tagalign.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,25 +211,28 @@ func (w *Helper) Process(pass *analysis.Pass) { //nolint:gocognit
}
uniqueKeys = append(uniqueKeys, k)
}
mark := make(map[int]struct{})

for i, field := range fields {
for i := 0; i < len(fields); {
field := fields[i]
column := pass.Fset.Position(field.Tag.Pos()).Column - 1
offsets[i] = column

tag, err := strconv.Unquote(field.Tag.Value)
if err != nil {
mark[i] = struct{}{}
// 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:]...)
continue
}

tags, err := structtag.Parse(tag)
if err != nil {
mark[i] = struct{}{}
// 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:]...)
continue
}

offsets = append(offsets, column)
maxTagNum = max(maxTagNum, tags.Len())

if w.sort {
Expand All @@ -244,18 +247,9 @@ func (w *Helper) Process(pass *analysis.Pass) { //nolint:gocognit
addKey(t.Key)
}
tagsGroup = append(tagsGroup, tags.Tags())
}

offset := 0
for i := range fields {
if _, exist := mark[i]; exist {
continue
}

fields[offset] = fields[i]
offset++
i++
}
fields = fields[:offset]

if w.sort && StrictStyle == w.style {
sortAllKeys(w.fixedTagOrder, uniqueKeys)
Expand Down
4 changes: 2 additions & 2 deletions tagalign_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ func Test_alignSingleField(t *testing.T) {
analysistest.Run(t, unsort, a)
}

func Test_issues6(t *testing.T) {
func Test_badSyntaxTag(t *testing.T) {
// only align
a := NewAnalyzer()
unsort, err := filepath.Abs("testdata/issues6")
unsort, err := filepath.Abs("testdata/bad_syntax_tag")
assert.NoError(t, err)
analysistest.Run(t, unsort, a)
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,12 @@ type FooBar struct {
FooFoo int8 `json:"foo_foo" validate:"required"`
BarBar int `json:"bar_bar" validate:"required"`
}

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"`
}

0 comments on commit 8a15bce

Please sign in to comment.