From bc864947bda3f1521b61bc5366a054dabb4f3da0 Mon Sep 17 00:00:00 2001 From: joerdav Date: Thu, 30 May 2024 16:31:27 +0100 Subject: [PATCH] fix: format single line raw go code --- parser/v2/format_test.go | 6 ++++++ parser/v2/formattestdata/raw_go_is_formatted.txt | 12 ++++++++++++ parser/v2/types.go | 12 ++++++------ 3 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 parser/v2/formattestdata/raw_go_is_formatted.txt diff --git a/parser/v2/format_test.go b/parser/v2/format_test.go index 3c6ee1eb2..bd96a3e07 100644 --- a/parser/v2/format_test.go +++ b/parser/v2/format_test.go @@ -5,11 +5,17 @@ import ( "path/filepath" "testing" + "github.com/a-h/templ/cfg" "github.com/google/go-cmp/cmp" "golang.org/x/tools/txtar" ) func TestFormatting(t *testing.T) { + oldFlags := cfg.Experiment + t.Cleanup(func() { + cfg.Experiment = oldFlags + }) + cfg.Experiment.RawGo = true files, _ := filepath.Glob("formattestdata/*.txt") if len(files) == 0 { t.Errorf("no test files found") diff --git a/parser/v2/formattestdata/raw_go_is_formatted.txt b/parser/v2/formattestdata/raw_go_is_formatted.txt new file mode 100644 index 000000000..3209bd630 --- /dev/null +++ b/parser/v2/formattestdata/raw_go_is_formatted.txt @@ -0,0 +1,12 @@ +-- in -- +package test + +templ nameList(items []Item) { + {{ first := items[0] }} +} +-- out -- +package test + +templ nameList(items []Item) { + {{ first := items[0] }} +} diff --git a/parser/v2/types.go b/parser/v2/types.go index 12c305c77..02a437d36 100644 --- a/parser/v2/types.go +++ b/parser/v2/types.go @@ -1136,14 +1136,14 @@ func (gc GoCode) Write(w io.Writer, indent int) error { if isWhitespace(gc.Expression.Value) { gc.Expression.Value = "" } - if !gc.Multiline { - return writeIndent(w, indent, `{{ `, gc.Expression.Value, ` }}`) - } - formatted, err := format.Source([]byte(gc.Expression.Value)) + source, err := format.Source([]byte(gc.Expression.Value)) if err != nil { - return err + source = []byte(gc.Expression.Value) + } + if !gc.Multiline { + return writeIndent(w, indent, `{{ `, string(source), ` }}`) } - if err := writeIndent(w, indent, "{{"+string(formatted)+"\n"); err != nil { + if err := writeIndent(w, indent, "{{"+string(source)+"\n"); err != nil { return err } return writeIndent(w, indent, "}}")