collector.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package permlib
  2. import (
  3. "strings"
  4. "github.com/xiaozi/permlib/pb"
  5. )
  6. func (e *Engine) collectPerms() []*pb.PermItem {
  7. seen := make(map[string]bool)
  8. var perms []*pb.PermItem
  9. add := func(code, name string) {
  10. if seen[code] {
  11. return
  12. }
  13. seen[code] = true
  14. if name == "" {
  15. name = generatePermName(code)
  16. }
  17. perms = append(perms, &pb.PermItem{Code: code, Name: name})
  18. }
  19. for _, decl := range e.staticPerms {
  20. add(decl.Code, decl.Name)
  21. dataCode := apiToDataCode(decl.Code)
  22. if dataCode != "" {
  23. add(dataCode, "")
  24. }
  25. }
  26. return perms
  27. }
  28. func apiToDataCode(apiCode string) string {
  29. if !strings.HasPrefix(apiCode, "api:") {
  30. return ""
  31. }
  32. return "data:" + apiCode[4:]
  33. }
  34. func generatePermName(code string) string {
  35. parts := strings.Split(code, ":")
  36. if len(parts) < 2 {
  37. return code
  38. }
  39. nameMap := map[string]string{
  40. "read": "读取",
  41. "write": "写入",
  42. "create": "创建",
  43. "update": "更新",
  44. "delete": "删除",
  45. "list": "列表",
  46. "detail": "详情",
  47. }
  48. var result []string
  49. for i := 1; i < len(parts); i++ {
  50. p := parts[i]
  51. if mapped, ok := nameMap[p]; ok {
  52. result = append(result, mapped)
  53. } else {
  54. result = append(result, p)
  55. }
  56. }
  57. return strings.Join(result, "-")
  58. }