Skip to content

Commit

Permalink
fix(generate): format using goimports
Browse files Browse the repository at this point in the history
this should make sure the imports are sorted
  • Loading branch information
crhntr committed Feb 2, 2025
1 parent 5ecf5d7 commit abfddf6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
2 changes: 1 addition & 1 deletion internal/muxt/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
18 changes: 18 additions & 0 deletions internal/source/go.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit abfddf6

Please sign in to comment.