-
Notifications
You must be signed in to change notification settings - Fork 0
/
4_path_param.go
110 lines (96 loc) · 2.28 KB
/
4_path_param.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
108
109
110
package moontpl
import (
"path/filepath"
"regexp"
"sort"
"strings"
)
type pathParams map[string]string
func getPathParams(filename string) pathParams {
re := regexp.MustCompile(`\[.*?\]`)
matched := re.FindString(filename)
result := map[string]string{}
if len(matched) == 0 {
return result
}
for _, s := range strings.Split(matched[1:len(matched)-1], ",") {
i := strings.Index(s, "=")
if i < 0 {
continue
}
key := strings.TrimSpace(s[0:i])
value := strings.TrimSpace(s[i+1:])
result[key] = value
}
return result
}
func extractPathParams(filename string) (pathParams, string) {
re := regexp.MustCompile(`\[.*?\]`)
matched := re.FindString(filename)
result := map[string]string{}
if len(matched) == 0 {
return result, filename
}
for _, s := range strings.Split(matched[1:len(matched)-1], ",") {
i := strings.Index(s, "=")
if i < 0 {
continue
}
key := strings.TrimSpace(s[0:i])
value := strings.TrimSpace(s[i+1:])
result[key] = value
}
return result, re.ReplaceAllString(filename, "")
}
func setPathParams(filename string, params pathParams, clear bool) string {
if len(params) == 0 {
return filename
}
re := regexp.MustCompile(`\[.*?\]`)
matched := re.FindString(filename)
filename = re.ReplaceAllString(filename, "")
tmp := map[string]string{}
if len(matched) > 0 && !clear {
for _, s := range strings.Split(matched[1:len(matched)-1], ",") {
i := strings.Index(s, "=")
if i < 0 {
continue
}
key := strings.TrimSpace(s[0:i])
value := strings.TrimSpace(s[i+1:])
tmp[key] = value
}
}
for k, v := range params {
tmp[k] = v
}
keys := []string{}
for k := range tmp {
keys = append(keys, k)
}
sort.Strings(keys)
buf := []string{}
for _, k := range keys {
buf = append(buf, k+"="+tmp[k])
}
paramsStr := "[" + strings.Join(buf, ",") + "]"
dotIndex := strings.Index(filename, ".")
if dotIndex < 0 {
dotIndex = len(filename)
}
result := filename[0:dotIndex] + paramsStr + filename[dotIndex:]
return result
}
func hasPathParams(filename string) bool {
matched, err := regexp.MatchString(`\[.+?\]`, filename)
if err != nil {
panic(err)
}
return matched
}
func relativeFrom(targetLink, srcPage string) string {
if !filepath.IsAbs(targetLink) {
return targetLink
}
return mustRel(filepath.Dir(srcPage), targetLink)
}