Skip to content

Commit

Permalink
chore(ci): add inlinecheck
Browse files Browse the repository at this point in the history
  • Loading branch information
gary-lgy committed Dec 10, 2024
1 parent e27d0d7 commit e49c408
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ jobs:
run: |
make fmt && git add pkg &&
git diff --cached --exit-code || (echo 'Please run "make fmt" to verify gofmt' && exit 1);
- name: Check inline fields
run: |
go run cmd/inlinecheck/main.go
76 changes: 76 additions & 0 deletions cmd/inlinecheck/main.go
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)
}
}

0 comments on commit e49c408

Please sign in to comment.