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
+12.4k Golang : Extract part of string with regular expression
+19.4k Golang : Fix cannot download, $GOPATH not set error
+12.3k Golang : Validate email address
+6k Javascript : Get operating system and browser information
+7.7k Golang : Test if an input is an Armstrong number example
+7.9k Golang : Gomobile init produce "iphoneos" cannot be located error
+9.5k Golang : Changing a RGBA image number of channels with OpenCV
+20.5k nginx: [emerg] unknown directive "passenger_enabled"
+9.6k Golang : Copy map(hash table) example
+9k Golang : Get SPF and DMARC from email headers to fight spam
+7.5k Golang : Create zip/ePub file without compression(use Store algorithm)
+10.6k Golang : Select region of interest with mouse click and crop from image