-
Notifications
You must be signed in to change notification settings - Fork 189
/
utils.go
107 lines (90 loc) · 2.42 KB
/
utils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package admin
import (
"html/template"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"github.com/qor/assetfs"
"github.com/qor/qor"
"github.com/qor/qor/utils"
"github.com/qor/roles"
)
var (
globalViewPaths []string
globalAssetFSes []assetfs.Interface
goModDeps []string
goModPrefix = "pkg/mod"
)
// HasPermissioner has permission interface
type HasPermissioner interface {
HasPermission(roles.PermissionMode, *qor.Context) bool
}
// ResourceNamer is an interface for models that defined method `ResourceName`
type ResourceNamer interface {
ResourceName() string
}
// I18n define admin's i18n interface
type I18n interface {
Scope(scope string) I18n
Default(value string) I18n
T(locale string, key string, args ...interface{}) template.HTML
}
// RegisterViewPath register view path for all assetfs
func RegisterViewPath(pth string) {
globalViewPaths = append(globalViewPaths, pth)
var err error
for _, assetFS := range globalAssetFSes {
if err = assetFS.RegisterPath(filepath.Join(utils.AppRoot, "vendor", pth)); err != nil {
for _, gopath := range utils.GOPATH() {
startDir, _ := os.Getwd()
if modPath := findGoModFile(startDir); modPath != "" {
if err = assetFS.RegisterPath(filepath.Join(gopath, getDepVersionFromMod(modPath, pth))); err == nil {
break
}
}
if err = assetFS.RegisterPath(filepath.Join(gopath, "src", pth)); err == nil {
break
}
}
}
}
if err != nil {
log.Printf("RegisterViewPathError: %s %s!", pth, err.Error())
}
}
func equal(a, b interface{}) bool {
return reflect.DeepEqual(a, b)
}
func getDepVersionFromMod(modPath, pth string) string {
if len(goModDeps) == 0 {
if cont, err := os.ReadFile(modPath); err == nil {
goModDeps = strings.Split(string(cont), "\n")
}
}
for _, val := range goModDeps {
if txt := strings.Trim(val, "\t\r"); strings.HasPrefix(txt, pth) {
return filepath.Join(goModPrefix, pth+"@"+strings.Split(txt, " ")[1])
}
}
if strings.LastIndex(pth, "/") == -1 {
return pth
}
return getDepVersionFromMod(modPath, pth[:strings.LastIndex(pth, "/")]) + pth[strings.LastIndex(pth, "/"):]
}
func findGoModFile(startDir string) string {
currentDir := startDir
for {
goModPath := filepath.Join(currentDir, "go.mod")
if _, err := os.Stat(goModPath); err == nil {
return goModPath
}
parentDir := filepath.Dir(currentDir)
if parentDir == currentDir {
break
}
currentDir = parentDir
}
return ""
}