Golang go/ast.FilterPackage() function example
package go/ast
FilterPackage trims the AST for a Go package in place by removing all names from top-level declarations (including struct field and interface method names, but not from parameter lists) that don't pass through the filter f. If the declaration is empty afterwards, the declaration is removed from the AST. The pkg.Files list is not changed, so that file names and top-level package comments don't get lost.
FilterPackage returns true if there are any top-level declarations left after filtering; it returns false otherwise.
Golang go/ast.FilterPackage() function usage
func makeRx(names []string) (*regexp.Regexp, error) {
if len(names) == 0 {
return nil, fmt.Errorf("no expression provided")
}
s := ""
for i, name := range names {
if i > 0 {
s += "|"
}
if isRegexp(name) {
s += name
} else {
s += "^" + name + "$" // must match exactly
}
}
return regexp.Compile(s)
}
func main() {
var astFile *ast.File
var dirname string
...
pkgName := astFile.Name.Name
if pkgName == "main" {
return
}
pkgPath := strings.TrimPrefix(strings.TrimPrefix(dirname, "/src/"), "pkg/")
astPkg := ast.Package{
Name: pkgName,
Files: map[string]*ast.File{
filename: astFile,
},
}
rx, _ := makeRx(args)
filter := func(s string) bool { return rx.MatchString(s) }
ast.FilterPackage(&astPkg, filter) // <-- here
...
}
References :
https://github.com/fzipp/pythia/blob/master/third_party/go.tools/godoc/cmdline.go
Advertisement
Something interesting
Tutorials
+17.1k Golang : XML to JSON example
+14.6k Golang : How to get URL port?
+9.9k Golang : Check if user agent is a robot or crawler example
+14.5k Golang : Rename directory
+6.7k Golang : When to use make or new?
+5.4k Golang : Qt update UI elements with core.QCoreApplication_ProcessEvents
+9.2k Golang : Write multiple lines or divide string into multiple lines
+11.7k Golang : Calculations using complex numbers example
+5k Golang : Calculate a pip value and distance to target profit example
+12.8k Golang : http.Get example
+9.3k Golang : Generate random Chinese, Japanese, Korean and other runes
+11k Golang : Replace a parameter's value inside a configuration file example