diff --git a/tools/html-to-htmgo/internal/adapters/services/formatter/formatter.go b/tools/html-to-htmgo/internal/adapters/services/formatter/formatter.go index 295a0af..a33d98a 100644 --- a/tools/html-to-htmgo/internal/adapters/services/formatter/formatter.go +++ b/tools/html-to-htmgo/internal/adapters/services/formatter/formatter.go @@ -16,11 +16,11 @@ import ( func MyComponent() *h.Element { return ` + node.String() + ` }`) - dist, err := format.Source(b) + indented := Indent(string(b)) + dist, err := format.Source([]byte(indented)) if err != nil { return string(b) } - return string(dist) } diff --git a/tools/html-to-htmgo/internal/adapters/services/formatter/indent.go b/tools/html-to-htmgo/internal/adapters/services/formatter/indent.go new file mode 100644 index 0000000..f6e9b13 --- /dev/null +++ b/tools/html-to-htmgo/internal/adapters/services/formatter/indent.go @@ -0,0 +1,58 @@ +package formatter + +import ( + "bytes" + "fmt" + "go/ast" + "go/parser" + "go/printer" + "go/token" + "golang.org/x/tools/go/ast/astutil" + "strings" +) + +func Indent(input string) string { + fset := token.NewFileSet() + // Parse the code string into an AST + f, err := parser.ParseFile(fset, "", input, 0) + + if err != nil { + return input + } + + component := f.Decls[1].(*ast.FuncDecl) + + astutil.Apply(component.Body, nil, func(cursor *astutil.Cursor) bool { + switch n := cursor.Node().(type) { + case *ast.CallExpr: + newChildren := make([]ast.Expr, 0) + for i, arg := range n.Args { + if i == 0 { + switch arg.(type) { + // If the first argument is another node, add an indent + case *ast.CallExpr: + newChildren = append(newChildren, ast.NewIdent("INDENT")) + } + } + newChildren = append(newChildren, arg) + newChildren = append(newChildren, ast.NewIdent("INDENT")) + } + n.Args = newChildren + return true + } + return true + }) + + // Convert the AST node to a string + var buf bytes.Buffer + if err := printer.Fprint(&buf, fset, component); err != nil { + fmt.Println("Error printing AST:", err) + return input + } + + // Output the formatted code + indented := strings.ReplaceAll(buf.String(), "INDENT,", "\n\t\t") + indented = strings.ReplaceAll(indented, ", INDENT", ", \n\t\t") + + return indented +}