Skip to content

Commit

Permalink
bake: add function to print ast
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidGamba committed Feb 7, 2024
1 parent 8ad6dd1 commit c8a81cc
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 0 deletions.
88 changes: 88 additions & 0 deletions bake/ast.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@ import (
"go/parser"
"go/printer"
"go/token"
"strings"

"github.com/davecgh/go-spew/spew"
"golang.org/x/tools/go/packages"
)

Expand Down Expand Up @@ -59,3 +61,89 @@ func GetFuncDeclForPackage(dir string, m *map[string]FuncDecl) error {
}
return nil
}

func PrintAst(dir string) error {
cfg := &packages.Config{Mode: packages.NeedFiles | packages.NeedSyntax, Dir: dir}
pkgs, err := packages.Load(cfg, ".")
if err != nil {
return fmt.Errorf("failed to load packages: %w", err)
}
for _, pkg := range pkgs {
// Logger.Println(pkg.ID, pkg.GoFiles)
for _, file := range pkg.GoFiles {
// Logger.Printf("file: %s\n", file)
// parse file
fset := token.NewFileSet()
fset.AddFile(file, fset.Base(), len(file))
f, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
return fmt.Errorf("failed to parse file: %w", err)
}
// Iterate through every node in the file
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
// Check function declarations for exported functions
case *ast.FuncDecl:
if x.Name.IsExported() {
name := x.Name.Name
description := x.Doc.Text()
var buf bytes.Buffer
printer.Fprint(&buf, fset, x.Type)
Logger.Printf("file: %s, name: %s, desc: %s\n", file, name, strings.TrimSpace(description))
Logger.Printf("file: %s, name: %s, type: %s\n", file, name, buf.String())

// Check for Expressions of opt type
ast.Inspect(n, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.BlockStmt:
for i, stmt := range x.List {
Logger.Printf("i: %d\n", i)
Logger.Printf("stmt: %T\n", stmt)
// We are expecting the expression before the return function
_, ok := stmt.(*ast.ReturnStmt)
if ok {
return false
}
Logger.Printf("inspect stmt: %T\n", stmt)
exprStmt, ok := stmt.(*ast.ExprStmt)
if !ok {
continue
}
// spew.Dump(exprStmt)

// Check for CallExpr
ast.Inspect(exprStmt, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.CallExpr:
fun, ok := x.Fun.(*ast.SelectorExpr)
if !ok {
return false
}
xIdent, ok := fun.X.(*ast.Ident)
if !ok {
return false
}
xSel := fun.Sel.Name
Logger.Printf("X: %s %s\n", xIdent.Name, xSel)

// Check for args
for _, arg := range x.Args {
Logger.Printf("arg: %T\n", arg)
spew.Dump(arg)
}
return false
}
return true
})
}
}
return true
})
}
}
return true
})
}
}
return nil
}
1 change: 1 addition & 0 deletions bake/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/sys v0.7.0 // indirect
)
2 changes: 2 additions & 0 deletions bake/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ github.com/DavidGamba/dgtools/run v0.7.0 h1:ENTskNQvBM1/n/b42PxqJktU9EzQVqPZRGUB
github.com/DavidGamba/dgtools/run v0.7.0/go.mod h1:3P1fMJupTWqsiE8IXsXrk2HtgkZBTCFRLbaTjRlmDe0=
github.com/DavidGamba/go-getoptions v0.27.0 h1:hldKJSwO9SwvR+z9pe6ojhEcYECrRiO/bar9B7MnBKA=
github.com/DavidGamba/go-getoptions v0.27.0/go.mod h1:qLaLSYeQ8sUVOfKuu5JT5qKKS3OCwyhkYSJnoG+ggmo=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk=
golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
Expand Down
15 changes: 15 additions & 0 deletions bake/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ func program(args []string) int {
bld := b.NewCommand("list-descriptions", "lists descriptions")
bld.SetCommandFn(ListDescriptionsRun(bakefile))

bast := b.NewCommand("show-ast", "show ast")
bast.SetCommandFn(ShowASTRun(bakefile))

opt.HelpCommand("help", opt.Alias("?"))
remaining, err := opt.Parse(args[1:])
if err != nil {
Expand Down Expand Up @@ -166,3 +169,15 @@ func ListDescriptionsRun(bakefile string) getoptions.CommandFn {
return nil
}
}

func ShowASTRun(bakefile string) getoptions.CommandFn {
return func(ctx context.Context, opt *getoptions.GetOpt, args []string) error {
Logger.Printf("bakefile: %s\n", bakefile)
dir := filepath.Dir(bakefile)
err := PrintAst(dir)
if err != nil {
return fmt.Errorf("failed to inspect package: %w", err)
}
return nil
}
}

0 comments on commit c8a81cc

Please sign in to comment.