astpatch

package
v0.1.12 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 5, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package astpatch is the shared AST helper that powers gofasta's modify-aware generators: g method, g field, g endpoint, g middleware, g repo-method, g relation, g rename.

Why dst over stdlib go/ast: dst (decorated syntax tree) preserves comment attachments and blank lines through the parse → modify → print round-trip. Stdlib go/ast loses that information, so a "modify one method" edit ends up reformatting the whole file in a way that makes the diff unreadable.

The helpers in this package are intentionally small and composable — each generator owns its own template fragment of "new code to insert," while astpatch handles the surgery (find the target, splice in the new node, write back, gofmt).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendFuncDecl

func AppendFuncDecl(f *File, declSrc string) error

AppendFuncDecl parses declSrc (a complete top-level function with body) and appends it to the file's declarations.

func AppendInterfaceMethod

func AppendInterfaceMethod(it *dst.InterfaceType, methodSrc string) error

AppendInterfaceMethod parses methodSrc as one interface method (e.g.

"Archive(ctx context.Context, id uuid.UUID) error"

) and appends it to the interface. Returns CodeASTPatchFailed if the fragment doesn't parse as a valid method signature.

func AppendKeyValueToCompositeLit

func AppendKeyValueToCompositeLit(lit *dst.CompositeLit, key, exprSrc string) error

AppendKeyValueToCompositeLit parses exprSrc and appends `key: <expr>,` to lit on its own line.

func AppendStringToCompositeLit

func AppendStringToCompositeLit(lit *dst.CompositeLit, val string)

AppendStringToCompositeLit appends the quoted string element val to lit on its own line.

func AppendStructField

func AppendStructField(st *dst.StructType, fieldSrc string) error

AppendStructField parses fieldSrc and appends it to the struct. Field source is a single line like:

"Archived bool `gorm:\"not null;default:false\"`"

Tags should be backtick-quoted exactly as they would appear in source.

func CompositeLitHasKey

func CompositeLitHasKey(lit *dst.CompositeLit, key string) bool

CompositeLitHasKey reports whether lit already has a Key: value entry for the given key identifier.

func CompositeLitHasString

func CompositeLitHasString(lit *dst.CompositeLit, val string) bool

CompositeLitHasString reports whether lit contains the quoted string element val (e.g. an allowlist already carrying "sku").

func EnsureImport

func EnsureImport(f *File, importPath string) bool

EnsureImport adds an import to the file if it isn't already present. Returns true when an import was added (the caller may then mark a patch action accordingly).

func FindFunc

func FindFunc(f *File, recv, name string) (*dst.FuncDecl, error)

FindFunc returns the top-level (or method) function declaration matching recv + name. Pass "" for recv to match a package-level function.

func FindInterface

func FindInterface(f *File, name string) (*dst.InterfaceType, error)

FindInterface walks decls looking for an interface declaration named name. Returns CodeASTPatchFailed when the file has no such declaration.

func FindStruct

func FindStruct(f *File, name string) (*dst.StructType, error)

FindStruct walks decls looking for a struct type declaration. Mirror of FindInterface for the modify-aware field-add generator.

func FindVarCompositeLit

func FindVarCompositeLit(f *File, name string) (*dst.CompositeLit, error)

FindVarCompositeLit locates a package-level `var <name> = T{...}` declaration and returns its composite literal. Powers the allowlist patches (`<lower>SortColumns`, `<lower>FilterColumns`).

func FirstCompositeLitInFunc

func FirstCompositeLitInFunc(fn *dst.FuncDecl) (*dst.CompositeLit, error)

FirstCompositeLitInFunc returns the first composite literal in fn's body in source order. The scaffold's mapper functions (FromModel, ToCreateInput, ToPatch, ToFilter, the test fixture builders) each build exactly one struct literal, and it is the first composite in the body — which makes "first" a stable anchor for field insertion.

func FuncContainsStringLit

func FuncContainsStringLit(fn *dst.FuncDecl, val string) bool

FuncContainsStringLit reports whether fn's body contains the string literal val anywhere. Used as the idempotency probe for statement insertions keyed on a column name (`out["sku"] = ...`).

func InsertStmtBeforeReturn

func InsertStmtBeforeReturn(fn *dst.FuncDecl, stmtSrc string) error

InsertStmtBeforeReturn parses stmtSrc (one or more statements) and inserts them immediately before the LAST top-level return in fn's body. Powers the AsMap / AsRepoFilter patches, whose shape is a run of `if p.X != nil { out["x"] = *p.X }` blocks followed by `return out`. Falls back to appending when the body has no return.

func InterfaceHasMethod

func InterfaceHasMethod(it *dst.InterfaceType, name string) bool

InterfaceHasMethod reports whether the interface already declares a method by this name. Used by the modify-aware generators as the idempotency check before appending.

func Render

func Render(f *File) ([]byte, error)

Render restores the dst.File to bytes and runs gofmt. Returns the rendered body without writing anywhere — useful for plan-mode previews and tests.

func StructHasField

func StructHasField(st *dst.StructType, name string) bool

StructHasField reports whether the struct already declares a field by this name (case-sensitive).

Types

type File

type File struct {
	Path string
	Dst  *dst.File
	Dec  *decorator.Decorator
}

File bundles a parsed dst.File with its decorator so callers can modify nodes and write back without re-parsing.

func Parse

func Parse(path string) (*File, error)

Parse reads path, parses it with dst, and returns the wrapper. Returns CodeASTParseFailed wrapped around the underlying error on syntax problems — the user gets a useful "the file has a syntax error" hint.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址