https://github.com/xaionaro-go/gosrc
Parse Go packages to handy structures (to save time on understanding `go/ast` and `go/types`).
https://github.com/xaionaro-go/gosrc
ast go golang parser
Last synced: 14 days ago
JSON representation
Parse Go packages to handy structures (to save time on understanding `go/ast` and `go/types`).
- Host: GitHub
- URL: https://github.com/xaionaro-go/gosrc
- Owner: xaionaro-go
- License: cc0-1.0
- Created: 2020-11-17T17:48:58.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-11-24T18:14:23.000Z (over 5 years ago)
- Last Synced: 2025-02-27T04:17:29.736Z (over 1 year ago)
- Topics: ast, go, golang, parser
- Language: Go
- Homepage:
- Size: 27.3 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://pkg.go.dev/github.com/xaionaro-go/gosrc?tab=doc)
[](https://goreportcard.com/report/github.com/xaionaro-go/gosrc)
To the extent possible under law,
Dmitrii Okunev
has waived all copyright and related or neighboring rights to
gosrc.
This work is published from:
Ireland.
# About
This package just simplifies working with `go/*` packages to parse a source code.
Initially the package was written to simplify code generation.
# Quick start
```go
package main
import (
"fmt"
"go/build"
"github.com/xaionaro-go/gosrc"
)
func assertNoError(err error) {
if err != nil {
panic(err)
}
}
func main() {
dir, err := gosrc.OpenDirectoryByPkgPath(&build.Default, "github.com/xaionaro-go/gosrc", false, false, false, nil)
assertNoError(err)
if len(dir.Packages) != 1 {
panic("expected one package")
}
pkg := dir.Packages[0]
for _, file := range pkg.Files {
for _, s := range file.Structs() {
fields, err := s.Fields()
assertNoError(err)
fmt.Println("amount of fields:", len(fields), ";\t amount of methods:", len(s.Methods()), "; \tstruct name:", s.Name())
}
}
}
```
The output is:
```
amount of fields: 2 ; amount of methods: 0 ; struct name: Directory
amount of fields: 2 ; amount of methods: 1 ; struct name: ErrPackageNotFound
amount of fields: 5 ; amount of methods: 7 ; struct name: Field
amount of fields: 2 ; amount of methods: 0 ; struct name: TypeNameValue
amount of fields: 3 ; amount of methods: 12 ; struct name: File
amount of fields: 1 ; amount of methods: 0 ; struct name: Func
amount of fields: 6 ; amount of methods: 5 ; struct name: Package
amount of fields: 3 ; amount of methods: 5 ; struct name: Struct
```