1
0
2025-01-25 16:11:19 -05:00

95 lines
1.6 KiB
Go

package main
import (
`errors`
`go/ast`
`go/token`
`log`
`strings`
`github.com/oriser/regroup`
)
/*
getParamSpec takes an ast.Decl d and returns a slice of
ParamConst found in it.
If no ParamConst are found, foundParams will be nil.
*/
func getValueSpec(d ast.Decl) (foundParams []*ParamConst) {
var ok bool
var idx int
var gd *ast.GenDecl
var spec ast.Spec
var vs *ast.ValueSpec
var vsId *ast.Ident
var nm *ast.Ident
var bl *ast.BasicLit
if gd, ok = d.(*ast.GenDecl); !ok || gd.Tok != token.CONST {
return
}
for _, spec = range gd.Specs {
if vs, ok = spec.(*ast.ValueSpec); !ok {
continue
}
if vs.Type != nil {
if vsId, ok = vs.Type.(*ast.Ident); !ok || vsId.Name != matchType {
continue
}
}
for idx, nm = range vs.Names {
if !strings.HasPrefix(nm.Name, pfx) {
continue
}
if bl, ok = vs.Values[idx].(*ast.BasicLit); !ok {
continue
}
foundParams = append(
foundParams,
&ParamConst{
ConstName: nm.Name,
// UriParamName: bl.Value,
UriParamName: stripQuotes(bl.Value),
},
)
}
}
return
}
/*
stripQuotes removes Golang-AST defining quotes.
This probably doesn't work for multiline, but should be fine for our purposes.
*/
func stripQuotes(inStr string) (outStr string) {
var err error
var matches map[string]string
var nomchErr *regroup.NoMatchFoundError = new(regroup.NoMatchFoundError)
outStr = inStr
if matches, err = stripQuotesPtrn.Groups(inStr); err != nil {
if errors.As(err, &nomchErr) {
err = nil
return
} else {
log.Panicln(err)
}
}
for _, v := range matches {
if v != "" {
outStr = v
return
}
}
return
}