1
0

parser.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package beego
  15. import (
  16. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "go/ast"
  20. "go/parser"
  21. "go/token"
  22. "io/ioutil"
  23. "os"
  24. "path/filepath"
  25. "sort"
  26. "strings"
  27. "github.com/astaxie/beego/logs"
  28. "github.com/astaxie/beego/utils"
  29. )
  30. var globalRouterTemplate = `package routers
  31. import (
  32. "github.com/astaxie/beego"
  33. )
  34. func init() {
  35. {{.globalinfo}}
  36. }
  37. `
  38. var (
  39. lastupdateFilename = "lastupdate.tmp"
  40. commentFilename string
  41. pkgLastupdate map[string]int64
  42. genInfoList map[string][]ControllerComments
  43. )
  44. const commentPrefix = "commentsRouter_"
  45. func init() {
  46. pkgLastupdate = make(map[string]int64)
  47. }
  48. func parserPkg(pkgRealpath, pkgpath string) error {
  49. rep := strings.NewReplacer("\\", "_", "/", "_", ".", "_")
  50. commentFilename, _ = filepath.Rel(AppPath, pkgRealpath)
  51. commentFilename = commentPrefix + rep.Replace(commentFilename) + ".go"
  52. if !compareFile(pkgRealpath) {
  53. logs.Info(pkgRealpath + " no changed")
  54. return nil
  55. }
  56. genInfoList = make(map[string][]ControllerComments)
  57. fileSet := token.NewFileSet()
  58. astPkgs, err := parser.ParseDir(fileSet, pkgRealpath, func(info os.FileInfo) bool {
  59. name := info.Name()
  60. return !info.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
  61. }, parser.ParseComments)
  62. if err != nil {
  63. return err
  64. }
  65. for _, pkg := range astPkgs {
  66. for _, fl := range pkg.Files {
  67. for _, d := range fl.Decls {
  68. switch specDecl := d.(type) {
  69. case *ast.FuncDecl:
  70. if specDecl.Recv != nil {
  71. exp, ok := specDecl.Recv.List[0].Type.(*ast.StarExpr) // Check that the type is correct first beforing throwing to parser
  72. if ok {
  73. parserComments(specDecl.Doc, specDecl.Name.String(), fmt.Sprint(exp.X), pkgpath)
  74. }
  75. }
  76. }
  77. }
  78. }
  79. }
  80. genRouterCode(pkgRealpath)
  81. savetoFile(pkgRealpath)
  82. return nil
  83. }
  84. func parserComments(comments *ast.CommentGroup, funcName, controllerName, pkgpath string) error {
  85. if comments != nil && comments.List != nil {
  86. for _, c := range comments.List {
  87. t := strings.TrimSpace(strings.TrimLeft(c.Text, "//"))
  88. if strings.HasPrefix(t, "@router") {
  89. elements := strings.TrimLeft(t, "@router ")
  90. e1 := strings.SplitN(elements, " ", 2)
  91. if len(e1) < 1 {
  92. return errors.New("you should has router information")
  93. }
  94. key := pkgpath + ":" + controllerName
  95. cc := ControllerComments{}
  96. cc.Method = funcName
  97. cc.Router = e1[0]
  98. if len(e1) == 2 && e1[1] != "" {
  99. e1 = strings.SplitN(e1[1], " ", 2)
  100. if len(e1) >= 1 {
  101. cc.AllowHTTPMethods = strings.Split(strings.Trim(e1[0], "[]"), ",")
  102. } else {
  103. cc.AllowHTTPMethods = append(cc.AllowHTTPMethods, "get")
  104. }
  105. } else {
  106. cc.AllowHTTPMethods = append(cc.AllowHTTPMethods, "get")
  107. }
  108. if len(e1) == 2 && e1[1] != "" {
  109. keyval := strings.Split(strings.Trim(e1[1], "[]"), " ")
  110. for _, kv := range keyval {
  111. kk := strings.Split(kv, ":")
  112. cc.Params = append(cc.Params, map[string]string{strings.Join(kk[:len(kk)-1], ":"): kk[len(kk)-1]})
  113. }
  114. }
  115. genInfoList[key] = append(genInfoList[key], cc)
  116. }
  117. }
  118. }
  119. return nil
  120. }
  121. func genRouterCode(pkgRealpath string) {
  122. os.Mkdir(getRouterDir(pkgRealpath), 0755)
  123. logs.Info("generate router from comments")
  124. var (
  125. globalinfo string
  126. sortKey []string
  127. )
  128. for k := range genInfoList {
  129. sortKey = append(sortKey, k)
  130. }
  131. sort.Strings(sortKey)
  132. for _, k := range sortKey {
  133. cList := genInfoList[k]
  134. for _, c := range cList {
  135. allmethod := "nil"
  136. if len(c.AllowHTTPMethods) > 0 {
  137. allmethod = "[]string{"
  138. for _, m := range c.AllowHTTPMethods {
  139. allmethod += `"` + m + `",`
  140. }
  141. allmethod = strings.TrimRight(allmethod, ",") + "}"
  142. }
  143. params := "nil"
  144. if len(c.Params) > 0 {
  145. params = "[]map[string]string{"
  146. for _, p := range c.Params {
  147. for k, v := range p {
  148. params = params + `map[string]string{` + k + `:"` + v + `"},`
  149. }
  150. }
  151. params = strings.TrimRight(params, ",") + "}"
  152. }
  153. globalinfo = globalinfo + `
  154. beego.GlobalControllerRouter["` + k + `"] = append(beego.GlobalControllerRouter["` + k + `"],
  155. beego.ControllerComments{
  156. Method: "` + strings.TrimSpace(c.Method) + `",
  157. ` + "Router: `" + c.Router + "`" + `,
  158. AllowHTTPMethods: ` + allmethod + `,
  159. Params: ` + params + `})
  160. `
  161. }
  162. }
  163. if globalinfo != "" {
  164. f, err := os.Create(filepath.Join(getRouterDir(pkgRealpath), commentFilename))
  165. if err != nil {
  166. panic(err)
  167. }
  168. defer f.Close()
  169. f.WriteString(strings.Replace(globalRouterTemplate, "{{.globalinfo}}", globalinfo, -1))
  170. }
  171. }
  172. func compareFile(pkgRealpath string) bool {
  173. if !utils.FileExists(filepath.Join(getRouterDir(pkgRealpath), commentFilename)) {
  174. return true
  175. }
  176. if utils.FileExists(lastupdateFilename) {
  177. content, err := ioutil.ReadFile(lastupdateFilename)
  178. if err != nil {
  179. return true
  180. }
  181. json.Unmarshal(content, &pkgLastupdate)
  182. lastupdate, err := getpathTime(pkgRealpath)
  183. if err != nil {
  184. return true
  185. }
  186. if v, ok := pkgLastupdate[pkgRealpath]; ok {
  187. if lastupdate <= v {
  188. return false
  189. }
  190. }
  191. }
  192. return true
  193. }
  194. func savetoFile(pkgRealpath string) {
  195. lastupdate, err := getpathTime(pkgRealpath)
  196. if err != nil {
  197. return
  198. }
  199. pkgLastupdate[pkgRealpath] = lastupdate
  200. d, err := json.Marshal(pkgLastupdate)
  201. if err != nil {
  202. return
  203. }
  204. ioutil.WriteFile(lastupdateFilename, d, os.ModePerm)
  205. }
  206. func getpathTime(pkgRealpath string) (lastupdate int64, err error) {
  207. fl, err := ioutil.ReadDir(pkgRealpath)
  208. if err != nil {
  209. return lastupdate, err
  210. }
  211. for _, f := range fl {
  212. if lastupdate < f.ModTime().UnixNano() {
  213. lastupdate = f.ModTime().UnixNano()
  214. }
  215. }
  216. return lastupdate, nil
  217. }
  218. func getRouterDir(pkgRealpath string) string {
  219. dir := filepath.Dir(pkgRealpath)
  220. for {
  221. d := filepath.Join(dir, "routers")
  222. if utils.FileExists(d) {
  223. return d
  224. }
  225. if r, _ := filepath.Rel(dir, AppPath); r == "." {
  226. return d
  227. }
  228. // Parent dir.
  229. dir = filepath.Dir(dir)
  230. }
  231. }