main.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "strings"
  8. "github.com/pkg/errors"
  9. )
  10. var (
  11. flagDep = flag.String("dep", "main,live,openplatform,ep", "department list , split by comma")
  12. flagPrefix = flag.String("prefix", `business`, "prefix path")
  13. flagService = flag.String("serivce", "interface,job,admin,service", "service type")
  14. // flagWhite prefix下允许的dir名称
  15. flagWhite = flag.String("white", "", "white subpath from prefix , split by comma")
  16. )
  17. const (
  18. codeSuccess = 0
  19. codeFail = 1
  20. )
  21. func main() {
  22. flag.Parse()
  23. var (
  24. depList []string
  25. serviceList []string
  26. filePathList []string
  27. whiteDirList []string
  28. )
  29. filePathList = flag.Args()
  30. if len(filePathList) <= 0 {
  31. fmt.Println("No file to check")
  32. os.Exit(codeSuccess)
  33. }
  34. depList = strings.Split(*flagDep, ",")
  35. serviceList = strings.Split(*flagService, ",")
  36. for _, wd := range strings.Split(*flagWhite, ",") {
  37. if wd != "" {
  38. whiteDirList = append(whiteDirList, strings.Join([]string{*flagPrefix, wd}, "/"))
  39. }
  40. }
  41. code := check(filePathList, serviceList, depList, whiteDirList)
  42. os.Exit(code)
  43. }
  44. func check(filePathList []string, serviceTypeList []string, depList []string, whiteDirList []string) (code int) {
  45. var (
  46. regDep = strings.Join(depList, "|")
  47. serviceType = strings.Join(serviceTypeList, "|")
  48. regStr = fmt.Sprintf(`%s/(%s)/(%s)`, *flagPrefix, serviceType, regDep)
  49. reg *regexp.Regexp
  50. flag = true
  51. failedFiles []string
  52. err error
  53. )
  54. regStr = strings.Replace(regStr, "/", `\/`, -1)
  55. if reg, err = regexp.Compile(regStr); err != nil {
  56. err = errors.Wrapf(err, "regexp : %s", regStr)
  57. fmt.Printf("%+v\n", err)
  58. code = codeFail
  59. return
  60. }
  61. for _, p := range filePathList {
  62. if strings.HasPrefix(p, *flagPrefix) {
  63. if whiteCheck(whiteDirList, p) {
  64. continue
  65. }
  66. if !reg.MatchString(p) {
  67. failedFiles = append(failedFiles, p)
  68. flag = false
  69. break
  70. }
  71. }
  72. }
  73. if !flag {
  74. fmt.Println("invalid files : ")
  75. for _, f := range failedFiles {
  76. fmt.Printf("\t%s\n", f)
  77. }
  78. code = codeFail
  79. } else {
  80. code = codeSuccess
  81. }
  82. return
  83. }
  84. func whiteCheck(whiteDirList []string, path string) bool {
  85. for _, wd := range whiteDirList {
  86. if strings.HasPrefix(path, wd) {
  87. return true
  88. }
  89. }
  90. return false
  91. }