feat(path): allow templates in mapped_locations

resolves #3084
This commit is contained in:
Jan De Dobbeleer 2022-11-16 08:37:25 +01:00 committed by Jan De Dobbeleer
parent f2d926b78c
commit 54672cefdf
4 changed files with 25 additions and 4 deletions

View file

@ -3,7 +3,6 @@ package segments
import (
"oh-my-posh/mock"
"oh-my-posh/properties"
"oh-my-posh/template"
"testing"
"github.com/stretchr/testify/assert"
@ -45,7 +44,7 @@ func TestAWSSegment(t *testing.T) {
Region: "eu-west",
Template: "profile: {{.Profile}}{{if .Region}} in {{.Region}}{{end}}",
},
{Case: "template: invalid", ExpectedString: template.InvalidTemplate, ExpectedEnabled: true, Profile: "c", Template: "{{ .Burp"},
{Case: "template: invalid", ExpectedString: "{{ .Burp", ExpectedEnabled: true, Profile: "c", Template: "{{ .Burp"},
}
for _, tc := range cases {

View file

@ -394,9 +394,22 @@ func (pt *Path) replaceMappedLocations() (string, string) {
// mapped locations can override predefined locations
keyValues := pt.props.GetKeyValueMap(MappedLocations, make(map[string]string))
for key, val := range keyValues {
if key != "" {
mappedLocations[pt.normalize(key)] = val
if len(key) == 0 {
continue
}
tmpl := &template.Text{
Template: key,
Context: pt,
Env: pt.env,
}
path, err := tmpl.Render()
if err != nil {
pt.env.Log(platform.Error, "replaceMappedLocations", err.Error())
}
if len(path) == 0 {
continue
}
mappedLocations[pt.normalize(path)] = val
}
// sort map keys in reverse order

View file

@ -842,6 +842,7 @@ func TestFullPathCustomMappedLocations(t *testing.T) {
PathSeparator string
Expected string
}{
{Pwd: "/a/b/c/d", MappedLocations: map[string]string{"{{ .Env.HOME }}/d": "#"}, Expected: "#"},
{Pwd: "/a/b/c/d", MappedLocations: map[string]string{"/a/b/c/d": "#"}, Expected: "#"},
{Pwd: "\\a\\b\\c\\d", MappedLocations: map[string]string{"\\a\\b": "#"}, GOOS: platform.WINDOWS, PathSeparator: "\\", Expected: "#\\c\\d"},
{Pwd: "/a/b/c/d", MappedLocations: map[string]string{"/a/b": "#"}, Expected: "#/c/d"},
@ -868,6 +869,11 @@ func TestFullPathCustomMappedLocations(t *testing.T) {
}
env.On("Flags").Return(args)
env.On("Shell").Return(shell.PLAIN)
env.On("TemplateCache").Return(&platform.TemplateCache{
Env: map[string]string{
"HOME": "/a/b/c",
},
})
path := &Path{
env: env,
props: properties.Map{

View file

@ -42,6 +42,9 @@ func (c *Context) init(t *Text) {
}
func (t *Text) Render() (string, error) {
if !strings.Contains(t.Template, "{{") || !strings.Contains(t.Template, "}}") {
return t.Template, nil
}
t.cleanTemplate()
tmpl, err := template.New(t.Template).Funcs(funcMap()).Parse(t.Template)
if err != nil {