github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/cmd/internal/name/exec.go (about)

     1  package name
     2  
     3  import (
     4  	"github.com/iancoleman/strcase"
     5  	"github.com/pkg/errors"
     6  	"github.com/unionj-cloud/go-doudou/cmd/internal/astutils"
     7  	"github.com/unionj-cloud/go-doudou/toolkit/stringutils"
     8  )
     9  
    10  // Name wraps config properties for name command
    11  type Name struct {
    12  	File      string
    13  	Strategy  string
    14  	Omitempty bool
    15  	Form      bool
    16  }
    17  
    18  const (
    19  	lowerCamelStrategy = "lowerCamel"
    20  	snakeStrategy      = "snake"
    21  )
    22  
    23  // Exec rewrites the json tag of each field of all structs in the file as snake case or lower camel case.
    24  // Unexported or ignored fields will be skipped.
    25  func (receiver Name) Exec() {
    26  	if stringutils.IsEmpty(receiver.File) {
    27  		panic(errors.New("file flag should not be empty"))
    28  	}
    29  
    30  	var convert func(string) string
    31  	switch receiver.Strategy {
    32  	case lowerCamelStrategy:
    33  		convert = strcase.ToLowerCamel
    34  	case snakeStrategy:
    35  		convert = strcase.ToSnake
    36  	default:
    37  		panic(errors.New(`unknown strategy. currently only support "lowerCamel" and "snake"`))
    38  	}
    39  
    40  	newcode, err := astutils.RewriteTag(astutils.RewriteTagConfig{
    41  		File:        receiver.File,
    42  		Omitempty:   receiver.Omitempty,
    43  		ConvertFunc: convert,
    44  		Form:        receiver.Form,
    45  	})
    46  	if err != nil {
    47  		panic(err)
    48  	}
    49  	astutils.FixImport([]byte(newcode), receiver.File)
    50  }