-
Notifications
You must be signed in to change notification settings - Fork 31
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
79 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
"reflect" | ||
"strings" | ||
|
||
configv1a1 "github.com/kubewharf/katalyst-api/pkg/apis/config/v1alpha1" | ||
"k8s.io/apimachinery/pkg/runtime" | ||
) | ||
|
||
func main() { | ||
scheme := runtime.NewScheme() | ||
configv1a1.AddToScheme(scheme) | ||
|
||
var errs []error | ||
for _, typ := range scheme.AllKnownTypes() { | ||
checkType(typ, typ.Name(), &errs) | ||
} | ||
|
||
for _, err := range errs { | ||
fmt.Println(err) | ||
} | ||
} | ||
|
||
func parseTag(tag string) (name string) { | ||
if idx := strings.Index(tag, ","); idx != -1 { | ||
return tag[:idx] | ||
} else { | ||
return tag | ||
} | ||
} | ||
|
||
// typ must be a struct type | ||
func checkType(typ reflect.Type, path string, errs *[]error) { | ||
for i := 0; i < typ.NumField(); i++ { | ||
field := typ.Field(i) | ||
if !field.IsExported() { | ||
continue | ||
} | ||
fieldTyp := field.Type | ||
origFieldTyp := fieldTyp | ||
|
||
if fieldTyp.Kind() == reflect.Ptr || | ||
fieldTyp.Kind() == reflect.Slice || | ||
fieldTyp.Kind() == reflect.Array || | ||
fieldTyp.Kind() == reflect.Map { | ||
fieldTyp = fieldTyp.Elem() | ||
} | ||
if fieldTyp.Kind() != reflect.Struct { | ||
continue | ||
} | ||
|
||
var newPath string | ||
switch origFieldTyp.Kind() { | ||
case reflect.Struct, reflect.Ptr: | ||
newPath = fmt.Sprintf("%s.%s", path, field.Name) | ||
case reflect.Array, reflect.Slice: | ||
newPath = fmt.Sprintf("%s.%s[0]", path, field.Name) | ||
case reflect.Map: | ||
newPath = fmt.Sprintf("%s.%s[*]", path, field.Name) | ||
default: | ||
continue | ||
} | ||
|
||
tag := field.Tag.Get("json") | ||
name := parseTag(tag) | ||
if name == "" && !field.Anonymous { | ||
*errs = append( | ||
*errs, | ||
fmt.Errorf("field %s has no json tag and is not embedded, will cause unpredictable deserialization", newPath), | ||
) | ||
} | ||
checkType(fieldTyp, newPath, errs) | ||
} | ||
} |