oh-my-posh/src/console_title.go

74 lines
1.7 KiB
Go
Raw Normal View History

2020-12-26 10:21:26 -08:00
package main
2020-12-27 02:56:33 -08:00
import (
"fmt"
2021-01-13 18:30:14 -08:00
"strings"
2020-12-27 02:56:33 -08:00
)
2020-12-26 10:21:26 -08:00
type consoleTitle struct {
env environmentInfo
settings *Settings
2020-12-26 10:51:21 -08:00
formats *ansiFormats
2020-12-26 10:21:26 -08:00
}
// ConsoleTitleStyle defines how to show the title in the console window
type ConsoleTitleStyle string
const (
// FolderName show the current folder name
FolderName ConsoleTitleStyle = "folder"
// FullPath show the current path
FullPath ConsoleTitleStyle = "path"
2020-12-27 02:56:33 -08:00
// Template allows a more powerful custom string
Template ConsoleTitleStyle = "template"
2020-12-26 10:21:26 -08:00
)
func (t *consoleTitle) getConsoleTitle() string {
2020-12-26 10:51:21 -08:00
var title string
2020-12-26 10:21:26 -08:00
switch t.settings.ConsoleTitleStyle {
case FullPath:
2021-01-13 18:30:14 -08:00
title = t.getPwd()
2020-12-27 02:56:33 -08:00
case Template:
title = t.getTemplateText()
2020-12-26 10:21:26 -08:00
case FolderName:
fallthrough
default:
2021-01-13 18:30:14 -08:00
title = base(t.getPwd(), t.env)
2020-12-26 10:21:26 -08:00
}
2020-12-26 10:51:21 -08:00
return fmt.Sprintf(t.formats.title, title)
2020-12-26 10:21:26 -08:00
}
2020-12-27 02:56:33 -08:00
func (t *consoleTitle) getTemplateText() string {
2021-01-13 17:11:47 -08:00
context := make(map[string]interface{})
context["Root"] = t.env.isRunningAsRoot()
context["Path"] = t.getPwd()
context["Folder"] = base(t.getPwd(), t.env)
context["Shell"] = t.env.getShellName()
context["User"] = t.env.getCurrentUser()
context["Host"] = ""
if host, err := t.env.getHostName(); err == nil {
context["Host"] = host
}
2021-01-13 17:11:47 -08:00
// load environment variables into the map
envVars := map[string]string{}
matches := findAllNamedRegexMatch(`\.Env\.(?P<ENV>[^ \.}]*)`, t.settings.ConsoleTitleTemplate)
for _, match := range matches {
envVars[match["ENV"]] = t.env.getenv(match["ENV"])
2020-12-27 02:56:33 -08:00
}
2021-01-13 17:11:47 -08:00
context["Env"] = envVars
2021-02-07 01:54:36 -08:00
template := &textTemplate{
Template: t.settings.ConsoleTitleTemplate,
Context: context,
2020-12-27 02:56:33 -08:00
}
2021-02-07 01:54:36 -08:00
return template.render()
2020-12-27 02:56:33 -08:00
}
2021-01-13 18:30:14 -08:00
func (t *consoleTitle) getPwd() string {
pwd := t.env.getcwd()
pwd = strings.Replace(pwd, t.env.homeDir(), "~", 1)
return pwd
}