github.com/mailru/activerecord@v1.12.2/internal/pkg/parser/mutator.go (about)

     1  package parser
     2  
     3  import (
     4  	"go/ast"
     5  	"strings"
     6  
     7  	"github.com/mailru/activerecord/internal/pkg/arerror"
     8  	"github.com/mailru/activerecord/internal/pkg/ds"
     9  )
    10  
    11  func ParseMutators(dst *ds.RecordPackage, fields []*ast.Field) error {
    12  	for _, field := range fields {
    13  		if field.Names == nil || len(field.Names) != 1 {
    14  			return &arerror.ErrParseMutatorDecl{Err: arerror.ErrNameDeclaration}
    15  		}
    16  
    17  		mutatorDeclaration := ds.MutatorDeclaration{
    18  			Name:       field.Names[0].Name,
    19  			ImportName: "mutator" + field.Names[0].Name,
    20  		}
    21  
    22  		tagParam, err := splitTag(field, NoCheckFlag, map[TagNameType]ParamValueRule{})
    23  		if err != nil {
    24  			return &arerror.ErrParseMutatorDecl{Name: mutatorDeclaration.Name, Err: err}
    25  		}
    26  
    27  		for _, kv := range tagParam {
    28  			switch kv[0] {
    29  			case "pkg":
    30  				mutatorDeclaration.Pkg = kv[1]
    31  			case "update":
    32  				mutatorDeclaration.Update = kv[1]
    33  			case "replace":
    34  				mutatorDeclaration.Replace = kv[1]
    35  			default:
    36  				return &arerror.ErrParseMutatorTagDecl{Name: mutatorDeclaration.Name, TagName: kv[0], TagValue: kv[1], Err: arerror.ErrParseTagUnknown}
    37  			}
    38  		}
    39  
    40  		if mutatorDeclaration.Pkg != "" {
    41  			imp, e := dst.FindOrAddImport(mutatorDeclaration.Pkg, mutatorDeclaration.ImportName)
    42  			if e != nil {
    43  				return &arerror.ErrParseMutatorDecl{Name: mutatorDeclaration.Name, Err: e}
    44  			}
    45  
    46  			mutatorDeclaration.ImportName = imp.ImportName
    47  		}
    48  
    49  		mutatorDeclaration.Type, err = ParseFieldType(dst, mutatorDeclaration.Name, "", field.Type)
    50  		if err != nil {
    51  			return &arerror.ErrParseMutatorDecl{Name: mutatorDeclaration.Name, Err: err}
    52  		}
    53  
    54  		// Ассоциируем указатель на тип с типом
    55  		structType := strings.Replace(mutatorDeclaration.Type, "*", "", 1)
    56  
    57  		mutatorDeclaration.PartialFields = dst.ImportStructFieldsMap[structType]
    58  
    59  		if err = dst.AddMutator(mutatorDeclaration); err != nil {
    60  			return err
    61  		}
    62  	}
    63  
    64  	return nil
    65  }