Skip to content

Commit

Permalink
add fileset to name expressions
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Aug 19, 2024
1 parent b2c88c3 commit 532fe62
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
13 changes: 9 additions & 4 deletions name.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,14 @@ type TemplateName struct {
fun *ast.Ident
call *ast.CallExpr

fileSet *token.FileSet

pathValueNames []string
}

func NewTemplateName(in string) (TemplateName, error, bool) {
func NewTemplateName(in string) (TemplateName, error, bool) { return newTemplate(in, "") }

func newTemplate(in, fileName string) (TemplateName, error, bool) {
if !templateNameMux.MatchString(in) {
return TemplateName{}, nil, false
}
Expand All @@ -59,6 +63,7 @@ func NewTemplateName(in string) (TemplateName, error, bool) {
path: matches[templateNameMux.SubexpIndex("path")],
handler: strings.TrimSpace(matches[templateNameMux.SubexpIndex("handler")]),
endpoint: matches[templateNameMux.SubexpIndex("endpoint")],
fileSet: token.NewFileSet(),
}

switch p.method {
Expand All @@ -76,7 +81,7 @@ func NewTemplateName(in string) (TemplateName, error, bool) {
return TemplateName{}, err, true
}

return p, parseHandler(&p), true
return p, parseHandler(p.fileSet, fileName, &p), true
}

var (
Expand Down Expand Up @@ -127,11 +132,11 @@ func (def TemplateName) byPathThenMethod(d TemplateName) int {
return cmp.Compare(def.handler, d.handler)
}

func parseHandler(def *TemplateName) error {
func parseHandler(fileSet *token.FileSet, fileName string, def *TemplateName) error {
if def.handler == "" {
return nil
}
e, err := parser.ParseExpr(def.handler)
e, err := parser.ParseExprFrom(fileSet, fileName, []byte(def.handler), 0)
if err != nil {
return fmt.Errorf("failed to parse handler expression: %v", err)
}
Expand Down
11 changes: 10 additions & 1 deletion name_internal_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package muxt

import (
"fmt"
"net/http"
"slices"
"testing"
Expand Down Expand Up @@ -88,11 +89,19 @@ func TestTemplateName_ByPathThenMethod(t *testing.T) {
} {
t.Run(tt.Name, func(t *testing.T) {
slices.SortFunc(tt.In, TemplateName.byPathThenMethod)
assert.Equal(t, tt.Exp, tt.In)
assert.Equal(t, stringList(tt.Exp), stringList(tt.In))
})
}
}

func stringList[T fmt.Stringer](in []T) []string {
out := make([]string, 0, len(in))
for _, e := range in {
out = append(out, e.String())
}
return out
}

func mustNewTemplateName(in ...string) []TemplateName {
var result []TemplateName
for _, n := range in {
Expand Down

0 comments on commit 532fe62

Please sign in to comment.