Debian Codegraph @

hugofs/hglob/glob.go

raw
1 // Copyright 2021 The Hugo Authors. 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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package hglob
15
16 import (
17 "os"
18 "path"
19 "path/filepath"
20 "runtime"
21 "strings"
22
23 "github.com/gobwas/glob"
24 "github.com/gobwas/glob/syntax"
25 "github.com/gohugoio/hugo/common/hmaps"
26 "github.com/gohugoio/hugo/identity"
27 )
28
29 const filepathSeparator = string(os.PathSeparator)
30
31 var (
32 isWindows = runtime.GOOS == "windows"
33 defaultGlobCache = &pathGlobCache{
34 isWindows: isWindows,
35 cache: hmaps.NewCache[string, globErr](),
36 }
37 dotGlobCache = hmaps.NewCache[string, globErr]()
38 )
39
40 type globErr struct {
41 glob glob.Glob
42 err error
43 }
44
45 type pathGlobCache struct {
46 // Config
47 isWindows bool
48
49 // Cache
50 cache *hmaps.Cache[string, globErr]
51 }
52
53 // GetGlobDot returns a glob.Glob that matches the given pattern, using '.' as the path separator.
54 func GetGlobDot(pattern string) (glob.Glob, error) {
55 v, err := dotGlobCache.GetOrCreate(pattern, func() (globErr, error) {
56 g, err := glob.Compile(pattern, '.')
57 return globErr{
58 glob: g,
59 err: err,
60 }, nil
61 })
62 if err != nil {
63 return nil, err
64 }
65
66 return v.glob, v.err
67 }
68
69 func (gc *pathGlobCache) GetGlob(pattern string) (glob.Glob, error) {
70 v, err := gc.cache.GetOrCreate(pattern, func() (globErr, error) {
71 pattern = filepath.ToSlash(pattern)
72 g, err := glob.Compile(strings.ToLower(pattern), '/')
73 return globErr{
74 glob: globDecorator{
75 isWindows: gc.isWindows,
76 g: g,
77 },
78 err: err,
79 }, nil
80 })
81 if err != nil {
82 return nil, err
83 }
84
85 return v.glob, v.err
86 }
87
88 // Or creates a new Glob from the given globs.
89 func Or(globs ...glob.Glob) glob.Glob {
90 return globSlice{globs: globs}
91 }
92
93 // MatchesFunc is a convenience type to create a glob.Glob from a function.
94 type MatchesFunc func(s string) bool
95
96 func (m MatchesFunc) Match(s string) bool {
97 return m(s)
98 }
99
100 type globSlice struct {
101 globs []glob.Glob
102 }
103
104 func (g globSlice) Match(s string) bool {
105 for _, g := range g.globs {
106 if g.Match(s) {
107 return true
108 }
109 }
110 return false
111 }
112
113 type globDecorator struct {
114 // On Windows we may get filenames with Windows slashes to match,
115 // which we need to normalize.
116 isWindows bool
117
118 g glob.Glob
119 }
120
121 func (g globDecorator) Match(s string) bool {
122 if g.isWindows {
123 s = filepath.ToSlash(s)
124 }
125 s = strings.ToLower(s)
126 return g.g.Match(s)
127 }
128
129 func GetGlob(pattern string) (glob.Glob, error) {
130 return defaultGlobCache.GetGlob(pattern)
131 }
132
133 func NormalizePath(p string) string {
134 return strings.ToLower(NormalizePathNoLower(p))
135 }
136
137 func NormalizePathNoLower(p string) string {
138 return strings.Trim(path.Clean(filepath.ToSlash(p)), "/.")
139 }
140
141 // ResolveRootDir takes a normalized path on the form "assets/**.json" and
142 // determines any root dir, i.e. any start path without any wildcards.
143 func ResolveRootDir(p string) string {
144 parts := strings.Split(path.Dir(p), "/")
145 var roots []string
146 for _, part := range parts {
147 if HasGlobChar(part) {
148 break
149 }
150 roots = append(roots, part)
151 }
152
153 if len(roots) == 0 {
154 return ""
155 }
156
157 return strings.Join(roots, "/")
158 }
159
160 // FilterGlobParts removes any string with glob wildcard.
161 func FilterGlobParts(a []string) []string {
162 b := a[:0]
163 for _, x := range a {
164 if !HasGlobChar(x) {
165 b = append(b, x)
166 }
167 }
168 return b
169 }
170
171 // HasGlobChar returns whether s contains any glob wildcards.
172 func HasGlobChar(s string) bool {
173 for i := range len(s) {
174 if syntax.Special(s[i]) {
175 return true
176 }
177 }
178 return false
179 }
180
181 // NewGlobIdentity creates a new Identity that
182 // is probably dependent on any other Identity
183 // that matches the given pattern.
184 func NewGlobIdentity(pattern string) identity.Identity {
185 glob, err := GetGlob(pattern)
186 if err != nil {
187 panic(err)
188 }
189
190 predicate := func(other identity.Identity) bool {
191 return glob.Match(other.IdentifierBase())
192 }
193
194 return identity.NewPredicateIdentity(predicate, nil)
195 }