Skip to content

Commit

Permalink
rewrite generation and expose simple types
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Aug 18, 2024
1 parent 4684f24 commit 339bceb
Show file tree
Hide file tree
Showing 41 changed files with 1,658 additions and 1,040 deletions.
80 changes: 80 additions & 0 deletions cmd/muxt/generate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package main

import (
"flag"
"fmt"
"go/ast"
"io"
"log"
"os"
"path/filepath"
"slices"

"golang.org/x/tools/go/packages"

"github.com/crhntr/muxt"
"github.com/crhntr/muxt/internal/source"
)

const CodeGenerationComment = "// Code generated by muxt. DO NOT EDIT."

type Generate struct {
Package *packages.Package
goPackage string
goFile string
goLine string

templatesVariable string
outputFilename string
routesFunction string
}

func (g Generate) ImportReceiverMethods(tp, method string) (*ast.FuncType, []*ast.ImportSpec, bool) {
return source.GoFiles(g.Package.Syntax).ImportReceiverMethods(tp, method)
}

func generateCommand(args []string, workingDirectory string, getEnv func(string) string, stdout, stderr io.Writer) error {
config := Generate{
goPackage: getEnv("GOPACKAGE"),
goFile: getEnv("GOFILE"),
goLine: getEnv("GOLINE"),
}
flagSet := flag.NewFlagSet("generate", flag.ContinueOnError)
flagSet.StringVar(&config.templatesVariable, "templates-variable", muxt.DefaultTemplatesVariableName, "templates variable name")
flagSet.StringVar(&config.outputFilename, "output-file", "template_routes.go", "file name of generated output")
flagSet.StringVar(&config.routesFunction, "routes-func", muxt.DefaultRoutesFunctionName, "file name of generated output")
if err := flagSet.Parse(args); err != nil {
return err
}
list, err := packages.Load(&packages.Config{
Mode: packages.NeedFiles | packages.NeedSyntax | packages.NeedEmbedPatterns | packages.NeedEmbedFiles,
Dir: workingDirectory,
Tests: false,
}, workingDirectory)
if err != nil {
return err
}
if config.goPackage != "" {
i := slices.IndexFunc(list, func(p *packages.Package) bool { return p.ID == config.goPackage })
if i < 0 {
return fmt.Errorf("package %s not loaded", config.goPackage)
}
config.Package = list[i]
} else if len(list) > 0 {
config.Package = list[0]
}
ts, err := source.Templates(workingDirectory, config.templatesVariable, config.Package.Fset, config.Package.Syntax, config.Package.EmbedFiles)
if err != nil {
return err
}
patterns, err := muxt.TemplatePatterns(ts)
if err != nil {
return err
}
out := log.New(stdout, "", 0)
s, err := muxt.Generate(patterns, config.goPackage, config.templatesVariable, config.routesFunction, "", config.Package.Fset, config.Package.Syntax, config.Package.Syntax, out)
if err != nil {
return err
}
return os.WriteFile(filepath.Join(workingDirectory, config.outputFilename), []byte(CodeGenerationComment+"\n\n"+s), 0644)
}
26 changes: 12 additions & 14 deletions internal/generate/generate_test.go → cmd/muxt/generate_test.go
Original file line number Diff line number Diff line change
@@ -1,42 +1,40 @@
package generate_test
package main

import (
"bytes"
"context"
"log"
"path/filepath"
"strings"
"testing"

"rsc.io/script"
"rsc.io/script/scripttest"

"github.com/crhntr/muxt/internal/generate"
)

