From abfddf6f66e1f7bf16c5bd934cd1815a05ae3adf Mon Sep 17 00:00:00 2001 From: Chrstopher Hunter <8398225+crhntr@users.noreply.github.com> Date: Sun, 2 Feb 2025 11:54:23 -0800 Subject: [PATCH] fix(generate): format using goimports this should make sure the imports are sorted --- internal/muxt/routes.go | 2 +- internal/source/go.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/internal/muxt/routes.go b/internal/muxt/routes.go index 8fd2582..388dd32 100644 --- a/internal/muxt/routes.go +++ b/internal/muxt/routes.go @@ -242,7 +242,7 @@ func TemplateRoutesFile(wd string, logger *log.Logger, config RoutesFileConfigur file.Decls = append(file.Decls, executeFuncDecl(imports, config.TemplatesVariable)) } - return source.Format(file), nil + return source.FormatFile(filepath.Join(wd, DefaultOutputFileName), file) } func appendParseArgumentStatements(statements []ast.Stmt, t Template, imports *source.Imports, sigs map[string]*types.Signature, parsed map[string]struct{}, receiver *types.Named, call *ast.CallExpr) ([]ast.Stmt, error) { diff --git a/internal/source/go.go b/internal/source/go.go index 1de403c..7df2aa8 100644 --- a/internal/source/go.go +++ b/internal/source/go.go @@ -10,6 +10,8 @@ import ( "net/http" "strconv" "strings" + + "golang.org/x/tools/imports" ) func IterateGenDecl(files []*ast.File, tok token.Token) func(func(*ast.File, *ast.GenDecl) bool) { @@ -40,6 +42,22 @@ func IterateValueSpecs(files []*ast.File) func(func(*ast.File, *ast.ValueSpec) b } } +func FormatFile(filePath string, node ast.Node) (string, error) { + var buf bytes.Buffer + if err := printer.Fprint(&buf, token.NewFileSet(), node); err != nil { + return "", fmt.Errorf("formatting error: %v", err) + } + out, err := imports.Process(filePath, buf.Bytes(), &imports.Options{ + Fragment: true, + AllErrors: true, + Comments: true, + }) + if err != nil { + return "", fmt.Errorf("formatting error: %v", err) + } + return string(bytes.ReplaceAll(out, []byte("\n}\nfunc "), []byte("\n}\n\nfunc "))), nil +} + func Format(node ast.Node) string { var buf bytes.Buffer if err := printer.Fprint(&buf, token.NewFileSet(), node); err != nil {