https://github.com/nick-jones/astpath
XPath query over Go ASTs
https://github.com/nick-jones/astpath
ast go-ast golang golang-ast xpath xpath-query
Last synced: 4 months ago
JSON representation
XPath query over Go ASTs
- Host: GitHub
- URL: https://github.com/nick-jones/astpath
- Owner: nick-jones
- License: mit
- Created: 2020-06-12T18:42:53.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2020-06-17T18:25:42.000Z (about 6 years ago)
- Last Synced: 2024-06-20T05:15:12.305Z (about 2 years ago)
- Topics: ast, go-ast, golang, golang-ast, xpath, xpath-query
- Language: Go
- Homepage:
- Size: 27.3 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# astpath
Quick hack that provides XPath querying over Go ASTs. Inspired by [hchasestevens/astpath](https://github.com/hchasestevens/astpath)
for Python.
## Installing
```
GO111MODULE=on go get github.com/nick-jones/astpath
```
## Usage
```
astpath
```
The file path can be a directory, in which case all files in that directly are checked recursively.
## Examples
Taking a basic and crude example:
```go
package test
import (
"log"
"strings"
)
func repeatConditional(str string, count int, fn func(string) bool) string {
if fn(str) {
log.Println("hit!")
return strings.Repeat(str, count)
}
log.Printf("str = %s", str)
return str
}
```
To view the raw XML output for a single file:
```
$ astpath --template='{{.XML}}' '/File' test.go | xmllint --format - | xmllint --format -
```
```xml
```
Extract import paths:
```
$ astpath '//ImportSpec' test.go
test.go:4:2 > "log"
test.go:5:2 > "strings"
```
... or
```
$ astpath --template='{{.XMLInner}}' '//ImportSpec/BasicLit/@value' test.go
log
strings
```
Locate `log.*` function calls:
```
$ astpath '//CallExpr/SelectorExpr[./Ident[1]/@name="log"]' test.go
test.go:10:3 > log.Println
test.go:13:2 > log.Printf
```
Locate `log.Printf` function calls:
```
$ astpath '//CallExpr/SelectorExpr[./Ident[1]/@name="log"][./Ident[2]/@name="Printf"]' test.go
test.go:13:2 > log.Printf
```