Skip to content

Commit

Permalink
fix: embedded types false positive (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
tmzane committed Feb 4, 2023
1 parent fd5338f commit 9229084
Show file tree
Hide file tree
Showing 2 changed files with 84 additions and 1 deletion.
6 changes: 5 additions & 1 deletion musttag.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,11 @@ func checkStruct(s *types.Struct, tag string, pos *token.Pos) (ok bool) {

st := reflect.StructTag(s.Tag(i))
if _, ok := st.Lookup(tag); !ok {
return false
// it's ok for embedded types not to be tagged,
// see https://github.com/junk1tm/musttag/issues/12
if !s.Field(i).Embedded() {
return false
}
}

// check if the field is a nested struct.
Expand Down
79 changes: 79 additions & 0 deletions testdata/src/tests/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,85 @@ func nestedAnonymousType() {
custom.Unmarshal(nil, &x)
}

// embedded types should not be reported.
func embeddedType() {
type Y struct { /* want
`\Qjson.Marshal`
`\Qjson.MarshalIndent`
`\Qjson.Unmarshal`
`\Qjson.Encoder.Encode`
`\Qjson.Decoder.Decode`
`\Qxml.Marshal`
`\Qxml.MarshalIndent`
`\Qxml.Unmarshal`
`\Qxml.Encoder.Encode`
`\Qxml.Decoder.Decode`
`\Qxml.Encoder.EncodeElement`
`\Qxml.Decoder.DecodeElement`
`\Qyaml.v3.Marshal`
`\Qyaml.v3.Unmarshal`
`\Qyaml.v3.Encoder.Encode`
`\Qyaml.v3.Decoder.Decode`
`\Qtoml.Unmarshal`
`\Qtoml.Decode`
`\Qtoml.DecodeFS`
`\Qtoml.DecodeFile`
`\Qtoml.Encoder.Encode`
`\Qtoml.Decoder.Decode`
`\Qmapstructure.Decode`
`\Qmapstructure.DecodeMetadata`
`\Qmapstructure.WeakDecode`
`\Qmapstructure.WeakDecodeMetadata`
`\Qcustom.Marshal`
`\Qcustom.Unmarshal` */
NoTag int
}

var x struct {
Y
Z int `json:"z" xml:"z" yaml:"z" toml:"z" mapstructure:"z" custom:"z"`
}

json.Marshal(x)
json.MarshalIndent(x, "", "")
json.Unmarshal(nil, &x)
json.NewEncoder(nil).Encode(x)
json.NewDecoder(nil).Decode(&x)

xml.Marshal(x)
xml.MarshalIndent(x, "", "")
xml.Unmarshal(nil, &x)
xml.NewEncoder(nil).Encode(x)
xml.NewDecoder(nil).Decode(&x)
xml.NewEncoder(nil).EncodeElement(x, xmlSE)
xml.NewDecoder(nil).DecodeElement(&x, &xmlSE)

yaml.Marshal(x)
yaml.Unmarshal(nil, &x)
yaml.NewEncoder(nil).Encode(x)
yaml.NewDecoder(nil).Decode(&x)

toml.Unmarshal(nil, &x)
toml.Decode("", &x)
toml.DecodeFS(nil, "", &x)
toml.DecodeFile("", &x)
toml.NewEncoder(nil).Encode(x)
toml.NewDecoder(nil).Decode(&x)

mapstructure.Decode(nil, &x)
mapstructure.DecodeMetadata(nil, &x, nil)
mapstructure.WeakDecode(nil, &x)
mapstructure.WeakDecodeMetadata(nil, &x, nil)

custom.Marshal(x)
custom.Unmarshal(nil, &x)
}

// all good, nothing to report.
func typeWithAllTags() {
var x struct {
Expand Down

0 comments on commit 9229084

Please sign in to comment.