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
+5.9k Golang : Extract unicode string from another unicode string example
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+5.5k Clean up Visual Studio For Mac installation failed disk full problem
+17.2k Golang : Find file size(disk usage) with filepath.Walk
+17.7k Golang : Read data from config file and assign to variables
+12.3k Golang : Display list of countries and ISO codes
+10k Golang : Get escape characters \u form from unicode characters
+9.4k Golang : Web(Javascript) to server-side websocket example
+5.6k Golang : Shortening import identifier
+16.9k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+20.9k Golang : Convert PNG transparent background image to JPG or JPEG image
+20.2k Golang : Reset or rewind io.Reader or io.Writer