{ return "pages" }
{ return 0 }
{
cfg := struct {
Dir string `json:"dir"`
}{Dir: "pages"}
if len(raw) > 0 {
_ = json.Unmarshal(raw, &cfg)
}
p.dir = cfg.Dir
routes := []struct{ Path, Comp string }{}
err := filepath.WalkDir(p.dir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if filepath.Ext(path) != ".go" || strings.HasSuffix(d.Name(), "_test.go") || strings.HasSuffix(d.Name(), "_gen.go") {
return nil
}
rel, err := filepath.Rel(p.dir, path)
if err != nil {
return err
}
r, c := deriveRoute(rel)
routes = append(routes, struct{ Path, Comp string }{r, c})
return nil
})
if err != nil {
return err
}
if len(routes) == 0 {
return nil
}
var b strings.Builder
b.WriteString("// Code generated by pages plugin. DO NOT EDIT.\n")
b.WriteString("package pages\n\n")
b.WriteString("import \"github.com/rfwlab/rfw/v1/router\"\n\n")
b.WriteString("func init() {\n")
for _, r := range routes {
b.WriteString("\trouter.RegisterRoute(router.Route{Path: \"" + r.Path + "\", Component: " + r.Comp + "})\n")
}
b.WriteString("}\n")
p.file = filepath.Join(p.dir, "routes_gen.go")
return os.WriteFile(p.file, []byte(b.String()), 0o644)
}
{ return nil }
{
if p.file != "" {
_ = os.Remove(p.file)
}
return nil
}
{
if !strings.HasPrefix(path, p.dir) {
return false
}
return !strings.HasSuffix(path, "_gen.go")
}
{ plugins.Register(&plugin{}) }
{
rel = strings.TrimSuffix(rel, ".go")
segments := strings.Split(rel, string(filepath.Separator))
pathSegs := []string{}
nameSegs := []string{}
for i, s := range segments {
isLast := i == len(segments)-1
if isLast && s == "index" {
nameSegs = append(nameSegs, "Index")
continue
}
if strings.HasPrefix(s, "[") && strings.HasSuffix(s, "]") {
param := s[1 : len(s)-1]
pathSegs = append(pathSegs, ":"+param)
nameSegs = append(nameSegs, toPascal(param))
} else {
pathSegs = append(pathSegs, s)
nameSegs = append(nameSegs, toPascal(s))
}
}
path := "/" + strings.Join(pathSegs, "/")
if len(pathSegs) == 0 {
path = "/"
}
comp := strings.Join(nameSegs, "")
return path, comp
}
{
s = strings.ReplaceAll(s, "-", " ")
s = strings.ReplaceAll(s, "_", " ")
parts := strings.Fields(s)
for i, p := range parts {
parts[i] = strings.ToUpper(p[:1]) + strings.ToLower(p[1:])
}
return strings.Join(parts, "")
}
{
tests := map[string]struct{ path, comp string }{
"index.go": {"/", "Index"},
"about.go": {"/about", "About"},
"blog/index.go": {"/blog", "BlogIndex"},
"posts/[id].go": {"/posts/:id", "PostsId"},
"[user]/settings.go": {"/:user/settings", "UserSettings"},
}
for in, exp := range tests {
p, c := deriveRoute(in)
if p != exp.path || c != exp.comp {
t.Errorf("%s => (%s,%s), want (%s,%s)", in, p, c, exp.path, exp.comp)
}
}
}
import "encoding/json"
import "io/fs"
import "os"
import "path/filepath"
import "strings"
import "github.com/rfwlab/rfw/cmd/rfw/plugins"
import "testing"