Skip to content

Commit

Permalink
feat: add staticcheck support for generated code
Browse files Browse the repository at this point in the history
  • Loading branch information
a-h committed Dec 1, 2021
1 parent e6023b1 commit 220fc80
Show file tree
Hide file tree
Showing 33 changed files with 60 additions and 69 deletions.
2 changes: 1 addition & 1 deletion cmd/templ/fmtcmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func Run(args []string) (err error) {
fmt.Printf("%s complete in %v\n", r.FileName, r.Duration)
successCount++
}
fmt.Printf("Formatted %d templates with %d errors in %s\n", successCount+errorCount, errorCount, time.Now().Sub(start))
fmt.Printf("Formatted %d templates with %d errors in %s\n", successCount+errorCount, errorCount, time.Since(start))
return
}

Expand Down
2 changes: 1 addition & 1 deletion cmd/templ/generatecmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func Run(args []string) (err error) {
successCount++
fmt.Printf("%s complete in %v\n", r.FileName, r.Duration)
}
fmt.Printf("Generated code for %d templates with %d errors in %s\n", successCount+errorCount, errorCount, time.Now().Sub(start))
fmt.Printf("Generated code for %d templates with %d errors in %s\n", successCount+errorCount, errorCount, time.Since(start))
return
}

Expand Down
2 changes: 0 additions & 2 deletions cmd/templ/lspcmd/changes.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ type documentContents struct {
log *zap.Logger
}

type documentEditor func(uri, prefix string, change lsp.TextDocumentContentChangeEvent) (requests []toClientRequest)

