Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: map errors from formatting generated files back to their locations in the templ file #737

Merged
merged 14 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion cmd/templ/generatecmd/eventhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"crypto/sha256"
"fmt"
"go/format"
"go/scanner"
"go/token"
"log/slog"
"os"
"path"
Expand Down Expand Up @@ -221,7 +223,12 @@ func (h *FSEventHandler) generate(ctx context.Context, fileName string) (goUpdat

formattedGoCode, err := format.Source(b.Bytes())
if err != nil {
return false, false, nil, fmt.Errorf("%s source formatting error: %w", fileName, err)
mapped, ok := mapFormatterError(err, sourceMap, fileName, targetFileName)
if !ok {
return false, false, nil, fmt.Errorf("generated file %s contains source formatting error %w", targetFileName, err)
}

return false, false, nil, mapped
}

// Hash output, and write out the file if the goCodeHash has changed.
Expand Down Expand Up @@ -257,6 +264,43 @@ func (h *FSEventHandler) generate(ctx context.Context, fileName string) (goUpdat
return goUpdated, textUpdated, parsedDiagnostics, err
}

// Takes an error from the formatter and attempts to convert the positions reported in the target file to their positions
// in the source file.
func mapFormatterError(err error, sourceMap *parser.SourceMap, fileName string, targetFileName string) (error, bool) {
list, ok := err.(scanner.ErrorList)
if !ok {
return nil, false
}
list.Sort()

mapped := scanner.ErrorList{}

for _, e := range list {
// The positions in the source map are off by one line because of the package.
srcPos, ok := sourceMap.SourcePositionFromTarget(uint32(e.Pos.Line-1), uint32(e.Pos.Column))

var mappedPos token.Position
if ok {
mappedPos = token.Position{
Filename: fileName,
Offset: int(srcPos.Index),
Line: int(srcPos.Line) + 1,
Column: int(srcPos.Col),
}
} else {
mappedPos = token.Position{
Filename: targetFileName,
Offset: e.Pos.Offset,
Line: e.Pos.Line,
Column: e.Pos.Column,
}
}
mapped.Add(mappedPos, e.Msg)
}

return mapped, true
}

func generateSourceMapVisualisation(ctx context.Context, templFileName, goFileName string, sourceMap *parser.SourceMap) error {
if err := ctx.Err(); err != nil {
return err
Expand Down
61 changes: 61 additions & 0 deletions cmd/templ/generatecmd/eventhandler_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package generatecmd

import (
"context"
"go/scanner"
"go/token"
"io"
"log/slog"
"testing"

"github.com/a-h/templ/generator"
)

func TestEventHandler(t *testing.T) {
tests := []struct {
name string
fileName string
errorPositions []token.Position
}{
{
name: "single error outputs location in srcFile",
fileName: "single_error.templ.error",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The .error suffix was necessary to prevent the test files from breaking the build because they would get pulled into any templ generate running from the root.

errorPositions: []token.Position{
{Filename: "single_error.templ.error", Offset: 41, Line: 3, Column: 20},
},
},
{
name: "multiple errors all output locations in srcFile",
fileName: "multiple_errors.templ.error",
errorPositions: []token.Position{
{Filename: "multiple_errors.templ.error", Offset: 36, Line: 3, Column: 15},
{Filename: "multiple_errors.templ.error", Offset: 96, Line: 7, Column: 22},
},
},
}

slog := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{}))
fseh := NewFSEventHandler(slog, ".", false, []generator.GenerateOpt{}, false, false, true)
for _, test := range tests {
_, _, _, err := fseh.generate(context.Background(), test.fileName)
if err == nil {
t.Errorf("No error was thrown for file %s", test.fileName)
}

list, ok := err.(scanner.ErrorList)
if !ok {
t.Errorf("Error is not of type scanner.ErrorList")
}

if len(list) != len(test.errorPositions) {
t.Errorf("Expected %d errors but got %d", len(test.errorPositions), len(list))
}

for i, err := range list {
if err.Pos != test.errorPositions[i] {
t.Errorf("Got error %s at pos %v, expected this error at pos %v", err.Msg, err.Pos, test.errorPositions[i])
}
}

}
}
9 changes: 9 additions & 0 deletions cmd/templ/generatecmd/multiple_errors.templ.error
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package generatecmd

func invalid(a: string) string {
return "foo"
}

templ multipleError(a: string) {
<div/>
}
5 changes: 5 additions & 0 deletions cmd/templ/generatecmd/single_error.templ.error
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package generatecmd

templ singleError(a: string) {
<div/>
}