feat: cfg.TerminalBackground as template

This commit is contained in:
Jan De Dobbeleer 2021-04-01 20:28:05 +02:00 committed by Jan De Dobbeleer
parent 0554cb31e9
commit 64aa66eebc
5 changed files with 49 additions and 2 deletions

View file

@ -21,6 +21,8 @@ const (
FullPath ConsoleTitleStyle = "path"
// Template allows a more powerful custom string
Template ConsoleTitleStyle = "template"
templateEnvRegex = `\.Env\.(?P<ENV>[^ \.}]*)`
)
func (t *consoleTitle) getConsoleTitle() string {
@ -53,7 +55,7 @@ func (t *consoleTitle) getTemplateText() string {
// load environment variables into the map
envVars := map[string]string{}
matches := findAllNamedRegexMatch(`\.Env\.(?P<ENV>[^ \.}]*)`, t.config.ConsoleTitleTemplate)
matches := findAllNamedRegexMatch(templateEnvRegex, t.config.ConsoleTitleTemplate)
for _, match := range matches {
envVars[match["ENV"]] = t.env.getenv(match["ENV"])
}

View file

@ -154,7 +154,7 @@ func main() {
}
colorer := &AnsiColor{
formats: formats,
terminalBackground: cfg.TerminalBackground,
terminalBackground: getConsoleBackgroundColor(env, cfg.TerminalBackground),
}
title := &consoleTitle{
env: env,
@ -219,3 +219,23 @@ func getShellInitScript(executable, configFile, script string) string {
script = strings.ReplaceAll(script, "::CONFIG::", configFile)
return script
}
func getConsoleBackgroundColor(env environmentInfo, backgroundColorTemplate string) string {
if len(backgroundColorTemplate) == 0 {
return backgroundColorTemplate
}
context := struct {
Env map[string]string
}{
Env: map[string]string{},
}
matches := findAllNamedRegexMatch(templateEnvRegex, backgroundColorTemplate)
for _, match := range matches {
context.Env[match["ENV"]] = env.getenv(match["ENV"])
}
template := &textTemplate{
Template: backgroundColorTemplate,
Context: context,
}
return template.render()
}

25
src/main_test.go Normal file
View file

@ -0,0 +1,25 @@
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestConsoleBackgroundColorTemplate(t *testing.T) {
cases := []struct {
Case string
Expected string
Term string
}{
{Case: "Inside vscode", Expected: "#123456", Term: "vscode"},
{Case: "Outside vscode", Expected: "", Term: "windowsterminal"},
}
for _, tc := range cases {
env := new(MockedEnvironment)
env.On("getenv", "TERM_PROGRAM").Return(tc.Term)
color := getConsoleBackgroundColor(env, "{{ if eq \"vscode\" .Env.TERM_PROGRAM }}#123456{{end}}")
assert.Equal(t, tc.Expected, color, tc.Case)
}
}