Skip to content

Commit

Permalink
optimize: router_sort
Browse files Browse the repository at this point in the history
  • Loading branch information
FGYFFFF committed Apr 24, 2024
1 parent bd2a9b2 commit 52964c9
Show file tree
Hide file tree
Showing 7 changed files with 35 additions and 12 deletions.
3 changes: 3 additions & 0 deletions cmd/hz/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ func Init() *cli.App {
noRecurseFlag := cli.BoolFlag{Name: "no_recurse", Usage: "Generate master model only.", Destination: &globalArgs.NoRecurse}
forceNewFlag := cli.BoolFlag{Name: "force", Aliases: []string{"f"}, Usage: "Force new a project, which will overwrite the generated files", Destination: &globalArgs.ForceNew}
enableExtendsFlag := cli.BoolFlag{Name: "enable_extends", Usage: "Parse 'extends' for thrift IDL", Destination: &globalArgs.EnableExtends}
sortRouterFlag := cli.BoolFlag{Name: "sort_router", Usage: "Sort router register code, to avoid code difference", Destination: &globalArgs.SortRouter}

jsonEnumStrFlag := cli.BoolFlag{Name: "json_enumstr", Usage: "Use string instead of num for json enums when idl is thrift.", Destination: &globalArgs.JSONEnumStr}
queryEnumIntFlag := cli.BoolFlag{Name: "query_enumint", Usage: "Use num instead of string for query enum parameter.", Destination: &globalArgs.QueryEnumAsInt}
Expand Down Expand Up @@ -227,6 +228,7 @@ func Init() *cli.App {
&noRecurseFlag,
&forceNewFlag,
&enableExtendsFlag,
&sortRouterFlag,

&jsonEnumStrFlag,
&unsetOmitemptyFlag,
Expand Down Expand Up @@ -261,6 +263,7 @@ func Init() *cli.App {
&optPkgFlag,
&noRecurseFlag,
&enableExtendsFlag,
&sortRouterFlag,

&jsonEnumStrFlag,
&unsetOmitemptyFlag,
Expand Down
1 change: 1 addition & 0 deletions cmd/hz/config/argument.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ type Argument struct {
ForceNew bool
SnakeStyleMiddleware bool
EnableExtends bool
SortRouter bool

CustomizeLayout string
CustomizeLayoutData string
Expand Down
2 changes: 1 addition & 1 deletion cmd/hz/generator/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ func (pkgGen *HttpPackageGenerator) processHandler(handler *Handler, root *Route
}
handler.Imports[mm.PackageName] = mm
}
err := root.Update(m, handler.PackageName, singleHandlerPackage)
err := root.Update(m, handler.PackageName, singleHandlerPackage, pkgGen.SortRouter)
if err != nil {
return err
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/hz/generator/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,13 @@ type HttpPackageGenerator struct {
IdlClientDir string // client dir for "client" command
ForceClientDir string // client dir without namespace for "client" command
BaseDomain string // request domain for "client" command
QueryEnumAsInt bool // client code use number for query parameter
QueryEnumAsInt bool // client code use number for query parameter
ServiceGenDir string

NeedModel bool
HandlerByMethod bool // generate handler files with method dimension
SnakeStyleMiddleware bool // use snake name style for middleware
SortRouter bool

loadedBackend Backend
curModel *model.Model
Expand Down
36 changes: 26 additions & 10 deletions cmd/hz/generator/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"regexp"
"sort"
"strings"
"unicode"

"github.com/cloudwego/hertz/cmd/hz/util"
)
Expand Down Expand Up @@ -73,7 +74,7 @@ func (routerNode *RouterNode) Sort() {
sort.Sort(routerNode.Children)
}

func (routerNode *RouterNode) Update(method *HttpMethod, handlerType, handlerPkg string) error {
func (routerNode *RouterNode) Update(method *HttpMethod, handlerType, handlerPkg string, sortRouter bool) error {
if method.Path == "" {
return fmt.Errorf("empty path for method '%s'", method.Name)
}
Expand All @@ -86,7 +87,7 @@ func (routerNode *RouterNode) Update(method *HttpMethod, handlerType, handlerPkg
return fmt.Errorf("path '%s' has been registered", method.Path)
}
name := util.ToVarName(paths[:last])
parent.Insert(name, method, handlerType, paths[last:], handlerPkg)
parent.Insert(name, method, handlerType, paths[last:], handlerPkg, sortRouter)
parent.Sort()
return nil
}
Expand Down Expand Up @@ -192,7 +193,7 @@ func (routerNode *RouterNode) DFS(i int, hook func(layer int, node *RouterNode)

var handlerPkgMap map[string]string

func (routerNode *RouterNode) Insert(name string, method *HttpMethod, handlerType string, paths []string, handlerPkg string) {
func (routerNode *RouterNode) Insert(name string, method *HttpMethod, handlerType string, paths []string, handlerPkg string, sortRouter bool) {
cur := routerNode
for i, p := range paths {
c := &RouterNode{
Expand Down Expand Up @@ -229,6 +230,9 @@ func (routerNode *RouterNode) Insert(name string, method *HttpMethod, handlerTyp
cur.Children = make([]*RouterNode, 0, 1)
}
cur.Children = append(cur.Children, c)
if sortRouter {
sort.Sort(cur.Children)
}
cur = c
}
}
Expand Down Expand Up @@ -270,17 +274,29 @@ func (c childrenRouterInfo) Len() int {
// Less reports whether the element with
// index i should sort before the element with index j.
func (c childrenRouterInfo) Less(i, j int) bool {
ci := c[i].Path
if len(c[i].Children) != 0 {
ci = ci[1:]
}
cj := c[j].Path
if len(c[j].Children) != 0 {
cj = cj[1:]
// remove non-litter char
// eg. /a -> a
// /:a -> a
ci := removeNonLetterPrefix(c[i].Path)
cj := removeNonLetterPrefix(c[j].Path)

// if ci == cj, use HTTP mothod for sort, preventing sorting inconsistencies
if ci == cj {
return c[i].HttpMethod < c[j].HttpMethod
}

return ci < cj
}

func removeNonLetterPrefix(str string) string {
for i, char := range str {
if unicode.IsLetter(char) || unicode.IsDigit(char) {
return str[i:]
}
}
return str
}

// Swap swaps the elements with indexes i and j.
func (c childrenRouterInfo) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
Expand Down
1 change: 1 addition & 0 deletions cmd/hz/protobuf/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,7 @@ func (plugin *Plugin) genHttpPackage(ast *descriptorpb.FileDescriptorProto, deps
BaseDomain: args.BaseDomain,
QueryEnumAsInt: args.QueryEnumAsInt,
SnakeStyleMiddleware: args.SnakeStyleMiddleware,
SortRouter: args.SortRouter,
}

if args.ModelBackend != "" {
Expand Down
1 change: 1 addition & 0 deletions cmd/hz/thrift/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ func (plugin *Plugin) Run() int {
BaseDomain: args.BaseDomain,
QueryEnumAsInt: args.QueryEnumAsInt,
SnakeStyleMiddleware: args.SnakeStyleMiddleware,
SortRouter: args.SortRouter,
}
if args.ModelBackend != "" {
sg.Backend = meta.Backend(args.ModelBackend)
Expand Down

0 comments on commit 52964c9

Please sign in to comment.