package filecache
import (
+ "encoding/json"
"errors"
"fmt"
"path"
IsResourceDir bool `json:"-"`
}
+// MarshalJSON marshals FileCacheConfig to JSON with MaxAge as a human-readable string.
+func (c FileCacheConfig) MarshalJSON() ([]byte, error) {
+ var maxAge any
+ if c.MaxAge == -1 {
+ maxAge = -1
+ } else {
+ maxAge = strings.TrimSuffix(c.MaxAge.String(), "0m0s")
+ }
+ return json.Marshal(&struct {
+ MaxAge any `json:"maxAge"`
+ Dir string `json:"dir"`
+ }{
+ MaxAge: maxAge,
+ Dir: c.Dir,
+ })
+}
+
// GetJSONCache gets the file cache for getJSON.
func (f Caches) GetJSONCache() *Cache {
return f[CacheKeyGetJSON]
package filecache_test
import (
+ "encoding/json"
"path/filepath"
"runtime"
"testing"
c.Assert(imgConfig.IsResourceDir, qt.Equals, true)
c.Assert(jsonConfig.IsResourceDir, qt.Equals, false)
}
+
+func TestFileCacheConfigMarshalJSON(t *testing.T) {
+ c := qt.New(t)
+
+ cfg := config.New()
+ cfg.Set("cacheDir", "/cache")
+ cfg.Set("workingDir", "/my/project")
+
+ fs := afero.NewMemMapFs()
+ decoded := testconfig.GetTestConfigs(fs, cfg).Base.Caches
+
+ moduleQueriesConfig := decoded[filecache.CacheKeyModuleQueries]
+ c.Assert(moduleQueriesConfig.MaxAge, qt.Equals, 24*time.Hour)
+
+ b, err := json.Marshal(moduleQueriesConfig)
+ c.Assert(err, qt.IsNil)
+
+ c.Assert(string(b), qt.Contains, `"maxAge":"24h"`)
+ c.Assert(string(b), qt.Not(qt.Contains), "86400000000000")
+ c.Assert(string(b), qt.Not(qt.Contains), "8.64e")
+
+ moduleQueriesConfig.MaxAge = -1
+ b, err = json.Marshal(moduleQueriesConfig)
+ c.Assert(err, qt.IsNil)
+ c.Assert(string(b), qt.Contains, `"maxAge":-1`)
+}