func Test(t *testing.T) {
func TestGenerate(t *testing.T) {
e := script.NewEngine()
e.Quiet = true
e.Cmds = scripttest.DefaultCmds()
e.Cmds["generate"] = script.Command(script.CmdUsage{
Summary: "executes muxt generate",
e.Cmds["muxt"] = script.Command(script.CmdUsage{
Summary: "muxt",
Args: "",
}, func(state *script.State, args ...string) (script.WaitFunc, error) {
return func(state *script.State) (string, string, error) {
var buf bytes.Buffer
logger := log.New(&buf, "", 0)
err := generate.Command(args, state.Getwd(), logger, state.LookupEnv)
var stdout, stderr bytes.Buffer
err := command(state.Getwd(), args, func(s string) string {
e, _ := state.LookupEnv(s)
return e
}, &stdout, &stderr)
if err != nil {
buf.WriteString(err.Error())
stderr.WriteString(err.Error())
}
return buf.String(), "", err
return stdout.String(), stderr.String(), err
}, nil
})
testFiles, err := filepath.Glob(filepath.FromSlash("testdata/*.txtar"))
testFiles, err := filepath.Glob(filepath.FromSlash("testdata/generate/*.txtar"))
if err != nil {
t.Fatal(err)
}

for _, filePath := range testFiles {
name := strings.TrimSuffix(filepath.Base(filePath), filepath.Ext(filePath))
t.Run(name, func(t *testing.T) {
Expand Down
31 changes: 23 additions & 8 deletions cmd/muxt/main.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,35 @@
package main

import (
_ "embed"
"log"
"flag"
"fmt"
"io"
"os"

"github.com/crhntr/muxt/internal/generate"
)

func main() {
flag.Parse()
wd, err := os.Getwd()
if err != nil {
log.Fatal(err)
os.Exit(handleError(err))
}
os.Exit(handleError(command(wd, flag.Args(), os.Getenv, os.Stdout, os.Stderr)))
}

func command(wd string, args []string, getEnv func(string) string, stdout, stderr io.Writer) error {
if len(args) > 0 {
switch args[0] {
case "generate", "gen", "g":
return generateCommand(args[1:], wd, getEnv, stdout, stderr)
}
}
logger := log.New(os.Stdout, "muxt: ", 0)
if err := generate.Command(os.Args[1:], wd, logger, os.LookupEnv); err != nil {
log.Fatal(err)
return fmt.Errorf("unknown command")
}

func handleError(err error) int {
if err != nil {
_, _ = os.Stderr.WriteString(err.Error())
return 1
}
return 0
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down Expand Up @@ -39,7 +39,7 @@ import (

type T struct{}

func (T) Method(ctx context.Context) (any, error) { return nil, nil }
func (T) Method(ctx context.Context) any { return nil }

func Test(t *testing.T) {
mux := http.NewServeMux()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down Expand Up @@ -39,7 +39,7 @@ import (

type T struct{}

func (T) Method(u string) (any, error) { return u, nil }
func (T) Method(u string) any { return u }

func Test(t *testing.T) {
mux := http.NewServeMux()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down Expand Up @@ -39,7 +39,7 @@ import (

type T struct{}

func (T) Method(*http.Request) (any, error) { return nil, nil }
func (T) Method(*http.Request) any { return nil }

func Test(t *testing.T) {
mux := http.NewServeMux()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down Expand Up @@ -39,7 +39,7 @@ import (

type T struct{}

func (T) Method(http.ResponseWriter) (any, error) { return nil, nil }
func (T) Method(http.ResponseWriter) any { return nil }

func Test(t *testing.T) {
mux := http.NewServeMux()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

! generate
stdout 'duplicate route pattern: GET /'
! muxt generate --routes-func=TemplateRoutes
stderr 'duplicate route pattern: GET /'

-- template.gohtml --
{{define "GET / Greetings()" }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

! generate --unknown
stdout 'flag'
! muxt generate --routes-func=TemplateRoutes --unknown
stderr 'flag'

-- template.gohtml --
{{printf "Hello, %s!", "world"}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ env GOLINE=11
env GOPACKAGE=unexpected
env GOFILE=template.go

! generate
stdout 'package unexpected not found'
! muxt generate --routes-func=TemplateRoutes
stderr 'package unexpected not loaded'

-- template.gohtml --
{{printf "Hello, %s!", "world"}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=13
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes
! stdout execute

exec go test -v -cover
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down Expand Up @@ -45,7 +45,7 @@ type Data struct {
Name string
}

func (T) ToUpper(in string) (any, error) { return Data{Name: strings.ToUpper(in)}, nil }
func (T) ToUpper(in string) any { return Data{Name: strings.ToUpper(in)} }

func Test(t *testing.T) {
mux := http.NewServeMux()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down Expand Up @@ -39,7 +39,7 @@ import (

type T struct{}

func (T) Number() (any, error) { return 32, nil }
func (T) Number() any { return 32 }

func Test(t *testing.T) {
mux := http.NewServeMux()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
muxt generate --routes-func=TemplateRoutes

exec go test -cover

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ env GOLINE=12
env GOPACKAGE=server
env GOFILE=template.go

generate
stdout 'TemplateRoutes has route for GET /'
muxt generate --routes-func=TemplateRoutes
stdout 'Routes has route for GET /'

-- index.gohtml --
{{define "GET /" }}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ env GOLINE=11
env GOPACKAGE=server
env GOFILE=template.go

generate
! stdout 'TemplateRoutes has route for GET /example'
muxt generate --routes-func=TemplateRoutes
! stdout 'Routes has route for GET /example'

exec go test

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ env GOLINE=12
env GOPACKAGE=server
env GOFILE=template.go

generate
stdout 'TemplateRoutes has route for GET /'
stdout 'TemplateRoutes has route for GET /form'
stdout 'TemplateRoutes has route for POST /form'
muxt generate --routes-func=TemplateRoutes
stdout 'Routes has route for GET /'
stdout 'Routes has route for GET /form'
stdout 'Routes has route for POST /form'

-- index.gohtml --
{{define "GET /" }}
Expand Down
Loading

0 comments on commit 339bceb

Please sign in to comment.