Skip to content
This repository has been archived by the owner. It is now read-only.
Go tool to walk & rewrite AST
Go
Branch: master
Clone or download
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Create FUNDING.yml May 27, 2019
.travis.yml Add travis support Jan 10, 2017
LICENSE Create LICENSE Jul 30, 2018
README.md Archive for a better package Dec 7, 2019
astrewrite.go Initial commit Jan 10, 2017
astrewrite_example_test.go Change example function so godoc picks it Jan 10, 2017

README.md

This project is archived and not maintained. There is a better implementation and solution in the golang.org/x/tools/go/ast/astutil package that you can use.

astrewrite GoDoc Build Status

astrewrite provides a Walk() function, similar to ast.Inspect() from the ast package. The only difference is that the passed walk function can also return a node, which is used to rewrite the parent node. This provides an easy way to rewrite a given ast.Node while walking the AST.

Example

package main

import (
	"bytes"
	"fmt"
	"go/ast"
	"go/parser"
	"go/printer"
	"go/token"

	"github.com/fatih/astrewrite"
)

func main() {
	src := `package main

type Foo struct{}`

	fset := token.NewFileSet()
	file, err := parser.ParseFile(fset, "foo.go", src, parser.ParseComments)
	if err != nil {
		panic(err)
	}

	rewriteFunc := func(n ast.Node) (ast.Node, bool) {
		x, ok := n.(*ast.TypeSpec)
		if !ok {
			return n, true
		}

		// change struct type name to "Bar"
		x.Name.Name = "Bar"
		return x, true
	}

	rewritten := astrewrite.Walk(file, rewriteFunc)

	var buf bytes.Buffer
	printer.Fprint(&buf, fset, rewritten)
	fmt.Println(buf.String())
	// Output:
	// package main
	//
	// type Bar struct{}
}
You can’t perform that action at this time.