@ -3,19 +3,19 @@ package parser
import (
import (
"bufio"
"bufio"
"errors"
"errors"
"regexp"
"strings"
"strings"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
"github.com/tal-tech/go-zero/tools/goctl/api/spec"
)
)
// struct match
var emptyType spec . Type
const typeRegex = ` (?m)(?m)(^ *type\s+[a-zA-Z][a-zA-Z0-9_-]+\s+(((struct)\s*?\ { [\w\W]*?[^\ { ]\})|([a-zA-Z][a-zA-Z0-9_-]+)))|(^ *type\s*?\([\w\W]+\}\s*\)) `
var (
type ApiStruct struct {
emptyStrcut = errors . New ( "struct body not found" )
Info string
emptyType spec . Type
StructBody string
)
Service string
Imports string
}
func GetType ( api * spec . ApiSpec , t string ) spec . Type {
func GetType ( api * spec . ApiSpec , t string ) spec . Type {
for _ , tp := range api . Types {
for _ , tp := range api . Types {
@ -69,32 +69,56 @@ func unread(r *bufio.Reader) error {
return r . UnreadRune ( )
return r . UnreadRune ( )
}
}
func MatchStruct ( api string ) ( info , structBody , service string , err error ) {
func MatchStruct ( api string ) ( * ApiStruct , error ) {
r := regexp . MustCompile ( typeRegex )
var result ApiStruct
indexes := r . FindAllStringIndex ( api , - 1 )
scanner := bufio . NewScanner ( strings . NewReader ( api ) )
if len ( indexes ) == 0 {
var parseInfo = false
return "" , "" , "" , emptyStrcut
var parseImport = false
}
var parseType = false
startIndexes := indexes [ 0 ]
var parseSevice = false
endIndexes := indexes [ len ( indexes ) - 1 ]
var segment string
for scanner . Scan ( ) {
line := strings . TrimSpace ( scanner . Text ( ) )
info = api [ : startIndexes [ 0 ] ]
if line == "@doc(" {
structBody = api [ startIndexes [ 0 ] : endIndexes [ len ( endIndexes ) - 1 ] ]
parseInfo = true
service = api [ endIndexes [ len ( endIndexes ) - 1 ] : ]
}
if line == ")" && parseInfo {
parseInfo = false
result . Info = segment + ")"
segment = ""
continue
}
firstIIndex := strings . Index ( info , "i" )
if strings . HasPrefix ( line , "import" ) {
if firstIIndex > 0 {
parseImport = true
info = info [ firstIIndex : ]
}
if parseImport && ( strings . HasPrefix ( line , "type" ) || strings . HasPrefix ( line , "@server" ) ||
strings . HasPrefix ( line , "service" ) ) {
parseImport = false
result . Imports = segment
segment = line + "\n"
continue
}
}
lastServiceRightBraceIndex := strings . LastIndex ( service , "}" ) + 1
if strings . HasPrefix ( line , "type" ) {
var firstServiceIndex int
parseType = true
for index , char := range service {
}
if ! isSpace ( char ) && ! isNewline ( char ) {
if strings . HasPrefix ( line , "@server" ) || strings . HasPrefix ( line , "service" ) {
firstServiceIndex = index
if parseType {
break
parseType = false
result . StructBody = segment
segment = line + "\n"
continue
}
parseSevice = true
}
}
segment += scanner . Text ( ) + "\n"
}
if ! parseSevice {
return nil , errors . New ( "no service defined" )
}
}
service = service [ firstServiceIndex : lastServiceRightBraceIndex ]
result. Service = segment
return
return & result , nil
}
}