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

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

Awesome Lists containing this project

README

          

[![GoDoc](https://godoc.org/github.com/xaionaro-go/gosrc?status.svg)](https://pkg.go.dev/github.com/xaionaro-go/gosrc?tab=doc)
[![go report](https://goreportcard.com/badge/github.com/xaionaro-go/gosrc)](https://goreportcard.com/report/github.com/xaionaro-go/gosrc)



CC0



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