fix(template): save Segments correctly

resolves #4143
This commit is contained in:
Jan De Dobbeleer 2023-08-08 09:09:05 +02:00 committed by Jan De Dobbeleer
parent 50d98f5e68
commit 328601be78
5 changed files with 34 additions and 20 deletions

View file

@ -56,7 +56,7 @@ func (fc *fileCache) Close() {
if !fc.dirty {
return
}
cache := fc.cache.List()
cache := fc.cache.SimpleMap()
if dump, err := json.MarshalIndent(cache, "", " "); err == nil {
cacheFilePath := filepath.Join(fc.cachePath, CacheFile)
_ = os.WriteFile(cacheFilePath, dump, 0644)

View file

@ -26,7 +26,7 @@ func (cm *ConcurrentMap) Contains(key string) bool {
return ok
}
func (cm *ConcurrentMap) List() map[string]any {
func (cm *ConcurrentMap) SimpleMap() SimpleMap {
list := make(map[string]any)
(*sync.Map)(cm).Range(func(key, value any) bool {
list[key.(string)] = value
@ -34,3 +34,13 @@ func (cm *ConcurrentMap) List() map[string]any {
})
return list
}
type SimpleMap map[string]any
func (m SimpleMap) ConcurrentMap() *ConcurrentMap {
var cm ConcurrentMap
for k, v := range m {
cm.Set(k, v)
}
return &cm
}

View file

@ -168,21 +168,22 @@ type SystemInfo struct {
}
type TemplateCache struct {
Root bool
PWD string
Folder string
Shell string
ShellVersion string
UserName string
HostName string
Code int
Env map[string]string
Var map[string]interface{}
OS string
WSL bool
PromptCount int
SHLVL int
Segments *ConcurrentMap
Root bool
PWD string
Folder string
Shell string
ShellVersion string
UserName string
HostName string
Code int
Env map[string]string
Var SimpleMap
OS string
WSL bool
PromptCount int
SHLVL int
Segments *ConcurrentMap
SegmentsCache SimpleMap
initialized bool
sync.RWMutex
@ -745,7 +746,9 @@ func (env *Shell) saveTemplateCache() {
if !canSave {
return
}
templateCache, err := json.Marshal(env.TemplateCache())
cache := env.TemplateCache()
cache.SegmentsCache = cache.Segments.SimpleMap()
templateCache, err := json.Marshal(cache)
if err == nil {
env.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440)
}
@ -769,6 +772,7 @@ func (env *Shell) LoadTemplateCache() {
env.Error(err)
return
}
tmplCache.Segments = tmplCache.SegmentsCache.ConcurrentMap()
tmplCache.initialized = true
env.tmplCache = &tmplCache
}

View file

@ -163,7 +163,7 @@ func (t *Text) cleanTemplate() {
// as we can't provide a clean way to access the list
// of segments, we need to replace the property with
// the list of segments so they can be accessed directly
property = strings.Replace(property, ".Segments", ".Segments.List", 1)
property = strings.Replace(property, ".Segments", ".Segments.SimpleMap", 1)
result += property
} else {
// check if we have the same property in Data

View file

@ -327,7 +327,7 @@ func TestCleanTemplate(t *testing.T) {
},
{
Case: "Replace a direct call to .Segments with .Segments.List",
Expected: `{{.Segments.List.Git.Repo}}`,
Expected: `{{.Segments.SimpleMap.Git.Repo}}`,
Template: `{{.Segments.Git.Repo}}`,
},
}