https://github.com/palantir/goastwriter
Go library for writing Go source code programatically
https://github.com/palantir/goastwriter
octo-correct-managed
Last synced: 2 months ago
JSON representation
Go library for writing Go source code programatically
- Host: GitHub
- URL: https://github.com/palantir/goastwriter
- Owner: palantir
- License: bsd-3-clause
- Created: 2017-03-31T01:52:15.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2025-03-06T17:00:16.000Z (3 months ago)
- Last Synced: 2025-03-24T11:45:21.200Z (3 months ago)
- Topics: octo-correct-managed
- Language: Go
- Homepage:
- Size: 663 KB
- Stars: 34
- Watchers: 258
- Forks: 6
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: changelog/0.0.1/pr-34.v2.yml
- License: LICENSE
Awesome Lists containing this project
README
goastwriter 👻✍️
================
[](http://godoc.org/github.com/palantir/goastwriter)`goastwriter` is a library that offers abstractions for defining and writing Go source files
programmatically. It is effectively a convenience wrapper for the structs and functions defined in
the `go/ast` package. However, by providing higher-level abstractions, convenience functions and
tests, `goastwriter` makes writing Go code programatically much simpler for simple use cases.`goastwriter` processes its generated code using `gofmt`, so its output is `gofmt`-compliant.
Usage
-----
`goastwriter.Write` is the primary function exported by the package and generates the code for a
single Go file. It is provided with the package name that should be used for the file and the
components that make up the file.Example
-------
Code for generating a Go source file:```go
out, _ := goastwriter.Write("testpkg",
decl.NewImports(map[string]string{
"fmt": "",
"go/format": "gofmt",
}),
&decl.Struct{
Name: "Foo",
Comment: "Foo is a struct",
Fields: []decl.StructField{
{
Name: "Bar",
Type: expression.StringType,
Comment: "Bar is a field",
},
{
Name: "baz",
Type: expression.BoolType.Pointer(),
Comment: "Baz is a field",
},
},
},
&decl.Function{
Name: "Bar",
Params: []*decl.FuncParam{
decl.NewFuncParam("input", expression.Type("Foo").Pointer()),
},
ReturnTypes: []expression.Type{
expression.Type("Foo").Pointer(),
expression.ErrorType,
},
Body: []astgen.ASTStmt{
&statement.Expression{
Expr: expression.NewCallFunction("fmt", "Println"),
},
&statement.Expression{
Expr: expression.NewCallFunction("gofmt", "Source", expression.Nil),
},
&statement.Return{
Values: []astgen.ASTExpr{
expression.VariableVal("input"),
expression.Nil,
},
},
},
},
)
fmt.Println(string(out))
```Output:
```go
package testpkgimport (
"fmt"
gofmt "go/format"
)// Foo is a struct
type Foo struct {
// Bar is a field
Bar string
// Baz is a field
baz *bool
}func Bar(input *Foo) (*Foo, error) {
fmt.Println()
gofmt.Source(nil)
return input, nil
}
```