// Set the contents of a document.
func (fc *documentContents) Set(uri string, contents []byte) {
fc.m.Lock()
Expand Down
10 changes: 4 additions & 6 deletions cmd/templ/lspcmd/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,13 @@ func (p *Proxy) Handle(ctx context.Context, conn *jsonrpc2.Conn, r *jsonrpc2.Req
func (p *Proxy) proxyCall(ctx context.Context, conn *jsonrpc2.Conn, r *jsonrpc2.Request) {
var resp interface{}
err := p.gopls.Call(ctx, r.Method, &r.Params, &resp)
if err != nil {
p.log.Error("client -> gopls -> client: error", zap.String("method", r.Method), zap.Bool("notif", r.Notif), zap.Error(err))
}
p.log.Info("client -> gopls -> client: reply", zap.String("method", r.Method), zap.Bool("notif", r.Notif))
err = conn.Reply(ctx, r.ID, resp)
if err != nil {
p.log.Info("client -> gopls -> client: error sending response", zap.String("method", r.Method), zap.Bool("notif", r.Notif))
p.log.Info("client -> gopls -> client: error sending response", zap.String("method", r.Method), zap.Bool("notif", r.Notif), zap.Error(err))
}
p.log.Info("client -> gopls -> client: complete", zap.String("method", r.Method), zap.Bool("notif", r.Notif))
}
Expand Down Expand Up @@ -429,11 +432,6 @@ func (p *Proxy) rewriteDidOpenRequest(r *jsonrpc2.Request) (err error) {
return err
}

type applyWorkspaceEditParams struct {
Label string `json:"label"`
Edit lsp.WorkspaceEdit `json:"edit"`
}

func (p *Proxy) rewriteDidChangeRequest(ctx context.Context, r *jsonrpc2.Request) (err error) {
// Unmarshal the params.
var params lsp.DidChangeTextDocumentParams
Expand Down
8 changes: 0 additions & 8 deletions cmd/templ/lspcmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,6 @@ func run(ctx context.Context, args Arguments) (err error) {
return nil
}

type rpcLogger struct {
log *zap.Logger
}

func (l rpcLogger) Printf(format string, v ...interface{}) {
l.log.Sugar().Infof(format, v...)
}

type stdrwc struct {
log *zap.Logger
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/templ/lspcmd/pls/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"io"
"os"
"os/exec"

"github.com/sourcegraph/jsonrpc2"
Expand Down Expand Up @@ -33,7 +34,7 @@ func (opts Options) AsArguments() []string {
func NewGopls(ctx context.Context, zapLogger *zap.Logger, onGoplsRequest func(ctx context.Context, conn *jsonrpc2.Conn, r *jsonrpc2.Request), opts Options) (conn *jsonrpc2.Conn, err error) {
_, err = exec.LookPath("gopls")
if errors.Is(err, exec.ErrNotFound) {
err = errors.New("templ lsp: cannot find gopls on the path, you can install it with `go install golang.org/x/tools/gopls@latest`")
err = fmt.Errorf("templ lsp: cannot find gopls on the path (%q), you can install it with `go install golang.org/x/tools/gopls@latest`", os.Getenv("PATH"))
return
}
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/templ/processor/processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func Process(dir string, f func(fileName string) error, workerCount int, results
results <- Result{
FileName: sourceFileName,
Error: f(sourceFileName),
Duration: time.Now().Sub(start),
Duration: time.Since(start),
}
}
}()
Expand Down
2 changes: 2 additions & 0 deletions example/posts_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,9 @@ func (g *generator) writePackage() error {
if _, err = g.w.Write("\n\n"); err != nil {
return err
}
if _, err = g.w.Write("//lint:file-ignore SA4006 This context is only used if a nested component is present.\n\n"); err != nil {
return err
}
return nil
}

Expand Down Expand Up @@ -473,7 +476,7 @@ func (g *generator) writeCallTemplateExpression(indentLevel int, n parser.CallTe
return err
}
// Template expression.
if r, err = g.w.Write(fmt.Sprintf(`%s`, n.Expression.Value)); err != nil {
if r, err = g.w.Write(n.Expression.Value); err != nil {
return err
}
g.sourceMap.Add(n.Expression, r)
Expand Down
2 changes: 2 additions & 0 deletions generator/test-a-href/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-attribute-escaping/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-call/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-css-expression/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-css-usage/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-doctype/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-for/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-html/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-if/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-ifelse/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-script-usage/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-string/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-switch/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-switchdefault/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-text/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions generator/test-void/template_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 2 additions & 17 deletions parser/elementparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ var elementCloseTagParser = parse.All(asElementCloseTag,
var attributeNameFirst = "abcdefghijklmnopqrstuvwxyz"
var attributeNameSubsequent = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-"
var attributeNameParser = parse.Then(parse.WithStringConcatCombiner,
parse.RuneIn(elementNameFirst),
parse.Many(parse.WithStringConcatCombiner, 0, 128, parse.RuneIn(elementNameSubsequent)),
parse.RuneIn(attributeNameFirst),
parse.Many(parse.WithStringConcatCombiner, 0, 128, parse.RuneIn(attributeNameSubsequent)),
)

// Constant attribute.
Expand Down Expand Up @@ -303,21 +303,6 @@ type elementOpenCloseParser struct {
SourceRangeToItemLookup SourceMap
}

func (p elementOpenCloseParser) asElement(parts []interface{}) (result interface{}, ok bool) {
e := Element{
Name: parts[0].(elementOpenTag).Name,
Attributes: parts[0].(elementOpenTag).Attributes,
}
if arr, isArray := parts[1].([]Node); isArray {
e.Children = append(e.Children, arr...)
}
return e, true
}

func (p elementOpenCloseParser) asChildren(parts []interface{}) (result interface{}, ok bool) {
return parts, true
}

func (p elementOpenCloseParser) Parse(pi parse.Input) parse.Result {
var r Element

Expand Down
5 changes: 0 additions & 5 deletions parser/newline_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,6 @@ aaa`)
}
}

type runeAndPosition struct {
r rune
p Position
}

func TestNewLineStream(t *testing.T) {
input := input.NewFromString("A\nB\n\nD")
testPosition(t, "start", Position{Index: 0, Line: 1, Col: 0}, NewPositionFromInput(input))
Expand Down
7 changes: 0 additions & 7 deletions parser/switchexpressionparser.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,6 @@ func newSwitchExpressionParser() switchExpressionParser {
type switchExpressionParser struct {
}

func (p switchExpressionParser) asSingleExpression(parts []interface{}) (result interface{}, ok bool) {
if len(parts) == 0 {
return CaseExpression{}, true
}
return parts[0].(CaseExpression), true
}

func (p switchExpressionParser) asMany(parts []interface{}) (result interface{}, ok bool) {
r := []CaseExpression{}

Expand Down
4 changes: 2 additions & 2 deletions runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ func (cssh CSSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {

// RenderCSS renders a <style> element with CSS content, if the styles have not already been rendered.
func RenderCSS(ctx context.Context, w io.Writer, classes []CSSClass) (err error) {
ctx, rc := RenderedCSSClassesFromContext(ctx)
_, rc := RenderedCSSClassesFromContext(ctx)
var sb strings.Builder
for _, c := range classes {
if ccc, ok := c.(ComponentCSSClass); ok {
Expand Down Expand Up @@ -373,7 +373,7 @@ func RenderedScriptsFromContext(ctx context.Context) (context.Context, *StringSe

// RenderScripts renders a <script> element, if the script has not already been rendered.
func RenderScripts(ctx context.Context, w io.Writer, scripts ...ComponentScript) (err error) {
ctx, rs := RenderedScriptsFromContext(ctx)
_, rs := RenderedScriptsFromContext(ctx)
var sb strings.Builder
for _, s := range scripts {
if !rs.Contains(s.Name) {
Expand Down
2 changes: 2 additions & 0 deletions storybook/example/templates_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 3 additions & 14 deletions storybook/storybook.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,6 @@ func (sh *Storybook) AddComponent(name string, componentConstructor interface{},
sh.Config[name] = c
h := NewHandler(name, componentConstructor, args...)
sh.Handlers[name] = h
return
}

var storybookPreviewMatcher = pathvars.NewExtractor("/storybook_preview/{name}")
Expand Down Expand Up @@ -217,6 +216,9 @@ func (sh *Storybook) configureStorybook() (configHasChanged bool, err error) {
}
}
after, err := dirhash.HashDir(storiesDir, "/", dirhash.DefaultHash)
if err != nil {
return configHasChanged, fmt.Errorf("failed to hash directory %q: %w", storiesDir, err)
}
configHasChanged = before != after
// Configure storybook Preview URL.
err = os.WriteFile(filepath.Join(sh.Path, ".storybook/preview.js"), []byte(previewJS), os.ModePerm)
Expand All @@ -239,19 +241,6 @@ export const parameters = {
};
`

func (sh *Storybook) hasConfigChanged() (err error) {
var cmd exec.Cmd
cmd.Dir = sh.Path
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Path, err = exec.LookPath("npm")
if err != nil {
return fmt.Errorf("templ-storybook: cannot run storybook, cannot find npm on the path, check that Node.js is installed: %w", err)
}
cmd.Args = []string{"npm", "run", "storybook-build"}
return cmd.Run()
}

func (sh *Storybook) buildStorybook() (err error) {
var cmd exec.Cmd
cmd.Dir = sh.Path
Expand Down
2 changes: 2 additions & 0 deletions turbo/stream_templ.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 220fc80

Please sign in to comment.