An open API service indexing awesome lists of open source software.

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

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
```