From a5aad7b058768458f6c6e463b300ab0344e11e00 Mon Sep 17 00:00:00 2001 From: Jan De Dobbeleer Date: Sun, 20 Nov 2022 13:59:32 +0100 Subject: [PATCH] feat(templates): allow querying the segment cache resolves #3103 --- src/platform/shell.go | 9 +++++++- src/template/text_test.go | 28 ++++++++++++++++++++++++ website/docs/configuration/templates.mdx | 6 +++++ 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/platform/shell.go b/src/platform/shell.go index f7519662..4b2ac1c4 100644 --- a/src/platform/shell.go +++ b/src/platform/shell.go @@ -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{}) { diff --git a/src/template/text_test.go b/src/template/text_test.go index 233d3d62..470320dc 100644 --- a/src/template/text_test.go +++ b/src/template/text_test.go @@ -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) + } +} diff --git a/website/docs/configuration/templates.mdx b/website/docs/configuration/templates.mdx index 84a03bc2..57c90a85 100644 --- a/website/docs/configuration/templates.mdx +++ b/website/docs/configuration/templates.mdx @@ -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: