Debian Codegraph @

cache/filecache/filecache_config.go

raw
1 // Copyright 2018 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 filecache provides a file based cache for Hugo.
15 package filecache
16
17 import (
18 "encoding/json"
19 "errors"
20 "fmt"
21 "path"
22 "path/filepath"
23 "strings"
24 "time"
25
26 "github.com/gohugoio/hugo/common/hmaps"
27 "github.com/gohugoio/hugo/config"
28
29 "github.com/mitchellh/mapstructure"
30 "github.com/spf13/afero"
31 )
32
33 const (
34 resourcesGenDir = ":resourceDir/_gen"
35 cacheDirProject = ":cacheDir/:project"
36 )
37
38 const (
39 CacheKeyImages = "images"
40 CacheKeyAssets = "assets"
41 CacheKeyModules = "modules"
42 CacheKeyModuleQueries = "modulequeries"
43 CacheKeyModuleGitInfo = "modulegitinfo"
44 CacheKeyGetResource = "getresource"
45 CacheKeyMisc = "misc"
46 )
47
48 type Configs map[string]FileCacheConfig
49
50 // CacheDirModules returns the compiled path to the modules cache.
51 // For internal use.
52 func (c Configs) CacheDirModules() string {
53 return c[CacheKeyModules].DirCompiled
54 }
55
56 // CacheDirMisc returns the compiled path to the misc cache.
57 // For internal use.
58 func (c Configs) CacheDirMisc() string {
59 return c[CacheKeyMisc].DirCompiled
60 }
61
62 var defaultCacheConfigs = Configs{
63 CacheKeyModules: {
64 MaxAge: -1,
65 Dir: ":cacheDir/modules",
66 fileCacheConfigInternal: fileCacheConfigInternal{
67 entryIsDir: true,
68 isReadOnly: true, // we need to make it writable when pruning.
69 },
70 },
71 CacheKeyModuleQueries: {
72 MaxAge: 24 * time.Hour,
73 Dir: ":cacheDir/modules",
74 },
75 CacheKeyModuleGitInfo: {
76 MaxAge: 24 * time.Hour,
77 Dir: ":cacheDir/modules",
78 fileCacheConfigInternal: fileCacheConfigInternal{
79 entryIsDir: true,
80 },
81 },
82 CacheKeyImages: {
83 MaxAge: -1,
84 Dir: resourcesGenDir,
85 },
86 CacheKeyAssets: {
87 MaxAge: -1,
88 Dir: resourcesGenDir,
89 },
90 CacheKeyGetResource: {
91 MaxAge: -1, // Never expire
92 Dir: cacheDirProject,
93 },
94 CacheKeyMisc: {
95 MaxAge: -1,
96 Dir: cacheDirProject,
97 },
98 }
99
100 func init() {
101 for k, v := range defaultCacheConfigs {
102 v.name = k
103 defaultCacheConfigs[k] = v
104 }
105 }
106
107 type FileCacheConfig struct {
108 // Max age of cache entries in this cache. Any items older than this will
109 // be removed and not returned from the cache.
110 // A negative value means forever, 0 means cache is disabled.
111 // Hugo is lenient with what types it accepts here, but we recommend using
112 // a duration string, a sequence of decimal numbers, each with optional fraction and a unit suffix,
113 // such as "300ms", "1.5h" or "2h45m".
114 // Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
115 MaxAge time.Duration
116
117 // The directory where files are stored.
118 Dir string
119
120 fileCacheConfigInternal `json:"-"`
121 }
122
123 func (cfg *FileCacheConfig) init() error {
124 if cfg.DirCompiled == "" {
125 // From unit tests. Just check that it does not contain any placeholders.
126 if strings.Contains(cfg.Dir, ":") {
127 return fmt.Errorf("cache dir %q contains unresolved placeholders", cfg.Dir)
128 }
129 cfg.DirCompiled = cfg.Dir
130 }
131 // Sanity check the config.
132 if len(cfg.DirCompiled) < 5 {
133 panic(fmt.Sprintf("invalid cache dir: %q", cfg.DirCompiled))
134 }
135 return nil
136 }
137
138 type fileCacheConfigInternal struct {
139 DirCompiled string
140
141 name string // The name of this cache, e.g. "images", "modules" etc.
142 entryIsDir bool // when set, the cache entries represents directories directly below the base dir.
143 isReadOnly bool // when set, the cache is read only and needs to be pruned differently. This is used for the Go modules cache.
144 IsResourceDir bool // resources/_gen will get its own composite filesystem that also checks any theme. TODO(bep) unexport this.
145 }
146
147 // MarshalJSON marshals FileCacheConfig to JSON with MaxAge as a human-readable string.
148 func (c FileCacheConfig) MarshalJSON() ([]byte, error) {
149 var maxAge any
150 if c.MaxAge == -1 {
151 maxAge = -1
152 } else {
153 maxAge = strings.TrimSuffix(c.MaxAge.String(), "0m0s")
154 }
155 return json.Marshal(&struct {
156 MaxAge any `json:"maxAge"`
157 Dir string `json:"dir"`
158 }{
159 MaxAge: maxAge,
160 Dir: c.Dir,
161 })
162 }
163
164 // ImageCache gets the file cache for processed images.
165 func (f Caches) ImageCache() *Cache {
166 return f[CacheKeyImages]
167 }
168
169 // ModulesCache gets the file cache for Hugo Modules.
170 func (f Caches) ModulesCache() *Cache {
171 return f[CacheKeyModules]
172 }
173
174 // ModuleQueriesCache gets the file cache for Hugo Module version queries.
175 // Returns nil if not found.
176 func (f Caches) ModuleQueriesCache() *Cache {
177 c, ok := f[CacheKeyModuleQueries]
178 if !ok {
179 panic("module queries cache not set")
180 }
181 return c
182 }
183
184 // ModuleGitInfoCache gets the file cache for Hugo Module git info.
185 func (f Caches) ModuleGitInfoCache() *Cache {
186 c, ok := f[CacheKeyModuleGitInfo]
187 if !ok {
188 panic("module git info cache not set")
189 }
190 return c
191 }
192
193 // AssetsCache gets the file cache for assets (processed resources, SCSS etc.).
194 func (f Caches) AssetsCache() *Cache {
195 return f[CacheKeyAssets]
196 }
197
198 // MiscCache gets the file cache for miscellaneous stuff.
199 func (f Caches) MiscCache() *Cache {
200 return f[CacheKeyMisc]
201 }
202
203 // GetResourceCache gets the file cache for remote resources.
204 func (f Caches) GetResourceCache() *Cache {
205 return f[CacheKeyGetResource]
206 }
207
208 func DecodeConfig(fs afero.Fs, bcfg config.BaseConfig, m map[string]any) (Configs, error) {
209 c := make(Configs)
210 valid := make(map[string]bool)
211 // Add defaults
212 for k, v := range defaultCacheConfigs {
213 c[k] = v
214 valid[k] = true
215 }
216
217 _, isOsFs := fs.(*afero.OsFs)
218
219 for k, v := range m {
220 if _, ok := v.(hmaps.Params); !ok {
221 continue
222 }
223 var ok bool
224 cc, ok := c[k]
225 if !ok {
226 return nil, fmt.Errorf("%q is not a valid cache name", k)
227 }
228
229 dc := &mapstructure.DecoderConfig{
230 Result: &cc,
231 DecodeHook: mapstructure.StringToTimeDurationHookFunc(),
232 WeaklyTypedInput: true,
233 }
234
235 decoder, err := mapstructure.NewDecoder(dc)
236 if err != nil {
237 return c, err
238 }
239
240 if err := decoder.Decode(v); err != nil {
241 return nil, fmt.Errorf("failed to decode filecache config: %w", err)
242 }
243
244 if cc.Dir == "" {
245 return c, errors.New("must provide cache Dir")
246 }
247
248 c[k] = cc
249
250 }
251
252 for k, v := range c {
253 dir := filepath.ToSlash(filepath.Clean(v.Dir))
254 hadSlash := strings.HasPrefix(dir, "/")
255 parts := strings.Split(dir, "/")
256
257 for i, part := range parts {
258 if strings.HasPrefix(part, ":") {
259 resolved, isResource, err := resolveDirPlaceholder(fs, bcfg, part)
260 if err != nil {
261 return c, err
262 }
263 if isResource {
264 v.IsResourceDir = true
265 }
266 parts[i] = resolved
267 }
268 }
269
270 dir = path.Join(parts...)
271 if hadSlash {
272 dir = "/" + dir
273 }
274 v.DirCompiled = filepath.Clean(filepath.FromSlash(dir))
275
276 if !v.IsResourceDir {
277 if isOsFs && !filepath.IsAbs(v.DirCompiled) {
278 return c, fmt.Errorf("%q must resolve to an absolute directory", v.DirCompiled)
279 }
280
281 // Avoid cache in root, e.g. / (Unix) or c:\ (Windows)
282 if len(strings.TrimPrefix(v.DirCompiled, filepath.VolumeName(v.DirCompiled))) == 1 {
283 return c, fmt.Errorf("%q is a root folder and not allowed as cache dir", v.DirCompiled)
284 }
285 }
286
287 if !strings.HasPrefix(v.DirCompiled, "_gen") {
288 // We do cache eviction (file removes) and since the user can set
289 // his/hers own cache directory, we really want to make sure
290 // we do not delete any files that do not belong to this cache.
291 // We do add the cache name as the root, but this is an extra safe
292 // guard. We skip the files inside /resources/_gen/ because
293 // that would be breaking.
294 v.DirCompiled = filepath.Join(v.DirCompiled, FilecacheRootDirname, k)
295 } else {
296 v.DirCompiled = filepath.Join(v.DirCompiled, k)
297 }
298
299 c[k] = v
300 }
301
302 return c, nil
303 }
304
305 // Resolves :resourceDir => /myproject/resources etc., :cacheDir => ...
306 func resolveDirPlaceholder(fs afero.Fs, bcfg config.BaseConfig, placeholder string) (cacheDir string, isResource bool, err error) {
307 switch strings.ToLower(placeholder) {
308 case ":resourcedir":
309 return "", true, nil
310 case ":cachedir":
311 return bcfg.CacheDir, false, nil
312 case ":project":
313 return filepath.Base(bcfg.WorkingDir), false, nil
314 }
315
316 return "", false, fmt.Errorf("%q is not a valid placeholder (valid values are :cacheDir or :resourceDir)", placeholder)
317 }