feat(templates): allow querying the segment cache

resolves #3103
This commit is contained in:
Jan De Dobbeleer 2022-11-20 13:59:32 +01:00 committed by Jan De Dobbeleer
parent 0d8b8591cc
commit a5aad7b058
3 changed files with 42 additions and 1 deletions

View file

@ -130,6 +130,13 @@ type Connection struct {
SSID string // Wi-Fi only
}
type SegmentsCache map[string]interface{}
func (c *SegmentsCache) Contains(key string) bool {
_, ok := (*c)[key]
return ok
}
type TemplateCache struct {
Root bool
PWD string
@ -142,7 +149,7 @@ type TemplateCache struct {
Env map[string]string
OS string
WSL bool
Segments map[string]interface{}
Segments SegmentsCache
}
func (t *TemplateCache) AddSegmentData(key string, value interface{}) {

View file

@ -284,3 +284,31 @@ func TestCleanTemplate(t *testing.T) {
assert.Equal(t, tc.Expected, tmpl.Template, tc.Case)
}
}
func TestSegmentContains(t *testing.T) {
cases := []struct {
Case string
Expected string
Template string
}{
{Case: "match", Expected: "hello", Template: `{{ if .Segments.Contains "Git" }}hello{{ end }}`},
{Case: "match", Expected: "world", Template: `{{ if .Segments.Contains "Path" }}hello{{ else }}world{{ end }}`},
}
env := &mock.MockedEnvironment{}
env.On("TemplateCache").Return(&platform.TemplateCache{
Env: make(map[string]string),
Segments: map[string]interface{}{
"Git": nil,
},
})
for _, tc := range cases {
tmpl := &Text{
Template: tc.Template,
Context: nil,
Env: env,
}
text, _ := tmpl.Render()
assert.Equal(t, tc.Expected, text, tc.Case)
}
}

View file

@ -189,6 +189,12 @@ to distinct between both. For example:
```
:::
If you want to know if a specific segment is active, you can use the `.Segments.Contains` function, for example:
```json
"template": "{{ if .Segments.Contains \"Git\" }}\uf7d3{{ else if gt .Code 0 }}\uf00d{{ else }}\uf00c{{ end }} "
```
## Text decoration
You can make use of the following syntax to decorate text: