refactor: move properties logic to module

This commit is contained in:
Jan De Dobbeleer 2022-01-26 13:53:35 +01:00 committed by Jan De Dobbeleer
parent c86b7b62bc
commit bdd13cb32f
91 changed files with 543 additions and 421 deletions

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/color" "oh-my-posh/color"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"sync" "sync"
"time" "time"
) )
@ -122,9 +123,9 @@ func (b *Block) renderSegment(segment *Segment) {
func (b *Block) renderText(text string) { func (b *Block) renderText(text string) {
defaultValue := " " defaultValue := " "
b.writer.Write(b.activeBackground, b.activeForeground, b.activeSegment.getValue(Prefix, defaultValue)) b.writer.Write(b.activeBackground, b.activeForeground, b.activeSegment.getValue(properties.Prefix, defaultValue))
b.writer.Write(b.activeBackground, b.activeForeground, text) b.writer.Write(b.activeBackground, b.activeForeground, text)
b.writer.Write(b.activeBackground, b.activeForeground, b.activeSegment.getValue(Postfix, defaultValue)) b.writer.Write(b.activeBackground, b.activeForeground, b.activeSegment.getValue(properties.Postfix, defaultValue))
} }
func (b *Block) writePowerline(final bool) { func (b *Block) writePowerline(final bool) {

View file

@ -9,6 +9,7 @@ import (
"fmt" "fmt"
"oh-my-posh/color" "oh-my-posh/color"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"os" "os"
"strconv" "strconv"
"strings" "strings"
@ -49,7 +50,7 @@ type TransientPrompt struct {
const ( const (
// HTTPTimeout timeout used when executing http request // HTTPTimeout timeout used when executing http request
HTTPTimeout Property = "http_timeout" HTTPTimeout properties.Property = "http_timeout"
// DefaultHTTPTimeout default timeout used when executing http request // DefaultHTTPTimeout default timeout used when executing http request
DefaultHTTPTimeout = 20 DefaultHTTPTimeout = 20
// DefaultCacheTimeout default timeout used when caching data // DefaultCacheTimeout default timeout used when caching data
@ -195,9 +196,9 @@ func getDefaultConfig(info string) *Config {
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#ff479c", Background: "#ff479c",
Foreground: "#ffffff", Foreground: "#ffffff",
Properties: properties{ Properties: properties.Map{
Prefix: " \uE5FF ", properties.Prefix: " \uE5FF ",
Style: "folder", properties.Style: "folder",
}, },
}, },
{ {
@ -206,7 +207,7 @@ func getDefaultConfig(info string) *Config {
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#fffb38", Background: "#fffb38",
Foreground: "#193549", Foreground: "#193549",
Properties: properties{ Properties: properties.Map{
FetchStashCount: true, FetchStashCount: true,
FetchUpstreamIcon: true, FetchUpstreamIcon: true,
}, },
@ -217,8 +218,8 @@ func getDefaultConfig(info string) *Config {
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#f36943", Background: "#f36943",
Foreground: "#193549", Foreground: "#193549",
Properties: properties{ Properties: properties.Map{
Postfix: "\uF295 ", properties.Postfix: "\uF295 ",
}, },
}, },
{ {
@ -227,9 +228,9 @@ func getDefaultConfig(info string) *Config {
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#6CA35E", Background: "#6CA35E",
Foreground: "#ffffff", Foreground: "#ffffff",
Properties: properties{ Properties: properties.Map{
Prefix: " \uE718", properties.Prefix: " \uE718",
FetchVersion: false, properties.FetchVersion: false,
}, },
}, },
{ {
@ -238,8 +239,8 @@ func getDefaultConfig(info string) *Config {
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#0077c2", Background: "#0077c2",
Foreground: "#ffffff", Foreground: "#ffffff",
Properties: properties{ Properties: properties.Map{
Prefix: " \uFCB5 ", properties.Prefix: " \uFCB5 ",
}, },
}, },
{ {
@ -255,8 +256,8 @@ func getDefaultConfig(info string) *Config {
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#ffffff", Background: "#ffffff",
Foreground: "#111111", Foreground: "#111111",
Properties: properties{ Properties: properties.Map{
SegmentTemplate: info, properties.SegmentTemplate: info,
}, },
}, },
{ {
@ -266,9 +267,9 @@ func getDefaultConfig(info string) *Config {
Foreground: "#ffffff", Foreground: "#ffffff",
LeadingDiamond: "<transparent,#2e9599>\uE0B0</>", LeadingDiamond: "<transparent,#2e9599>\uE0B0</>",
TrailingDiamond: "\uE0B4", TrailingDiamond: "\uE0B4",
Properties: properties{ Properties: properties.Map{
AlwaysEnabled: true, properties.AlwaysEnabled: true,
Prefix: " \uE23A", properties.Prefix: " \uE23A",
}, },
}, },
}, },

View file

@ -1,4 +1,4 @@
package main package properties
import ( import (
"fmt" "fmt"
@ -51,17 +51,17 @@ const (
RefreshToken Property = "refresh_token" RefreshToken Property = "refresh_token"
) )
type properties map[Property]interface{} type Map map[Property]interface{}
func (p properties) GetString(property Property, defaultValue string) string { func (m Map) GetString(property Property, defaultValue string) string {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
return parseString(val, defaultValue) return ParseString(val, defaultValue)
} }
func parseString(value interface{}, defaultValue string) string { func ParseString(value interface{}, defaultValue string) string {
stringValue, ok := value.(string) stringValue, ok := value.(string)
if !ok { if !ok {
return defaultValue return defaultValue
@ -69,12 +69,12 @@ func parseString(value interface{}, defaultValue string) string {
return stringValue return stringValue
} }
func (p properties) GetColor(property Property, defaultValue string) string { func (m Map) GetColor(property Property, defaultValue string) string {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
colorString := parseString(val, defaultValue) colorString := ParseString(val, defaultValue)
if color.IsAnsiColorName(colorString) { if color.IsAnsiColorName(colorString) {
return colorString return colorString
} }
@ -85,8 +85,8 @@ func (p properties) GetColor(property Property, defaultValue string) string {
return defaultValue return defaultValue
} }
func (p properties) GetBool(property Property, defaultValue bool) bool { func (m Map) GetBool(property Property, defaultValue bool) bool {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
@ -97,8 +97,8 @@ func (p properties) GetBool(property Property, defaultValue bool) bool {
return boolValue return boolValue
} }
func (p properties) GetFloat64(property Property, defaultValue float64) float64 { func (m Map) GetFloat64(property Property, defaultValue float64) float64 {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
@ -116,8 +116,8 @@ func (p properties) GetFloat64(property Property, defaultValue float64) float64
return float64(intValue) return float64(intValue)
} }
func (p properties) GetInt(property Property, defaultValue int) int { func (m Map) GetInt(property Property, defaultValue int) int {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
@ -135,8 +135,8 @@ func (p properties) GetInt(property Property, defaultValue int) int {
return int(intValue) return int(intValue)
} }
func (p properties) GetKeyValueMap(property Property, defaultValue map[string]string) map[string]string { func (m Map) GetKeyValueMap(property Property, defaultValue map[string]string) map[string]string {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
@ -146,18 +146,18 @@ func (p properties) GetKeyValueMap(property Property, defaultValue map[string]st
return keyValues return keyValues
} }
func (p properties) GetStringArray(property Property, defaultValue []string) []string { func (m Map) GetStringArray(property Property, defaultValue []string) []string {
val, found := p[property] val, found := m[property]
if !found { if !found {
return defaultValue return defaultValue
} }
keyValues := parseStringArray(val) keyValues := ParseStringArray(val)
return keyValues return keyValues
} }
func parseStringArray(param interface{}) []string { func ParseStringArray(param interface{}) []string {
switch v := param.(type) { switch v := param.(type) {
default: default:
return []string{} return []string{}
@ -194,7 +194,7 @@ func parseKeyValueArray(param interface{}) map[string]string {
case []interface{}: case []interface{}:
keyValueArray := make(map[string]string) keyValueArray := make(map[string]string)
for _, s := range v { for _, s := range v {
l := parseStringArray(s) l := ParseStringArray(s)
if len(l) == 2 { if len(l) == 2 {
key := l[0] key := l[0]
val := l[1] val := l[1]

View file

@ -1,4 +1,4 @@
package main package properties
import ( import (
"testing" "testing"
@ -14,101 +14,101 @@ const (
) )
func TestGetString(t *testing.T) { func TestGetString(t *testing.T) {
var properties properties = properties{Foo: expected} var properties Map = Map{Foo: expected}
value := properties.GetString(Foo, "err") value := properties.GetString(Foo, "err")
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetStringNoEntry(t *testing.T) { func TestGetStringNoEntry(t *testing.T) {
var properties properties = properties{} var properties Map = Map{}
value := properties.GetString(Foo, expected) value := properties.GetString(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetStringNoTextEntry(t *testing.T) { func TestGetStringNoTextEntry(t *testing.T) {
var properties properties = properties{Foo: true} var properties Map = Map{Foo: true}
value := properties.GetString(Foo, expected) value := properties.GetString(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetHexColor(t *testing.T) { func TestGetHexColor(t *testing.T) {
expected := expectedColor expected := expectedColor
var properties properties = properties{Foo: expected} var properties Map = Map{Foo: expected}
value := properties.GetColor(Foo, "#789123") value := properties.GetColor(Foo, "#789123")
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetColor(t *testing.T) { func TestGetColor(t *testing.T) {
expected := "yellow" expected := "yellow"
var properties properties = properties{Foo: expected} var properties Map = Map{Foo: expected}
value := properties.GetColor(Foo, "#789123") value := properties.GetColor(Foo, "#789123")
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestDefaultColorWithInvalidColorCode(t *testing.T) { func TestDefaultColorWithInvalidColorCode(t *testing.T) {
expected := expectedColor expected := expectedColor
var properties properties = properties{Foo: "invalid"} var properties Map = Map{Foo: "invalid"}
value := properties.GetColor(Foo, expected) value := properties.GetColor(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestDefaultColorWithUnavailableProperty(t *testing.T) { func TestDefaultColorWithUnavailableProperty(t *testing.T) {
expected := expectedColor expected := expectedColor
var properties properties = properties{} var properties Map = Map{}
value := properties.GetColor(Foo, expected) value := properties.GetColor(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetPaletteColor(t *testing.T) { func TestGetPaletteColor(t *testing.T) {
expected := "p:red" expected := "p:red"
var properties properties = properties{Foo: expected} var properties Map = Map{Foo: expected}
value := properties.GetColor(Foo, "white") value := properties.GetColor(Foo, "white")
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetBool(t *testing.T) { func TestGetBool(t *testing.T) {
expected := true expected := true
var properties properties = properties{Foo: expected} var properties Map = Map{Foo: expected}
value := properties.GetBool(Foo, false) value := properties.GetBool(Foo, false)
assert.True(t, value) assert.True(t, value)
} }
func TestGetBoolPropertyNotInMap(t *testing.T) { func TestGetBoolPropertyNotInMap(t *testing.T) {
var properties properties = properties{} var properties Map = Map{}
value := properties.GetBool(Foo, false) value := properties.GetBool(Foo, false)
assert.False(t, value) assert.False(t, value)
} }
func TestGetBoolInvalidProperty(t *testing.T) { func TestGetBoolInvalidProperty(t *testing.T) {
var properties properties = properties{Foo: "borked"} var properties Map = Map{Foo: "borked"}
value := properties.GetBool(Foo, false) value := properties.GetBool(Foo, false)
assert.False(t, value) assert.False(t, value)
} }
func TestGetFloat64(t *testing.T) { func TestGetFloat64(t *testing.T) {
expected := float64(1337) expected := float64(1337)
var properties properties = properties{Foo: expected} var properties Map = Map{Foo: expected}
value := properties.GetFloat64(Foo, 9001) value := properties.GetFloat64(Foo, 9001)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetFloat64PropertyNotInMap(t *testing.T) { func TestGetFloat64PropertyNotInMap(t *testing.T) {
expected := float64(1337) expected := float64(1337)
var properties properties = properties{} var properties Map = Map{}
value := properties.GetFloat64(Foo, expected) value := properties.GetFloat64(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetFloat64InvalidStringProperty(t *testing.T) { func TestGetFloat64InvalidStringProperty(t *testing.T) {
expected := float64(1337) expected := float64(1337)
var properties properties = properties{Foo: "invalid"} var properties Map = Map{Foo: "invalid"}
value := properties.GetFloat64(Foo, expected) value := properties.GetFloat64(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }
func TestGetFloat64InvalidBoolProperty(t *testing.T) { func TestGetFloat64InvalidBoolProperty(t *testing.T) {
expected := float64(1337) expected := float64(1337)
var properties properties = properties{Foo: true} var properties Map = Map{Foo: true}
value := properties.GetFloat64(Foo, expected) value := properties.GetFloat64(Foo, expected)
assert.Equal(t, expected, value) assert.Equal(t, expected, value)
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strings" "strings"
) )
@ -36,20 +37,20 @@ func (s *ScmStatus) String() string {
} }
type scm struct { type scm struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
} }
const ( const (
// BranchMaxLength truncates the length of the branch name // BranchMaxLength truncates the length of the branch name
BranchMaxLength Property = "branch_max_length" BranchMaxLength properties.Property = "branch_max_length"
// TruncateSymbol appends the set symbol to a truncated branch name // TruncateSymbol appends the set symbol to a truncated branch name
TruncateSymbol Property = "truncate_symbol" TruncateSymbol properties.Property = "truncate_symbol"
// FullBranchPath displays the full path of a branch // FullBranchPath displays the full path of a branch
FullBranchPath Property = "full_branch_path" FullBranchPath properties.Property = "full_branch_path"
) )
func (s *scm) init(props Properties, env environment.Environment) { func (s *scm) init(props properties.Properties, env environment.Environment) {
s.props = props s.props = props
s.env = env s.env = env
} }
@ -69,7 +70,7 @@ func (s *scm) truncateBranch(branch string) string {
} }
func (s *scm) shouldIgnoreRootRepository(rootDir string) bool { func (s *scm) shouldIgnoreRootRepository(rootDir string) bool {
excludedFolders := s.props.GetStringArray(ExcludeFolders, []string{}) excludedFolders := s.props.GetStringArray(properties.ExcludeFolders, []string{})
if len(excludedFolders) == 0 { if len(excludedFolders) == 0 {
return false return false
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -106,7 +107,7 @@ func TestTruncateBranch(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
props := properties{ props := properties.Map{
BranchMaxLength: tc.MaxLength, BranchMaxLength: tc.MaxLength,
FullBranchPath: tc.FullBranch, FullBranchPath: tc.FullBranch,
} }
@ -142,7 +143,7 @@ func TestTruncateBranchWithSymbol(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
props := properties{ props := properties.Map{
BranchMaxLength: tc.MaxLength, BranchMaxLength: tc.MaxLength,
TruncateSymbol: tc.TruncateSymbol, TruncateSymbol: tc.TruncateSymbol,
FullBranchPath: tc.FullBranch, FullBranchPath: tc.FullBranch,
@ -173,8 +174,8 @@ func TestScmShouldIgnoreRootRepository(t *testing.T) {
"/home/bill", "/home/bill",
"/home/gates.*", "/home/gates.*",
} }
props := properties{ props := properties.Map{
ExcludeFolders: excludeFolders, properties.ExcludeFolders: excludeFolders,
} }
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Home").Return("/home/bill") env.On("Home").Return("/home/bill")

View file

@ -4,24 +4,25 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"runtime/debug" "runtime/debug"
"time" "time"
) )
// Segment represent a single segment and it's configuration // Segment represent a single segment and it's configuration
type Segment struct { type Segment struct {
Type SegmentType `config:"type"` Type SegmentType `config:"type"`
Tips []string `config:"tips"` Tips []string `config:"tips"`
Style SegmentStyle `config:"style"` Style SegmentStyle `config:"style"`
PowerlineSymbol string `config:"powerline_symbol"` PowerlineSymbol string `config:"powerline_symbol"`
InvertPowerline bool `config:"invert_powerline"` InvertPowerline bool `config:"invert_powerline"`
Foreground string `config:"foreground"` Foreground string `config:"foreground"`
ForegroundTemplates []string `config:"foreground_templates"` ForegroundTemplates []string `config:"foreground_templates"`
Background string `config:"background"` Background string `config:"background"`
BackgroundTemplates []string `config:"background_templates"` BackgroundTemplates []string `config:"background_templates"`
LeadingDiamond string `config:"leading_diamond"` LeadingDiamond string `config:"leading_diamond"`
TrailingDiamond string `config:"trailing_diamond"` TrailingDiamond string `config:"trailing_diamond"`
Properties properties `config:"properties"` Properties properties.Map `config:"properties"`
writer SegmentWriter writer SegmentWriter
stringValue string stringValue string
active bool active bool
@ -42,7 +43,7 @@ type SegmentTiming struct {
type SegmentWriter interface { type SegmentWriter interface {
enabled() bool enabled() bool
template() string template() string
init(props Properties, env environment.Environment) init(props properties.Properties, env environment.Environment)
} }
// SegmentStyle the syle of segment, for more information, see the constants // SegmentStyle the syle of segment, for more information, see the constants
@ -164,9 +165,9 @@ func (segment *Segment) enabled() bool {
return segment.active return segment.active
} }
func (segment *Segment) getValue(property Property, defaultValue string) string { func (segment *Segment) getValue(property properties.Property, defaultValue string) string {
if value, ok := segment.Properties[property]; ok { if value, ok := segment.Properties[property]; ok {
return parseString(value, defaultValue) return properties.ParseString(value, defaultValue)
} }
return defaultValue return defaultValue
} }
@ -178,13 +179,13 @@ func (segment *Segment) shouldIncludeFolder() bool {
} }
func (segment *Segment) cwdIncluded() bool { func (segment *Segment) cwdIncluded() bool {
value, ok := segment.Properties[IncludeFolders] value, ok := segment.Properties[properties.IncludeFolders]
if !ok { if !ok {
// IncludeFolders isn't specified, everything is included // IncludeFolders isn't specified, everything is included
return true return true
} }
list := parseStringArray(value) list := properties.ParseStringArray(value)
if len(list) == 0 { if len(list) == 0 {
// IncludeFolders is an empty array, everything is included // IncludeFolders is an empty array, everything is included
@ -195,11 +196,11 @@ func (segment *Segment) cwdIncluded() bool {
} }
func (segment *Segment) cwdExcluded() bool { func (segment *Segment) cwdExcluded() bool {
value, ok := segment.Properties[ExcludeFolders] value, ok := segment.Properties[properties.ExcludeFolders]
if !ok { if !ok {
value = segment.Properties[IgnoreFolders] value = segment.Properties[properties.IgnoreFolders]
} }
list := parseStringArray(value) list := properties.ParseStringArray(value)
return environment.DirMatchesOneOf(segment.env, segment.env.Pwd(), list) return environment.DirMatchesOneOf(segment.env, segment.env.Pwd(), list)
} }
@ -287,7 +288,7 @@ func (segment *Segment) mapSegmentWithWriter(env environment.Environment) error
Ipify: &ipify{}, Ipify: &ipify{},
} }
if segment.Properties == nil { if segment.Properties == nil {
segment.Properties = make(properties) segment.Properties = make(properties.Map)
} }
if writer, ok := functions[segment.Type]; ok { if writer, ok := functions[segment.Type]; ok {
writer.init(segment.Properties, env) writer.init(segment.Properties, env)

View file

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type angular struct { type angular struct {
@ -14,7 +15,7 @@ func (a *angular) template() string {
return languageTemplate return languageTemplate
} }
func (a *angular) init(props Properties, env environment.Environment) { func (a *angular) init(props properties.Properties, env environment.Environment) {
a.language = language{ a.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -34,7 +35,7 @@ func TestAngularCliVersionDisplayed(t *testing.T) {
env.On("TemplateCache").Return(&environment.TemplateCache{ env.On("TemplateCache").Return(&environment.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
}) })
props := properties{} props := properties.Map{}
angular := &angular{} angular := &angular{}
angular.init(props, env) angular.init(props, env)
assert.True(t, angular.enabled(), fmt.Sprintf("Failed in case: %s", ta.Case)) assert.True(t, angular.enabled(), fmt.Sprintf("Failed in case: %s", ta.Case))

View file

@ -3,11 +3,12 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strings" "strings"
) )
type aws struct { type aws struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Profile string Profile string
@ -22,7 +23,7 @@ func (a *aws) template() string {
return "{{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }}" return "{{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }}"
} }
func (a *aws) init(props Properties, env environment.Environment) { func (a *aws) init(props properties.Properties, env environment.Environment) {
a.props = props a.props = props
a.env = env a.env = env
} }
@ -37,7 +38,7 @@ func (a *aws) enabled() bool {
} }
return "" return ""
} }
displayDefaultUser := a.props.GetBool(DisplayDefault, true) displayDefaultUser := a.props.GetBool(properties.DisplayDefault, true)
a.Profile = getEnvFirstMatch("AWS_VAULT", "AWS_PROFILE") a.Profile = getEnvFirstMatch("AWS_VAULT", "AWS_PROFILE")
if !displayDefaultUser && a.Profile == defaultUser { if !displayDefaultUser && a.Profile == defaultUser {
return false return false

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -55,8 +56,8 @@ func TestAWSSegment(t *testing.T) {
env.On("Getenv", "AWS_CONFIG_FILE").Return(tc.ConfigFile) env.On("Getenv", "AWS_CONFIG_FILE").Return(tc.ConfigFile)
env.On("FileContent", "/usr/home/.aws/config").Return("") env.On("FileContent", "/usr/home/.aws/config").Return("")
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
props := properties{ props := properties.Map{
DisplayDefault: tc.DisplayDefault, properties.DisplayDefault: tc.DisplayDefault,
} }
aws := &aws{ aws := &aws{
env: env, env: env,

View file

@ -3,12 +3,13 @@ package main
import ( import (
"encoding/json" "encoding/json"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"path/filepath" "path/filepath"
"strings" "strings"
) )
type az struct { type az struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
AzureSubscription AzureSubscription
@ -83,7 +84,7 @@ func (a *az) template() string {
return "{{ .Name }}" return "{{ .Name }}"
} }
func (a *az) init(props Properties, env environment.Environment) { func (a *az) init(props properties.Properties, env environment.Environment) {
a.props = props a.props = props
a.env = env a.env = env
} }

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type azfunc struct { type azfunc struct {
language language
@ -10,7 +13,7 @@ func (az *azfunc) template() string {
return languageTemplate return languageTemplate
} }
func (az *azfunc) init(props Properties, env environment.Environment) { func (az *azfunc) init(props properties.Properties, env environment.Environment) {
az.language = language{ az.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -4,6 +4,7 @@ import (
"io/ioutil" "io/ioutil"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"path/filepath" "path/filepath"
"testing" "testing"
@ -91,7 +92,7 @@ func TestAzSegment(t *testing.T) {
env.On("FileContent", filepath.Join(home, ".azure", "AzureRmContext.json")).Return(azureRMContext) env.On("FileContent", filepath.Join(home, ".azure", "AzureRmContext.json")).Return(azureRMContext)
az := &az{ az := &az{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.Equal(t, tc.ExpectedEnabled, az.enabled(), tc.Case) assert.Equal(t, tc.ExpectedEnabled, az.enabled(), tc.Case)
assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, az), tc.Case) assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, az), tc.Case)

View file

@ -3,12 +3,13 @@ package main
import ( import (
"math" "math"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"github.com/distatus/battery" "github.com/distatus/battery"
) )
type batt struct { type batt struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
battery.Battery battery.Battery
@ -19,11 +20,11 @@ type batt struct {
const ( const (
// ChargingIcon to display when charging // ChargingIcon to display when charging
ChargingIcon Property = "charging_icon" ChargingIcon properties.Property = "charging_icon"
// DischargingIcon o display when discharging // DischargingIcon o display when discharging
DischargingIcon Property = "discharging_icon" DischargingIcon properties.Property = "discharging_icon"
// ChargedIcon to display when fully charged // ChargedIcon to display when fully charged
ChargedIcon Property = "charged_icon" ChargedIcon properties.Property = "charged_icon"
) )
func (b *batt) template() string { func (b *batt) template() string {
@ -70,7 +71,7 @@ func (b *batt) enabledWhileError(err error) bool {
if _, ok := err.(*environment.NoBatteryError); ok { if _, ok := err.(*environment.NoBatteryError); ok {
return false return false
} }
displayError := b.props.GetBool(DisplayError, false) displayError := b.props.GetBool(properties.DisplayError, false)
if !displayError { if !displayError {
return false return false
} }
@ -104,7 +105,7 @@ func (b *batt) mapMostLogicalState(currentState, newState battery.State) battery
return newState return newState
} }
func (b *batt) init(props Properties, env environment.Environment) { func (b *batt) init(props properties.Properties, env environment.Environment) {
b.props = props b.props = props
b.env = env b.env = env
} }

View file

@ -8,13 +8,14 @@ import (
"math" "math"
"net/http" "net/http"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"sort" "sort"
"time" "time"
) )
// segment struct, makes templating easier // segment struct, makes templating easier
type brewfather struct { type brewfather struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Batch Batch
@ -31,28 +32,28 @@ type brewfather struct {
} }
const ( const (
BFUserID Property = "user_id" BFUserID properties.Property = "user_id"
BFAPIKey Property = "api_key" BFAPIKey properties.Property = "api_key"
BFBatchID Property = "batch_id" BFBatchID properties.Property = "batch_id"
BFDoubleUpIcon Property = "doubleup_icon" BFDoubleUpIcon properties.Property = "doubleup_icon"
BFSingleUpIcon Property = "singleup_icon" BFSingleUpIcon properties.Property = "singleup_icon"
BFFortyFiveUpIcon Property = "fortyfiveup_icon" BFFortyFiveUpIcon properties.Property = "fortyfiveup_icon"
BFFlatIcon Property = "flat_icon" BFFlatIcon properties.Property = "flat_icon"
BFFortyFiveDownIcon Property = "fortyfivedown_icon" BFFortyFiveDownIcon properties.Property = "fortyfivedown_icon"
BFSingleDownIcon Property = "singledown_icon" BFSingleDownIcon properties.Property = "singledown_icon"
BFDoubleDownIcon Property = "doubledown_icon" BFDoubleDownIcon properties.Property = "doubledown_icon"
BFPlanningStatusIcon Property = "planning_status_icon" BFPlanningStatusIcon properties.Property = "planning_status_icon"
BFBrewingStatusIcon Property = "brewing_status_icon" BFBrewingStatusIcon properties.Property = "brewing_status_icon"
BFFermentingStatusIcon Property = "fermenting_status_icon" BFFermentingStatusIcon properties.Property = "fermenting_status_icon"
BFConditioningStatusIcon Property = "conditioning_status_icon" BFConditioningStatusIcon properties.Property = "conditioning_status_icon"
BFCompletedStatusIcon Property = "completed_status_icon" BFCompletedStatusIcon properties.Property = "completed_status_icon"
BFArchivedStatusIcon Property = "archived_status_icon" BFArchivedStatusIcon properties.Property = "archived_status_icon"
BFDayIcon Property = "day_icon" BFDayIcon properties.Property = "day_icon"
BFCacheTimeout Property = "cache_timeout" BFCacheTimeout properties.Property = "cache_timeout"
DefaultTemplate string = "{{.StatusIcon}} {{if .DaysBottledOrFermented}}{{.DaysBottledOrFermented}}{{.DayIcon}} {{end}}[{{.Recipe.Name}}]({{.URL}})" + DefaultTemplate string = "{{.StatusIcon}} {{if .DaysBottledOrFermented}}{{.DaysBottledOrFermented}}{{.DayIcon}} {{end}}[{{.Recipe.Name}}]({{.URL}})" +
" {{printf \"%.1f\" .MeasuredAbv}}%{{ if and (.Reading) (eq .Status \"Fermenting\")}} " + " {{printf \"%.1f\" .MeasuredAbv}}%{{ if and (.Reading) (eq .Status \"Fermenting\")}} " +
@ -325,7 +326,7 @@ func (bf *brewfather) SGToPlato(sg float64) float64 {
return math.Round(100*((135.997*sg*sg*sg)-(630.272*sg*sg)+(1111.14*sg)-616.868)) / 100 // 2 decimal places return math.Round(100*((135.997*sg*sg*sg)-(630.272*sg*sg)+(1111.14*sg)-616.868)) / 100 // 2 decimal places
} }
func (bf *brewfather) init(props Properties, env environment.Environment) { func (bf *brewfather) init(props properties.Properties, env environment.Environment) {
bf.props = props bf.props = props
bf.env = env bf.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"time" "time"
@ -138,7 +139,7 @@ func TestBrewfatherSegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
props := properties{ props := properties.Map{
CacheTimeout: tc.CacheTimeout, CacheTimeout: tc.CacheTimeout,
BFBatchID: BFFakeBatchID, BFBatchID: BFFakeBatchID,
BFAPIKey: "FAKE", BFAPIKey: "FAKE",

View file

@ -2,11 +2,12 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strings" "strings"
) )
type command struct { type command struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Output string Output string
@ -14,9 +15,9 @@ type command struct {
const ( const (
// ExecutableShell to execute command in // ExecutableShell to execute command in
ExecutableShell Property = "shell" ExecutableShell properties.Property = "shell"
// Command to execute // Command to execute
Command Property = "command" Command properties.Property = "command"
) )
func (c *command) template() string { func (c *command) template() string {
@ -52,7 +53,7 @@ func (c *command) enabled() bool {
return c.Output != "" return c.Output != ""
} }
func (c *command) init(props Properties, env environment.Environment) { func (c *command) init(props properties.Properties, env environment.Environment) {
c.props = props c.props = props
c.env = env c.env = env
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -11,7 +12,7 @@ func TestExecuteCommand(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
props := properties{ props := properties.Map{
Command: "echo hello", Command: "echo hello",
} }
c := &command{ c := &command{
@ -29,7 +30,7 @@ func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
env.On("RunShellCommand", "bash", "exit 1").Return("") env.On("RunShellCommand", "bash", "exit 1").Return("")
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
env.On("RunShellCommand", "bash", "exit 1 || echo hello").Return("hello") env.On("RunShellCommand", "bash", "exit 1 || echo hello").Return("hello")
props := properties{ props := properties.Map{
Command: "exit 1 || echo hello", Command: "exit 1 || echo hello",
} }
c := &command{ c := &command{
@ -46,7 +47,7 @@ func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
env.On("RunShellCommand", "bash", "echo world").Return("world") env.On("RunShellCommand", "bash", "echo world").Return("world")
props := properties{ props := properties.Map{
Command: "echo hello || echo world", Command: "echo hello || echo world",
} }
c := &command{ c := &command{
@ -63,7 +64,7 @@ func TestExecuteMultipleCommandsAnd(t *testing.T) {
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo hello").Return("hello") env.On("RunShellCommand", "bash", "echo hello").Return("hello")
env.On("RunShellCommand", "bash", "echo world").Return("world") env.On("RunShellCommand", "bash", "echo world").Return("world")
props := properties{ props := properties.Map{
Command: "echo hello && echo world", Command: "echo hello && echo world",
} }
c := &command{ c := &command{
@ -79,7 +80,7 @@ func TestExecuteSingleCommandEmpty(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "").Return("") env.On("RunShellCommand", "bash", "").Return("")
props := properties{ props := properties.Map{
Command: "", Command: "",
} }
c := &command{ c := &command{
@ -94,7 +95,7 @@ func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo no command specified").Return("no command specified") env.On("RunShellCommand", "bash", "echo no command specified").Return("no command specified")
var props properties var props properties.Map
c := &command{ c := &command{
props: props, props: props,
env: env, env: env,
@ -108,7 +109,7 @@ func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo").Return("") env.On("RunShellCommand", "bash", "echo").Return("")
props := properties{ props := properties.Map{
Command: "echo && echo", Command: "echo && echo",
} }
c := &command{ c := &command{
@ -124,7 +125,7 @@ func TestExecuteMultipleCommandsOrDisabled(t *testing.T) {
env.On("HasCommand", "bash").Return(true) env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo").Return("") env.On("RunShellCommand", "bash", "echo").Return("")
env.On("RunShellCommand", "bash", "echo|| echo").Return("") env.On("RunShellCommand", "bash", "echo|| echo").Return("")
props := properties{ props := properties.Map{
Command: "echo|| echo", Command: "echo|| echo",
} }
c := &command{ c := &command{

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type crystal struct { type crystal struct {
language language
@ -10,7 +13,7 @@ func (c *crystal) template() string {
return languageTemplate return languageTemplate
} }
func (c *crystal) init(props Properties, env environment.Environment) { func (c *crystal) init(props properties.Properties, env environment.Environment) {
c.language = language{ c.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type dart struct { type dart struct {
language language
@ -10,7 +13,7 @@ func (d *dart) template() string {
return languageTemplate return languageTemplate
} }
func (d *dart) init(props Properties, env environment.Environment) { func (d *dart) init(props properties.Properties, env environment.Environment) {
d.language = language{ d.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type dotnet struct { type dotnet struct {
language language
@ -12,7 +15,7 @@ func (d *dotnet) template() string {
return "{{ if .Unsupported }}\uf071{{ else }}{{ .Full }}{{ end }}" return "{{ if .Unsupported }}\uf071{{ else }}{{ .Full }}{{ end }}"
} }
func (d *dotnet) init(props Properties, env environment.Environment) { func (d *dotnet) init(props properties.Properties, env environment.Environment) {
d.language = language{ d.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,8 +41,8 @@ func TestDotnetSegment(t *testing.T) {
env.On("TemplateCache").Return(&environment.TemplateCache{ env.On("TemplateCache").Return(&environment.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
}) })
props := properties{ props := properties.Map{
FetchVersion: tc.FetchVersion, properties.FetchVersion: tc.FetchVersion,
} }
dotnet := &dotnet{} dotnet := &dotnet{}
dotnet.init(props, env) dotnet.init(props, env)

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strconv" "strconv"
lang "golang.org/x/text/language" lang "golang.org/x/text/language"
@ -10,7 +11,7 @@ import (
) )
type executiontime struct { type executiontime struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
FormattedMs string FormattedMs string
@ -22,7 +23,7 @@ type DurationStyle string
const ( const (
// ThresholdProperty represents minimum duration (milliseconds) required to enable this segment // ThresholdProperty represents minimum duration (milliseconds) required to enable this segment
ThresholdProperty Property = "threshold" ThresholdProperty properties.Property = "threshold"
// Austin milliseconds short // Austin milliseconds short
Austin DurationStyle = "austin" Austin DurationStyle = "austin"
// Roundrock milliseconds long // Roundrock milliseconds long
@ -48,13 +49,13 @@ const (
) )
func (t *executiontime) enabled() bool { func (t *executiontime) enabled() bool {
alwaysEnabled := t.props.GetBool(AlwaysEnabled, false) alwaysEnabled := t.props.GetBool(properties.AlwaysEnabled, false)
executionTimeMs := t.env.ExecutionTime() executionTimeMs := t.env.ExecutionTime()
thresholdMs := t.props.GetFloat64(ThresholdProperty, float64(500)) thresholdMs := t.props.GetFloat64(ThresholdProperty, float64(500))
if !alwaysEnabled && executionTimeMs < thresholdMs { if !alwaysEnabled && executionTimeMs < thresholdMs {
return false return false
} }
style := DurationStyle(t.props.GetString(Style, string(Austin))) style := DurationStyle(t.props.GetString(properties.Style, string(Austin)))
t.Ms = int64(executionTimeMs) t.Ms = int64(executionTimeMs)
t.FormattedMs = t.formatDuration(style) t.FormattedMs = t.formatDuration(style)
return t.FormattedMs != "" return t.FormattedMs != ""
@ -64,7 +65,7 @@ func (t *executiontime) template() string {
return "{{ .FormattedMs }}" return "{{ .FormattedMs }}"
} }
func (t *executiontime) init(props Properties, env environment.Environment) { func (t *executiontime) init(props properties.Properties, env environment.Environment) {
t.props = props t.props = props
t.env = env t.env = env
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"time" "time"
@ -13,7 +14,7 @@ func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) {
env.On("ExecutionTime").Return(1337) env.On("ExecutionTime").Return(1337)
executionTime := &executiontime{ executionTime := &executiontime{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.True(t, executionTime.enabled()) assert.True(t, executionTime.enabled())
} }
@ -23,7 +24,7 @@ func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) {
env.On("ExecutionTime").Return(1) env.On("ExecutionTime").Return(1)
executionTime := &executiontime{ executionTime := &executiontime{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.False(t, executionTime.enabled()) assert.False(t, executionTime.enabled())
} }
@ -31,7 +32,7 @@ func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) {
func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) { func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ExecutionTime").Return(99) env.On("ExecutionTime").Return(99)
props := properties{ props := properties.Map{
ThresholdProperty: float64(10), ThresholdProperty: float64(10),
} }
executionTime := &executiontime{ executionTime := &executiontime{
@ -44,7 +45,7 @@ func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) {
func TestExecutionTimeWriterCustomThresholdDisabled(t *testing.T) { func TestExecutionTimeWriterCustomThresholdDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ExecutionTime").Return(99) env.On("ExecutionTime").Return(99)
props := properties{ props := properties.Map{
ThresholdProperty: float64(100), ThresholdProperty: float64(100),
} }
executionTime := &executiontime{ executionTime := &executiontime{
@ -61,7 +62,7 @@ func TestExecutionTimeWriterDuration(t *testing.T) {
env.On("ExecutionTime").Return(input) env.On("ExecutionTime").Return(input)
executionTime := &executiontime{ executionTime := &executiontime{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
executionTime.enabled() executionTime.enabled()
assert.Equal(t, expected, executionTime.FormattedMs) assert.Equal(t, expected, executionTime.FormattedMs)
@ -74,7 +75,7 @@ func TestExecutionTimeWriterDuration2(t *testing.T) {
env.On("ExecutionTime").Return(input) env.On("ExecutionTime").Return(input)
executionTime := &executiontime{ executionTime := &executiontime{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
executionTime.enabled() executionTime.enabled()
assert.Equal(t, expected, executionTime.FormattedMs) assert.Equal(t, expected, executionTime.FormattedMs)

View file

@ -2,11 +2,12 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strconv" "strconv"
) )
type exit struct { type exit struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Text string Text string
@ -18,13 +19,13 @@ func (e *exit) template() string {
func (e *exit) enabled() bool { func (e *exit) enabled() bool {
e.Text = e.getMeaningFromExitCode(e.env.ErrorCode()) e.Text = e.getMeaningFromExitCode(e.env.ErrorCode())
if e.props.GetBool(AlwaysEnabled, false) { if e.props.GetBool(properties.AlwaysEnabled, false) {
return true return true
} }
return e.env.ErrorCode() != 0 return e.env.ErrorCode() != 0
} }
func (e *exit) init(props Properties, env environment.Environment) { func (e *exit) init(props properties.Properties, env environment.Environment) {
e.props = props e.props = props
e.env = env e.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -23,7 +24,7 @@ func TestExitWriterEnabled(t *testing.T) {
env.On("ErrorCode").Return(tc.ExitCode) env.On("ErrorCode").Return(tc.ExitCode)
e := &exit{ e := &exit{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.Equal(t, tc.Expected, e.enabled()) assert.Equal(t, tc.Expected, e.enabled())
} }
@ -83,7 +84,7 @@ func TestExitWriterTemplateString(t *testing.T) {
}) })
e := &exit{ e := &exit{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, e), tc.Case) assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, e), tc.Case)
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"oh-my-posh/regex" "oh-my-posh/regex"
"strconv" "strconv"
"strings" "strings"
@ -59,48 +60,48 @@ type git struct {
const ( const (
// FetchStatus fetches the status of the repository // FetchStatus fetches the status of the repository
FetchStatus Property = "fetch_status" FetchStatus properties.Property = "fetch_status"
// FetchStashCount fetches the stash count // FetchStashCount fetches the stash count
FetchStashCount Property = "fetch_stash_count" FetchStashCount properties.Property = "fetch_stash_count"
// FetchWorktreeCount fetches the worktree count // FetchWorktreeCount fetches the worktree count
FetchWorktreeCount Property = "fetch_worktree_count" FetchWorktreeCount properties.Property = "fetch_worktree_count"
// FetchUpstreamIcon fetches the upstream icon // FetchUpstreamIcon fetches the upstream icon
FetchUpstreamIcon Property = "fetch_upstream_icon" FetchUpstreamIcon properties.Property = "fetch_upstream_icon"
// BranchIcon the icon to use as branch indicator // BranchIcon the icon to use as branch indicator
BranchIcon Property = "branch_icon" BranchIcon properties.Property = "branch_icon"
// BranchIdenticalIcon the icon to display when the remote and local branch are identical // BranchIdenticalIcon the icon to display when the remote and local branch are identical
BranchIdenticalIcon Property = "branch_identical_icon" BranchIdenticalIcon properties.Property = "branch_identical_icon"
// BranchAheadIcon the icon to display when the local branch is ahead of the remote // BranchAheadIcon the icon to display when the local branch is ahead of the remote
BranchAheadIcon Property = "branch_ahead_icon" BranchAheadIcon properties.Property = "branch_ahead_icon"
// BranchBehindIcon the icon to display when the local branch is behind the remote // BranchBehindIcon the icon to display when the local branch is behind the remote
BranchBehindIcon Property = "branch_behind_icon" BranchBehindIcon properties.Property = "branch_behind_icon"
// BranchGoneIcon the icon to use when ther's no remote // BranchGoneIcon the icon to use when ther's no remote
BranchGoneIcon Property = "branch_gone_icon" BranchGoneIcon properties.Property = "branch_gone_icon"
// RebaseIcon shows before the rebase context // RebaseIcon shows before the rebase context
RebaseIcon Property = "rebase_icon" RebaseIcon properties.Property = "rebase_icon"
// CherryPickIcon shows before the cherry-pick context // CherryPickIcon shows before the cherry-pick context
CherryPickIcon Property = "cherry_pick_icon" CherryPickIcon properties.Property = "cherry_pick_icon"
// RevertIcon shows before the revert context // RevertIcon shows before the revert context
RevertIcon Property = "revert_icon" RevertIcon properties.Property = "revert_icon"
// CommitIcon shows before the detached context // CommitIcon shows before the detached context
CommitIcon Property = "commit_icon" CommitIcon properties.Property = "commit_icon"
// NoCommitsIcon shows when there are no commits in the repo yet // NoCommitsIcon shows when there are no commits in the repo yet
NoCommitsIcon Property = "no_commits_icon" NoCommitsIcon properties.Property = "no_commits_icon"
// TagIcon shows before the tag context // TagIcon shows before the tag context
TagIcon Property = "tag_icon" TagIcon properties.Property = "tag_icon"
// MergeIcon shows before the merge context // MergeIcon shows before the merge context
MergeIcon Property = "merge_icon" MergeIcon properties.Property = "merge_icon"
// GithubIcon shows√ when upstream is github // GithubIcon shows√ when upstream is github
GithubIcon Property = "github_icon" GithubIcon properties.Property = "github_icon"
// BitbucketIcon shows when upstream is bitbucket // BitbucketIcon shows when upstream is bitbucket
BitbucketIcon Property = "bitbucket_icon" BitbucketIcon properties.Property = "bitbucket_icon"
// AzureDevOpsIcon shows when upstream is azure devops // AzureDevOpsIcon shows when upstream is azure devops
AzureDevOpsIcon Property = "azure_devops_icon" AzureDevOpsIcon properties.Property = "azure_devops_icon"
// GitlabIcon shows when upstream is gitlab // GitlabIcon shows when upstream is gitlab
GitlabIcon Property = "gitlab_icon" GitlabIcon properties.Property = "gitlab_icon"
// GitIcon shows when the upstream can't be identified // GitIcon shows when the upstream can't be identified
GitIcon Property = "git_icon" GitIcon properties.Property = "git_icon"
DETACHED = "(detached)" DETACHED = "(detached)"
BRANCHPREFIX = "ref: refs/heads/" BRANCHPREFIX = "ref: refs/heads/"

View file

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"strings" "strings"
"testing" "testing"
@ -23,7 +24,7 @@ func TestEnabledGitNotFound(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
assert.False(t, g.enabled()) assert.False(t, g.enabled())
@ -46,7 +47,7 @@ func TestEnabledInWorkingDirectory(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
assert.True(t, g.enabled()) assert.True(t, g.enabled())
@ -72,7 +73,7 @@ func TestEnabledInWorkingTree(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
assert.True(t, g.enabled()) assert.True(t, g.enabled())
@ -99,7 +100,7 @@ func TestEnabledInSubmodule(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
assert.True(t, g.enabled()) assert.True(t, g.enabled())
@ -119,7 +120,7 @@ func TestGetGitOutputForCommand(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
got := g.getGitCommandOutput(commandArgs...) got := g.getGitCommandOutput(commandArgs...)
@ -263,7 +264,7 @@ func TestSetGitHEADContextClean(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{ props: properties.Map{
BranchIcon: "branch ", BranchIcon: "branch ",
CommitIcon: "commit ", CommitIcon: "commit ",
RebaseIcon: "rebase ", RebaseIcon: "rebase ",
@ -305,7 +306,7 @@ func TestSetPrettyHEADName(t *testing.T) {
g := &git{ g := &git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{ props: properties.Map{
BranchIcon: "branch ", BranchIcon: "branch ",
CommitIcon: "commit ", CommitIcon: "commit ",
TagIcon: "tag ", TagIcon: "tag ",
@ -483,7 +484,7 @@ func TestGitUpstream(t *testing.T) {
env.On("RunCommand", "git", []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false", env.On("RunCommand", "git", []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false",
"-c", "color.status=false", "remote", "get-url", "origin"}).Return(tc.Upstream, nil) "-c", "color.status=false", "remote", "get-url", "origin"}).Return(tc.Upstream, nil)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
props := properties{ props := properties.Map{
GithubIcon: "GH", GithubIcon: "GH",
GitlabIcon: "GL", GitlabIcon: "GL",
BitbucketIcon: "BB", BitbucketIcon: "BB",
@ -519,7 +520,7 @@ func TestGetBranchStatus(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
props := properties{ props := properties.Map{
BranchAheadIcon: "up", BranchAheadIcon: "up",
BranchBehindIcon: "down", BranchBehindIcon: "down",
BranchIdenticalIcon: "equal", BranchIdenticalIcon: "equal",
@ -704,7 +705,7 @@ func TestGitTemplateString(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
props := properties{ props := properties.Map{
FetchStatus: true, FetchStatus: true,
} }
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"golang.org/x/mod/modfile" "golang.org/x/mod/modfile"
) )
@ -11,14 +12,14 @@ type golang struct {
} }
const ( const (
ParseModFile Property = "parse_mod_file" ParseModFile properties.Property = "parse_mod_file"
) )
func (g *golang) template() string { func (g *golang) template() string {
return languageTemplate return languageTemplate
} }
func (g *golang) init(props Properties, env environment.Environment) { func (g *golang) init(props properties.Properties, env environment.Environment) {
g.language = language{ g.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -6,6 +6,7 @@ import (
"io/ioutil" "io/ioutil"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -18,7 +19,7 @@ type mockedLanguageParams struct {
extension string extension string
} }
func getMockedLanguageEnv(params *mockedLanguageParams) (*mock.MockedEnvironment, properties) { func getMockedLanguageEnv(params *mockedLanguageParams) (*mock.MockedEnvironment, properties.Map) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", params.cmd).Return(true) env.On("HasCommand", params.cmd).Return(true)
env.On("RunCommand", params.cmd, []string{params.versionParam}).Return(params.versionOutput, nil) env.On("RunCommand", params.cmd, []string{params.versionParam}).Return(params.versionOutput, nil)
@ -28,8 +29,8 @@ func getMockedLanguageEnv(params *mockedLanguageParams) (*mock.MockedEnvironment
env.On("TemplateCache").Return(&environment.TemplateCache{ env.On("TemplateCache").Return(&environment.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
}) })
props := properties{ props := properties.Map{
FetchVersion: true, properties.FetchVersion: true,
} }
return env, props return env, props
} }

View file

@ -1,15 +1,18 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type ipify struct { type ipify struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
IP string IP string
} }
const ( const (
IpifyURL Property = "url" IpifyURL properties.Property = "url"
) )
func (i *ipify) template() string { func (i *ipify) template() string {
@ -57,7 +60,7 @@ func (i *ipify) getResult() (string, error) {
return response, nil return response, nil
} }
func (i *ipify) init(props Properties, env environment.Environment) { func (i *ipify) init(props properties.Properties, env environment.Environment) {
i.props = props i.props = props
i.env = env i.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -44,7 +45,7 @@ func TestIpifySegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
props := properties{ props := properties.Map{
CacheTimeout: 0, CacheTimeout: 0,
} }
env.On("HTTPRequest", IPIFYAPIURL).Return([]byte(tc.Response), tc.Error) env.On("HTTPRequest", IPIFYAPIURL).Return([]byte(tc.Response), tc.Error)

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type java struct { type java struct {
@ -13,7 +14,7 @@ func (j *java) template() string {
return languageTemplate return languageTemplate
} }
func (j *java) init(props Properties, env environment.Environment) { func (j *java) init(props properties.Properties, env environment.Environment) {
javaRegex := `(?: JRE)(?: \(.*\))? \((?P<version>(?P<major>[0-9]+)(?:\.(?P<minor>[0-9]+))?(?:\.(?P<patch>[0-9]+))?).*\),` javaRegex := `(?: JRE)(?: \(.*\))? \((?P<version>(?P<major>[0-9]+)(?:\.(?P<minor>[0-9]+))?(?:\.(?P<patch>[0-9]+))?).*\),`
javaCmd := &cmd{ javaCmd := &cmd{
executable: "java", executable: "java",

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -67,8 +68,8 @@ func TestJava(t *testing.T) {
} else { } else {
env.On("Getenv", "JAVA_HOME").Return("") env.On("Getenv", "JAVA_HOME").Return("")
} }
props := properties{ props := properties.Map{
FetchVersion: true, properties.FetchVersion: true,
} }
j := &java{} j := &java{}
j.init(props, env) j.init(props, env)

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type julia struct { type julia struct {
language language
@ -10,7 +13,7 @@ func (j *julia) template() string {
return languageTemplate return languageTemplate
} }
func (j *julia) init(props Properties, env environment.Environment) { func (j *julia) init(props properties.Properties, env environment.Environment) {
j.language = language{ j.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -2,16 +2,17 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"path/filepath" "path/filepath"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
// Whether to use kubectl or read kubeconfig ourselves // Whether to use kubectl or read kubeconfig ourselves
const ParseKubeConfig Property = "parse_kubeconfig" const ParseKubeConfig properties.Property = "parse_kubeconfig"
type kubectl struct { type kubectl struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Context string Context string
@ -37,7 +38,7 @@ func (k *kubectl) template() string {
return "{{ .Context }}{{ if .Namespace }} :: {{ .Namespace }}{{ end }}" return "{{ .Context }}{{ if .Namespace }} :: {{ .Namespace }}{{ end }}"
} }
func (k *kubectl) init(props Properties, env environment.Environment) { func (k *kubectl) init(props properties.Properties, env environment.Environment) {
k.props = props k.props = props
k.env = env k.env = env
} }
@ -92,7 +93,7 @@ func (k *kubectl) doParseKubeConfig() bool {
return true return true
} }
displayError := k.props.GetBool(DisplayError, false) displayError := k.props.GetBool(properties.DisplayError, false)
if !displayError { if !displayError {
return false return false
} }
@ -106,7 +107,7 @@ func (k *kubectl) doCallKubectl() bool {
return false return false
} }
result, err := k.env.RunCommand(cmd, "config", "view", "--output", "yaml", "--minify") result, err := k.env.RunCommand(cmd, "config", "view", "--output", "yaml", "--minify")
displayError := k.props.GetBool(DisplayError, false) displayError := k.props.GetBool(properties.DisplayError, false)
if err != nil && displayError { if err != nil && displayError {
k.setError("KUBECTL ERR") k.setError("KUBECTL ERR")
return true return true

View file

@ -5,6 +5,7 @@ import (
"io/ioutil" "io/ioutil"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"path/filepath" "path/filepath"
"testing" "testing"
@ -130,9 +131,9 @@ func TestKubectlSegment(t *testing.T) {
k := &kubectl{ k := &kubectl{
env: env, env: env,
props: properties{ props: properties.Map{
DisplayError: tc.DisplayError, properties.DisplayError: tc.DisplayError,
ParseKubeConfig: tc.ParseKubeConfig, ParseKubeConfig: tc.ParseKubeConfig,
}, },
} }
assert.Equal(t, tc.ExpectedEnabled, k.enabled(), tc.Case) assert.Equal(t, tc.ExpectedEnabled, k.enabled(), tc.Case)

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"oh-my-posh/regex" "oh-my-posh/regex"
) )
@ -53,7 +54,7 @@ func (c *cmd) parse(versionInfo string) (*version, error) {
} }
type language struct { type language struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
extensions []string extensions []string
commands []*cmd commands []*cmd
@ -72,7 +73,7 @@ type language struct {
const ( const (
// DisplayMode sets the display mode (always, when_in_context, never) // DisplayMode sets the display mode (always, when_in_context, never)
DisplayMode Property = "display_mode" DisplayMode properties.Property = "display_mode"
// DisplayModeAlways displays the segment always // DisplayModeAlways displays the segment always
DisplayModeAlways string = "always" DisplayModeAlways string = "always"
// DisplayModeFiles displays the segment when the current folder contains certain extensions // DisplayModeFiles displays the segment when the current folder contains certain extensions
@ -82,11 +83,11 @@ const (
// DisplayModeContext displays the segment when the environment or files is active // DisplayModeContext displays the segment when the environment or files is active
DisplayModeContext string = "context" DisplayModeContext string = "context"
// MissingCommandText sets the text to display when the command is not present in the system // MissingCommandText sets the text to display when the command is not present in the system
MissingCommandText Property = "missing_command_text" MissingCommandText properties.Property = "missing_command_text"
// HomeEnabled displays the segment in the HOME folder or not // HomeEnabled displays the segment in the HOME folder or not
HomeEnabled Property = "home_enabled" HomeEnabled properties.Property = "home_enabled"
// LanguageExtensions the list of extensions to validate // LanguageExtensions the list of extensions to validate
LanguageExtensions Property = "extensions" LanguageExtensions properties.Property = "extensions"
) )
func (l *language) enabled() bool { func (l *language) enabled() bool {
@ -118,7 +119,7 @@ func (l *language) enabled() bool {
enabled = l.hasLanguageFiles() || l.inLanguageContext() enabled = l.hasLanguageFiles() || l.inLanguageContext()
} }
} }
if !enabled || !l.props.GetBool(FetchVersion, true) { if !enabled || !l.props.GetBool(properties.FetchVersion, true) {
return enabled return enabled
} }
err := l.setVersion() err := l.setVersion()
@ -191,7 +192,7 @@ func (l *language) inLanguageContext() bool {
} }
func (l *language) buildVersionURL() { func (l *language) buildVersionURL() {
versionURLTemplate := l.props.GetString(VersionURLTemplate, l.versionURLTemplate) versionURLTemplate := l.props.GetString(properties.VersionURLTemplate, l.versionURLTemplate)
if len(versionURLTemplate) == 0 { if len(versionURLTemplate) == 0 {
return return
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -22,7 +23,7 @@ type languageArgs struct {
enabledCommands []string enabledCommands []string
versionURLTemplate string versionURLTemplate string
expectedError error expectedError error
properties Properties properties properties.Properties
matchesVersionFile matchesVersionFile matchesVersionFile matchesVersionFile
inHome bool inHome bool
} }
@ -56,7 +57,7 @@ func bootStrapLanguageTest(args *languageArgs) *language {
Env: make(map[string]string), Env: make(map[string]string),
}) })
if args.properties == nil { if args.properties == nil {
args.properties = properties{} args.properties = properties.Map{}
} }
l := &language{ l := &language{
props: args.properties, props: args.properties,
@ -86,8 +87,8 @@ func TestLanguageFilesFoundButNoCommandAndVersionAndDisplayVersion(t *testing.T)
} }
func TestLanguageFilesFoundButNoCommandAndVersionAndDontDisplayVersion(t *testing.T) { func TestLanguageFilesFoundButNoCommandAndVersionAndDontDisplayVersion(t *testing.T) {
props := properties{ props := properties.Map{
FetchVersion: false, properties.FetchVersion: false,
} }
args := &languageArgs{ args := &languageArgs{
commands: []*cmd{ commands: []*cmd{
@ -236,8 +237,8 @@ func TestLanguageEnabledAllExtensionsFound(t *testing.T) {
} }
func TestLanguageEnabledNoVersion(t *testing.T) { func TestLanguageEnabledNoVersion(t *testing.T) {
props := properties{ props := properties.Map{
FetchVersion: false, properties.FetchVersion: false,
} }
args := &languageArgs{ args := &languageArgs{
commands: []*cmd{ commands: []*cmd{
@ -259,8 +260,8 @@ func TestLanguageEnabledNoVersion(t *testing.T) {
} }
func TestLanguageEnabledMissingCommand(t *testing.T) { func TestLanguageEnabledMissingCommand(t *testing.T) {
props := properties{ props := properties.Map{
FetchVersion: false, properties.FetchVersion: false,
} }
args := &languageArgs{ args := &languageArgs{
commands: []*cmd{}, commands: []*cmd{},
@ -276,8 +277,8 @@ func TestLanguageEnabledMissingCommand(t *testing.T) {
} }
func TestLanguageEnabledNoVersionData(t *testing.T) { func TestLanguageEnabledNoVersionData(t *testing.T) {
props := properties{ props := properties.Map{
FetchVersion: true, properties.FetchVersion: true,
} }
args := &languageArgs{ args := &languageArgs{
commands: []*cmd{ commands: []*cmd{
@ -300,7 +301,7 @@ func TestLanguageEnabledNoVersionData(t *testing.T) {
func TestLanguageEnabledMissingCommandCustomText(t *testing.T) { func TestLanguageEnabledMissingCommandCustomText(t *testing.T) {
expected := "missing" expected := "missing"
props := properties{ props := properties.Map{
MissingCommandText: expected, MissingCommandText: expected,
} }
args := &languageArgs{ args := &languageArgs{
@ -317,9 +318,9 @@ func TestLanguageEnabledMissingCommandCustomText(t *testing.T) {
} }
func TestLanguageEnabledMissingCommandCustomTextHideError(t *testing.T) { func TestLanguageEnabledMissingCommandCustomTextHideError(t *testing.T) {
props := properties{ props := properties.Map{
MissingCommandText: "missing", MissingCommandText: "missing",
DisplayError: false, properties.DisplayError: false,
} }
args := &languageArgs{ args := &languageArgs{
commands: []*cmd{}, commands: []*cmd{},
@ -375,7 +376,7 @@ func TestLanguageHyperlinkEnabled(t *testing.T) {
enabledExtensions: []string{corn}, enabledExtensions: []string{corn},
enabledCommands: []string{"corn"}, enabledCommands: []string{"corn"},
version: universion, version: universion,
properties: properties{}, properties: properties.Map{},
} }
lang := bootStrapLanguageTest(args) lang := bootStrapLanguageTest(args)
assert.True(t, lang.enabled()) assert.True(t, lang.enabled())
@ -401,7 +402,7 @@ func TestLanguageHyperlinkEnabledWrongRegex(t *testing.T) {
enabledExtensions: []string{corn}, enabledExtensions: []string{corn},
enabledCommands: []string{"corn"}, enabledCommands: []string{"corn"},
version: universion, version: universion,
properties: properties{}, properties: properties.Map{},
} }
lang := bootStrapLanguageTest(args) lang := bootStrapLanguageTest(args)
assert.True(t, lang.enabled()) assert.True(t, lang.enabled())
@ -418,7 +419,7 @@ func TestLanguageEnabledInHome(t *testing.T) {
{Case: "Context disabled", HomeEnabled: false, ExpectedEnabled: false}, {Case: "Context disabled", HomeEnabled: false, ExpectedEnabled: false},
} }
for _, tc := range cases { for _, tc := range cases {
props := properties{ props := properties.Map{
HomeEnabled: tc.HomeEnabled, HomeEnabled: tc.HomeEnabled,
} }
args := &languageArgs{ args := &languageArgs{

View file

@ -3,10 +3,11 @@ package main
import ( import (
"encoding/json" "encoding/json"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type nbgv struct { type nbgv struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
VersionInfo VersionInfo
@ -44,7 +45,7 @@ func (n *nbgv) enabled() bool {
return n.VersionInfo.VersionFileFound return n.VersionInfo.VersionFileFound
} }
func (n *nbgv) init(props Properties, env environment.Environment) { func (n *nbgv) init(props properties.Properties, env environment.Environment) {
n.props = props n.props = props
n.env = env n.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
@ -63,7 +64,7 @@ func TestNbgv(t *testing.T) {
env.On("RunCommand", "nbgv", []string{"get-version", "--format=json"}).Return(tc.Response, tc.Error) env.On("RunCommand", "nbgv", []string{"get-version", "--format=json"}).Return(tc.Response, tc.Error)
nbgv := &nbgv{ nbgv := &nbgv{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
enabled := nbgv.enabled() enabled := nbgv.enabled()
assert.Equal(t, tc.ExpectedEnabled, enabled, tc.Case) assert.Equal(t, tc.ExpectedEnabled, enabled, tc.Case)

View file

@ -4,12 +4,13 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"time" "time"
) )
// segment struct, makes templating easier // segment struct, makes templating easier
type nightscout struct { type nightscout struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
NightscoutData NightscoutData
@ -18,17 +19,17 @@ type nightscout struct {
const ( const (
// Your complete Nightscout URL and APIKey like this // Your complete Nightscout URL and APIKey like this
URL Property = "url" URL properties.Property = "url"
DoubleUpIcon Property = "doubleup_icon" DoubleUpIcon properties.Property = "doubleup_icon"
SingleUpIcon Property = "singleup_icon" SingleUpIcon properties.Property = "singleup_icon"
FortyFiveUpIcon Property = "fortyfiveup_icon" FortyFiveUpIcon properties.Property = "fortyfiveup_icon"
FlatIcon Property = "flat_icon" FlatIcon properties.Property = "flat_icon"
FortyFiveDownIcon Property = "fortyfivedown_icon" FortyFiveDownIcon properties.Property = "fortyfivedown_icon"
SingleDownIcon Property = "singledown_icon" SingleDownIcon properties.Property = "singledown_icon"
DoubleDownIcon Property = "doubledown_icon" DoubleDownIcon properties.Property = "doubledown_icon"
NSCacheTimeout Property = "cache_timeout" NSCacheTimeout properties.Property = "cache_timeout"
) )
// NightscoutData struct contains the API data // NightscoutData struct contains the API data
@ -138,7 +139,7 @@ func (ns *nightscout) getResult() (*NightscoutData, error) {
return data, nil return data, nil
} }
func (ns *nightscout) init(props Properties, env environment.Environment) { func (ns *nightscout) init(props properties.Properties, env environment.Environment) {
ns.props = props ns.props = props
ns.env = env ns.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -131,7 +132,7 @@ func TestNSSegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
props := properties{ props := properties.Map{
CacheTimeout: tc.CacheTimeout, CacheTimeout: tc.CacheTimeout,
URL: "FAKE", URL: "FAKE",
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"oh-my-posh/regex" "oh-my-posh/regex"
) )
@ -14,18 +15,18 @@ type node struct {
const ( const (
// YarnIcon illustrates Yarn is used // YarnIcon illustrates Yarn is used
YarnIcon Property = "yarn_icon" YarnIcon properties.Property = "yarn_icon"
// NPMIcon illustrates NPM is used // NPMIcon illustrates NPM is used
NPMIcon Property = "npm_icon" NPMIcon properties.Property = "npm_icon"
// FetchPackageManager shows if NPM or Yarn is used // FetchPackageManager shows if NPM or Yarn is used
FetchPackageManager Property = "fetch_package_manager" FetchPackageManager properties.Property = "fetch_package_manager"
) )
func (n *node) template() string { func (n *node) template() string {
return "{{ if .PackageManagerIcon }}{{ .PackageManagerIcon }} {{ end }}{{ .Full }}" return "{{ if .PackageManagerIcon }}{{ .PackageManagerIcon }} {{ end }}{{ .Full }}"
} }
func (n *node) init(props Properties, env environment.Environment) { func (n *node) init(props properties.Properties, env environment.Environment) {
n.language = language{ n.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
@ -68,7 +69,7 @@ func TestNodeInContext(t *testing.T) {
node := &node{ node := &node{
language: language{ language: language{
env: env, env: env,
props: properties{ props: properties.Map{
YarnIcon: "yarn", YarnIcon: "yarn",
NPMIcon: "npm", NPMIcon: "npm",
FetchPackageManager: tc.PkgMgrEnabled, FetchPackageManager: tc.PkgMgrEnabled,

View file

@ -1,9 +1,12 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type osInfo struct { type osInfo struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Icon string Icon string
@ -11,51 +14,51 @@ type osInfo struct {
const ( const (
// MacOS the string/icon to use for MacOS // MacOS the string/icon to use for MacOS
MacOS Property = "macos" MacOS properties.Property = "macos"
// Linux the string/icon to use for linux // Linux the string/icon to use for linux
Linux Property = "linux" Linux properties.Property = "linux"
// Windows the string/icon to use for windows // Windows the string/icon to use for windows
Windows Property = "windows" Windows properties.Property = "windows"
// Alpine the string/icon to use for Alpine // Alpine the string/icon to use for Alpine
Alpine Property = "alpine" Alpine properties.Property = "alpine"
// Aosc the string/icon to use for Aosc // Aosc the string/icon to use for Aosc
Aosc Property = "aosc" Aosc properties.Property = "aosc"
// Arch the string/icon to use for Arch // Arch the string/icon to use for Arch
Arch Property = "arch" Arch properties.Property = "arch"
// Centos the string/icon to use for Centos // Centos the string/icon to use for Centos
Centos Property = "centos" Centos properties.Property = "centos"
// Coreos the string/icon to use for Coreos // Coreos the string/icon to use for Coreos
Coreos Property = "coreos" Coreos properties.Property = "coreos"
// Debian the string/icon to use for Debian // Debian the string/icon to use for Debian
Debian Property = "debian" Debian properties.Property = "debian"
// Devuan the string/icon to use for Devuan // Devuan the string/icon to use for Devuan
Devuan Property = "devuan" Devuan properties.Property = "devuan"
// Raspbian the string/icon to use for Raspbian // Raspbian the string/icon to use for Raspbian
Raspbian Property = "raspbian" Raspbian properties.Property = "raspbian"
// Elementary the string/icon to use for Elementary // Elementary the string/icon to use for Elementary
Elementary Property = "elementary" Elementary properties.Property = "elementary"
// Fedora the string/icon to use for Fedora // Fedora the string/icon to use for Fedora
Fedora Property = "fedora" Fedora properties.Property = "fedora"
// Gentoo the string/icon to use for Gentoo // Gentoo the string/icon to use for Gentoo
Gentoo Property = "gentoo" Gentoo properties.Property = "gentoo"
// Mageia the string/icon to use for Mageia // Mageia the string/icon to use for Mageia
Mageia Property = "mageia" Mageia properties.Property = "mageia"
// Manjaro the string/icon to use for Manjaro // Manjaro the string/icon to use for Manjaro
Manjaro Property = "manjaro" Manjaro properties.Property = "manjaro"
// Mint the string/icon to use for Mint // Mint the string/icon to use for Mint
Mint Property = "mint" Mint properties.Property = "mint"
// Nixos the string/icon to use for Nixos // Nixos the string/icon to use for Nixos
Nixos Property = "nixos" Nixos properties.Property = "nixos"
// Opensuse the string/icon to use for Opensuse // Opensuse the string/icon to use for Opensuse
Opensuse Property = "opensuse" Opensuse properties.Property = "opensuse"
// Sabayon the string/icon to use for Sabayon // Sabayon the string/icon to use for Sabayon
Sabayon Property = "sabayon" Sabayon properties.Property = "sabayon"
// Slackware the string/icon to use for Slackware // Slackware the string/icon to use for Slackware
Slackware Property = "slackware" Slackware properties.Property = "slackware"
// Ubuntu the string/icon to use for Ubuntu // Ubuntu the string/icon to use for Ubuntu
Ubuntu Property = "ubuntu" Ubuntu properties.Property = "ubuntu"
// DisplayDistroName display the distro name or not // DisplayDistroName display the distro name or not
DisplayDistroName Property = "display_distro_name" DisplayDistroName properties.Property = "display_distro_name"
) )
func (oi *osInfo) template() string { func (oi *osInfo) template() string {
@ -127,7 +130,7 @@ func (oi *osInfo) getDistroIcon(distro string) string {
return oi.props.GetString(Linux, "\uF17C") return oi.props.GetString(Linux, "\uF17C")
} }
func (oi *osInfo) init(props Properties, env environment.Environment) { func (oi *osInfo) init(props properties.Properties, env environment.Environment) {
oi.props = props oi.props = props
oi.env = env oi.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -71,7 +72,7 @@ func TestOSInfo(t *testing.T) {
}) })
osInfo := &osInfo{ osInfo := &osInfo{
env: env, env: env,
props: properties{ props: properties.Map{
DisplayDistroName: tc.DisplayDistroName, DisplayDistroName: tc.DisplayDistroName,
Windows: "windows", Windows: "windows",
MacOS: "darwin", MacOS: "darwin",

View file

@ -5,10 +5,11 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type owm struct { type owm struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Temperature float64 Temperature float64
@ -20,13 +21,13 @@ type owm struct {
const ( const (
// APIKey openweathermap api key // APIKey openweathermap api key
APIKey Property = "apikey" APIKey properties.Property = "apikey"
// Location openweathermap location // Location openweathermap location
Location Property = "location" Location properties.Property = "location"
// Units openweathermap units // Units openweathermap units
Units Property = "units" Units properties.Property = "units"
// CacheTimeout cache timeout // CacheTimeout cache timeout
CacheTimeout Property = "cache_timeout" CacheTimeout properties.Property = "cache_timeout"
// CacheKeyResponse key used when caching the response // CacheKeyResponse key used when caching the response
CacheKeyResponse string = "owm_response" CacheKeyResponse string = "owm_response"
// CacheKeyURL key used when caching the url responsible for the response // CacheKeyURL key used when caching the url responsible for the response
@ -163,7 +164,7 @@ func (d *owm) setStatus() error {
return nil return nil
} }
func (d *owm) init(props Properties, env environment.Environment) { func (d *owm) init(props properties.Properties, env environment.Environment) {
d.props = props d.props = props
d.env = env d.env = env
} }

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -52,7 +53,7 @@ func TestOWMSegmentSingle(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
props := properties{ props := properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
Units: "metric", Units: "metric",
@ -187,7 +188,7 @@ func TestOWMSegmentIcons(t *testing.T) {
env.On("HTTPRequest", OWMAPIURL).Return([]byte(response), nil) env.On("HTTPRequest", OWMAPIURL).Return([]byte(response), nil)
o := &owm{ o := &owm{
props: properties{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
Units: "metric", Units: "metric",
@ -210,7 +211,7 @@ func TestOWMSegmentIcons(t *testing.T) {
env.On("HTTPRequest", OWMAPIURL).Return([]byte(response), nil) env.On("HTTPRequest", OWMAPIURL).Return([]byte(response), nil)
o := &owm{ o := &owm{
props: properties{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
Units: "metric", Units: "metric",
@ -230,7 +231,7 @@ func TestOWMSegmentFromCache(t *testing.T) {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
cache := &mock.MockedCache{} cache := &mock.MockedCache{}
o := &owm{ o := &owm{
props: properties{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
Units: "metric", Units: "metric",
@ -254,7 +255,7 @@ func TestOWMSegmentFromCacheWithHyperlink(t *testing.T) {
cache := &mock.MockedCache{} cache := &mock.MockedCache{}
o := &owm{ o := &owm{
props: properties{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
Units: "metric", Units: "metric",

View file

@ -3,13 +3,14 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"oh-my-posh/regex" "oh-my-posh/regex"
"sort" "sort"
"strings" "strings"
) )
type path struct { type path struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
pwd string pwd string
@ -20,13 +21,13 @@ type path struct {
const ( const (
// FolderSeparatorIcon the path which is split will be separated by this icon // FolderSeparatorIcon the path which is split will be separated by this icon
FolderSeparatorIcon Property = "folder_separator_icon" FolderSeparatorIcon properties.Property = "folder_separator_icon"
// HomeIcon indicates the $HOME location // HomeIcon indicates the $HOME location
HomeIcon Property = "home_icon" HomeIcon properties.Property = "home_icon"
// FolderIcon identifies one folder // FolderIcon identifies one folder
FolderIcon Property = "folder_icon" FolderIcon properties.Property = "folder_icon"
// WindowsRegistryIcon indicates the registry location on Windows // WindowsRegistryIcon indicates the registry location on Windows
WindowsRegistryIcon Property = "windows_registry_icon" WindowsRegistryIcon properties.Property = "windows_registry_icon"
// Agnoster displays a short path with separator icon, this the default style // Agnoster displays a short path with separator icon, this the default style
Agnoster string = "agnoster" Agnoster string = "agnoster"
// AgnosterFull displays all the folder names with the folder_separator_icon // AgnosterFull displays all the folder names with the folder_separator_icon
@ -46,13 +47,13 @@ const (
// AgnosterLeft like agnoster, but keeps the left side of the path // AgnosterLeft like agnoster, but keeps the left side of the path
AgnosterLeft string = "agnoster_left" AgnosterLeft string = "agnoster_left"
// MixedThreshold the threshold of the length of the path Mixed will display // MixedThreshold the threshold of the length of the path Mixed will display
MixedThreshold Property = "mixed_threshold" MixedThreshold properties.Property = "mixed_threshold"
// MappedLocations allows overriding certain location with an icon // MappedLocations allows overriding certain location with an icon
MappedLocations Property = "mapped_locations" MappedLocations properties.Property = "mapped_locations"
// MappedLocationsEnabled enables overriding certain locations with an icon // MappedLocationsEnabled enables overriding certain locations with an icon
MappedLocationsEnabled Property = "mapped_locations_enabled" MappedLocationsEnabled properties.Property = "mapped_locations_enabled"
// MaxDepth Maximum path depth to display whithout shortening // MaxDepth Maximum path depth to display whithout shortening
MaxDepth Property = "max_depth" MaxDepth properties.Property = "max_depth"
) )
func (pt *path) template() string { func (pt *path) template() string {
@ -61,7 +62,7 @@ func (pt *path) template() string {
func (pt *path) enabled() bool { func (pt *path) enabled() bool {
pt.pwd = pt.env.Pwd() pt.pwd = pt.env.Pwd()
switch style := pt.props.GetString(Style, Agnoster); style { switch style := pt.props.GetString(properties.Style, Agnoster); style {
case Agnoster: case Agnoster:
pt.Path = pt.getAgnosterPath() pt.Path = pt.getAgnosterPath()
case AgnosterFull: case AgnosterFull:
@ -102,7 +103,7 @@ func (pt *path) formatWindowsDrive(pwd string) string {
return pwd + "\\" return pwd + "\\"
} }
func (pt *path) init(props Properties, env environment.Environment) { func (pt *path) init(props properties.Properties, env environment.Environment) {
pt.props = props pt.props = props
pt.env = env pt.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/gookit/config/v2" "github.com/gookit/config/v2"
@ -99,7 +100,7 @@ func TestRootLocationHome(t *testing.T) {
env.On("GOOS").Return("") env.On("GOOS").Return("")
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
HomeIcon: tc.HomeIcon, HomeIcon: tc.HomeIcon,
WindowsRegistryIcon: tc.RegistryIcon, WindowsRegistryIcon: tc.RegistryIcon,
}, },
@ -252,9 +253,9 @@ func TestAgnosterPathStyles(t *testing.T) {
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
FolderSeparatorIcon: tc.FolderSeparatorIcon, FolderSeparatorIcon: tc.FolderSeparatorIcon,
Style: tc.Style, properties.Style: tc.Style,
MaxDepth: tc.MaxDepth, MaxDepth: tc.MaxDepth,
}, },
} }
@ -374,8 +375,8 @@ func TestGetFullPath(t *testing.T) {
if len(tc.Template) == 0 { if len(tc.Template) == 0 {
tc.Template = "{{ if gt .StackCount 0 }}{{ .StackCount }} {{ end }}{{ .Path }}" tc.Template = "{{ if gt .StackCount 0 }}{{ .StackCount }} {{ end }}{{ .Path }}"
} }
props := properties{ props := properties.Map{
Style: tc.Style, properties.Style: tc.Style,
} }
if tc.FolderSeparatorIcon != "" { if tc.FolderSeparatorIcon != "" {
props[FolderSeparatorIcon] = tc.FolderSeparatorIcon props[FolderSeparatorIcon] = tc.FolderSeparatorIcon
@ -422,7 +423,7 @@ func TestGetFullPathCustomMappedLocations(t *testing.T) {
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
MappedLocationsEnabled: false, MappedLocationsEnabled: false,
MappedLocations: tc.MappedLocations, MappedLocations: tc.MappedLocations,
}, },
@ -473,7 +474,7 @@ func TestGetFolderPathCustomMappedLocations(t *testing.T) {
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
MappedLocations: map[string]string{ MappedLocations: map[string]string{
"/a/b/c/d": "#", "/a/b/c/d": "#",
}, },
@ -520,7 +521,7 @@ func TestAgnosterPath(t *testing.T) { // nolint:dupl
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
FolderSeparatorIcon: " > ", FolderSeparatorIcon: " > ",
FolderIcon: "f", FolderIcon: "f",
HomeIcon: "~", HomeIcon: "~",
@ -568,7 +569,7 @@ func TestAgnosterLeftPath(t *testing.T) { // nolint:dupl
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
FolderSeparatorIcon: " > ", FolderSeparatorIcon: " > ",
FolderIcon: "f", FolderIcon: "f",
HomeIcon: "~", HomeIcon: "~",
@ -616,7 +617,7 @@ func TestGetPwd(t *testing.T) {
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &path{
env: env, env: env,
props: properties{ props: properties.Map{
MappedLocationsEnabled: tc.MappedLocationsEnabled, MappedLocationsEnabled: tc.MappedLocationsEnabled,
MappedLocations: map[string]string{ MappedLocations: map[string]string{
"/a/b/c/d": "#", "/a/b/c/d": "#",

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type php struct { type php struct {
language language
@ -10,7 +13,7 @@ func (p *php) template() string {
return languageTemplate return languageTemplate
} }
func (p *php) init(props Properties, env environment.Environment) { func (p *php) init(props properties.Properties, env environment.Environment) {
p.language = language{ p.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"oh-my-posh/regex" "oh-my-posh/regex"
"strconv" "strconv"
"strings" "strings"
@ -36,7 +37,7 @@ type plastic struct {
plasticWorkspaceFolder string // root folder of workspace plasticWorkspaceFolder string // root folder of workspace
} }
func (p *plastic) init(props Properties, env environment.Environment) { func (p *plastic) init(props properties.Properties, env environment.Environment) {
p.props = props p.props = props
p.env = env p.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -16,7 +17,7 @@ func TestPlasticEnabledNotFound(t *testing.T) {
p := &plastic{ p := &plastic{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
assert.False(t, p.enabled()) assert.False(t, p.enabled())
@ -37,7 +38,7 @@ func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) {
p := &plastic{ p := &plastic{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
assert.True(t, p.enabled()) assert.True(t, p.enabled())
@ -51,7 +52,7 @@ func setupCmStatusEnv(status, headStatus string) *plastic {
p := &plastic{ p := &plastic{
scm: scm{ scm: scm{
env: env, env: env,
props: properties{}, props: properties.Map{},
}, },
} }
return p return p
@ -327,7 +328,7 @@ func TestPlasticTemplateString(t *testing.T) {
} }
for _, tc := range cases { for _, tc := range cases {
props := properties{ props := properties.Map{
FetchStatus: true, FetchStatus: true,
} }
tc.Plastic.props = props tc.Plastic.props = props

View file

@ -2,11 +2,12 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strings" "strings"
) )
type poshgit struct { type poshgit struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Status string Status string
@ -26,7 +27,7 @@ func (p *poshgit) enabled() bool {
return p.Status != "" return p.Status != ""
} }
func (p *poshgit) init(props Properties, env environment.Environment) { func (p *poshgit) init(props properties.Properties, env environment.Environment) {
p.props = props p.props = props
p.env = env p.env = env
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -24,7 +25,7 @@ func TestPoshGitSegment(t *testing.T) {
env.On("Getenv", poshGitEnv).Return(tc.PoshGitPrompt) env.On("Getenv", poshGitEnv).Return(tc.PoshGitPrompt)
p := &poshgit{ p := &poshgit{
env: env, env: env,
props: &properties{}, props: &properties.Map{},
} }
assert.Equal(t, tc.Enabled, p.enabled(), tc.Case) assert.Equal(t, tc.Enabled, p.enabled(), tc.Case)
if tc.Enabled { if tc.Enabled {

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type python struct { type python struct {
language language
@ -10,14 +13,14 @@ type python struct {
const ( const (
// FetchVirtualEnv fetches the virtual env // FetchVirtualEnv fetches the virtual env
FetchVirtualEnv Property = "fetch_virtual_env" FetchVirtualEnv properties.Property = "fetch_virtual_env"
) )
func (p *python) template() string { func (p *python) template() string {
return languageTemplate return languageTemplate
} }
func (p *python) init(props Properties, env environment.Environment) { func (p *python) init(props properties.Properties, env environment.Environment) {
p.language = language{ p.language = language{
env: env, env: env,
props: props, props: props,
@ -75,7 +78,7 @@ func (p *python) canUseVenvName(name string) bool {
if name == "" || name == "." { if name == "" || name == "." {
return false return false
} }
if p.language.props.GetBool(DisplayDefault, true) { if p.language.props.GetBool(properties.DisplayDefault, true) {
return true return true
} }
invalidNames := [2]string{"system", "base"} invalidNames := [2]string{"system", "base"}

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/alecthomas/assert" "github.com/alecthomas/assert"
@ -54,9 +55,9 @@ func TestPythonTemplate(t *testing.T) {
env.On("PathSeperator").Return("") env.On("PathSeperator").Return("")
env.On("Pwd").Return("/usr/home/project") env.On("Pwd").Return("/usr/home/project")
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
props := properties{ props := properties.Map{
FetchVersion: tc.FetchVersion, properties.FetchVersion: tc.FetchVersion,
DisplayMode: DisplayModeAlways, DisplayMode: DisplayModeAlways,
} }
env.On("TemplateCache").Return(&environment.TemplateCache{ env.On("TemplateCache").Return(&environment.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
@ -85,7 +86,7 @@ func TestPythonPythonInContext(t *testing.T) {
env.On("Getenv", "CONDA_DEFAULT_ENV").Return("") env.On("Getenv", "CONDA_DEFAULT_ENV").Return("")
env.On("Getenv", "PYENV_VERSION").Return("") env.On("Getenv", "PYENV_VERSION").Return("")
python := &python{} python := &python{}
python.init(properties{}, env) python.init(properties.Map{}, env)
python.loadContext() python.loadContext()
assert.Equal(t, tc.Expected, python.inContext()) assert.Equal(t, tc.Expected, python.inContext())
} }

View file

@ -1,9 +1,12 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type root struct { type root struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
} }
@ -15,7 +18,7 @@ func (rt *root) enabled() bool {
return rt.env.Root() return rt.env.Root()
} }
func (rt *root) init(props Properties, env environment.Environment) { func (rt *root) init(props properties.Properties, env environment.Environment) {
rt.props = props rt.props = props
rt.env = env rt.env = env
} }

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type ruby struct { type ruby struct {
language language
@ -10,7 +13,7 @@ func (r *ruby) template() string {
return languageTemplate return languageTemplate
} }
func (r *ruby) init(props Properties, env environment.Environment) { func (r *ruby) init(props properties.Properties, env environment.Environment) {
r.language = language{ r.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -99,8 +100,8 @@ func TestRuby(t *testing.T) {
env.On("HasFiles", "Gemfile").Return(tc.HasGemFile) env.On("HasFiles", "Gemfile").Return(tc.HasGemFile)
env.On("Pwd").Return("/usr/home/project") env.On("Pwd").Return("/usr/home/project")
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
props := properties{ props := properties.Map{
FetchVersion: tc.FetchVersion, properties.FetchVersion: tc.FetchVersion,
} }
ruby := &ruby{} ruby := &ruby{}
ruby.init(props, env) ruby.init(props, env)

View file

@ -1,6 +1,9 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type rust struct { type rust struct {
language language
@ -10,7 +13,7 @@ func (r *rust) template() string {
return languageTemplate return languageTemplate
} }
func (r *rust) init(props Properties, env environment.Environment) { func (r *rust) init(props properties.Properties, env environment.Environment) {
r.language = language{ r.language = language{
env: env, env: env,
props: props, props: props,

View file

@ -1,9 +1,12 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type session struct { type session struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
// text string // text string
@ -22,7 +25,7 @@ func (s *session) template() string {
return "{{ .UserName }}@{{ .HostName }}" return "{{ .UserName }}@{{ .HostName }}"
} }
func (s *session) init(props Properties, env environment.Environment) { func (s *session) init(props properties.Properties, env environment.Environment) {
s.props = props s.props = props
s.env = env s.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -110,7 +111,7 @@ func TestSessionSegmentTemplate(t *testing.T) {
}) })
session := &session{ session := &session{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
_ = session.enabled() _ = session.enabled()
assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, session), tc.Case) assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, session), tc.Case)

View file

@ -2,11 +2,12 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"strings" "strings"
) )
type shell struct { type shell struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Name string Name string
@ -14,7 +15,7 @@ type shell struct {
const ( const (
// MappedShellNames allows for custom text in place of shell names // MappedShellNames allows for custom text in place of shell names
MappedShellNames Property = "mapped_shell_names" MappedShellNames properties.Property = "mapped_shell_names"
) )
func (s *shell) template() string { func (s *shell) template() string {
@ -33,7 +34,7 @@ func (s *shell) enabled() bool {
return true return true
} }
func (s *shell) init(props Properties, env environment.Environment) { func (s *shell) init(props properties.Properties, env environment.Environment) {
s.props = props s.props = props
s.env = env s.env = env
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -13,7 +14,7 @@ func TestWriteCurrentShell(t *testing.T) {
env.On("Shell").Return(expected, nil) env.On("Shell").Return(expected, nil)
s := &shell{ s := &shell{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
_ = s.enabled() _ = s.enabled()
assert.Equal(t, expected, renderTemplate(env, s.template(), s)) assert.Equal(t, expected, renderTemplate(env, s.template(), s))
@ -33,7 +34,7 @@ func TestUseMappedShellNames(t *testing.T) {
env.On("Shell").Return(tc.Expected, nil) env.On("Shell").Return(tc.Expected, nil)
s := &shell{ s := &shell{
env: env, env: env,
props: properties{ props: properties.Map{
MappedShellNames: map[string]string{"pwsh": "PS"}, MappedShellNames: map[string]string{"pwsh": "PS"},
}, },
} }

View file

@ -1,9 +1,12 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type spotify struct { type spotify struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
MusicPlayer MusicPlayer
@ -18,11 +21,11 @@ type MusicPlayer struct {
const ( const (
// PlayingIcon indicates a song is playing // PlayingIcon indicates a song is playing
PlayingIcon Property = "playing_icon" PlayingIcon properties.Property = "playing_icon"
// PausedIcon indicates a song is paused // PausedIcon indicates a song is paused
PausedIcon Property = "paused_icon" PausedIcon properties.Property = "paused_icon"
// StoppedIcon indicates a song is stopped // StoppedIcon indicates a song is stopped
StoppedIcon Property = "stopped_icon" StoppedIcon properties.Property = "stopped_icon"
playing = "playing" playing = "playing"
stopped = "stopped" stopped = "stopped"
@ -45,7 +48,7 @@ func (s *spotify) resolveIcon() {
} }
} }
func (s *spotify) init(props Properties, env environment.Environment) { func (s *spotify) init(props properties.Properties, env environment.Environment) {
s.props = props s.props = props
s.env = env s.env = env
} }

View file

@ -5,6 +5,7 @@ package main
import ( import (
"errors" "errors"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -32,7 +33,7 @@ func TestSpotifyDarwinEnabledAndSpotifyPlaying(t *testing.T) {
env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to name of current track as string"}).Return(tc.Track, nil) env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to name of current track as string"}).Return(tc.Track, nil)
s := &spotify{ s := &spotify{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.Equal(t, tc.Running == "true", s.enabled()) assert.Equal(t, tc.Running == "true", s.enabled())
assert.Equal(t, tc.Expected, renderTemplate(env, s.template(), s)) assert.Equal(t, tc.Expected, renderTemplate(env, s.template(), s))

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -17,7 +18,7 @@ func TestSpotifyStringPlayingSong(t *testing.T) {
Status: "playing", Status: "playing",
Icon: "\ue602 ", Icon: "\ue602 ",
}, },
props: properties{}, props: properties.Map{},
env: env, env: env,
} }
assert.Equal(t, expected, renderTemplate(env, s.template(), s)) assert.Equal(t, expected, renderTemplate(env, s.template(), s))
@ -33,7 +34,7 @@ func TestSpotifyStringStoppedSong(t *testing.T) {
Status: "stopped", Status: "stopped",
Icon: "\uf04d ", Icon: "\uf04d ",
}, },
props: properties{}, props: properties.Map{},
env: env, env: env,
} }
assert.Equal(t, expected, renderTemplate(env, s.template(), s)) assert.Equal(t, expected, renderTemplate(env, s.template(), s))

View file

@ -5,6 +5,7 @@ package main
import ( import (
"errors" "errors"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -20,7 +21,7 @@ func bootStrapSpotifyWindowsTest(args *spotifyArgs) *spotify {
env.On("WindowTitle", "spotify.exe").Return(args.title, args.runError) env.On("WindowTitle", "spotify.exe").Return(args.title, args.runError)
s := &spotify{ s := &spotify{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
return s return s
} }
@ -41,7 +42,7 @@ func TestSpotifyWindowsEnabledAndSpotifyPlaying(t *testing.T) {
env.On("WindowTitle", "spotify.exe").Return(args.title, args.runError) env.On("WindowTitle", "spotify.exe").Return(args.title, args.runError)
s := &spotify{ s := &spotify{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.Equal(t, true, s.enabled()) assert.Equal(t, true, s.enabled())
assert.Equal(t, "\ue602 Candlemass - Spellbreaker", renderTemplate(env, s.template(), s)) assert.Equal(t, "\ue602 Candlemass - Spellbreaker", renderTemplate(env, s.template(), s))

View file

@ -7,6 +7,7 @@ import (
"testing" "testing"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -58,7 +59,7 @@ func TestSpotifyWsl(t *testing.T) {
env.On("RunCommand", "tasklist.exe", []string{"/V", "/FI", "Imagename eq Spotify.exe", "/FO", "CSV", "/NH"}).Return(tc.ExecOutput, nil) env.On("RunCommand", "tasklist.exe", []string{"/V", "/FI", "Imagename eq Spotify.exe", "/FO", "CSV", "/NH"}).Return(tc.ExecOutput, nil)
s := &spotify{ s := &spotify{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
assert.Equal(t, tc.ExpectedEnabled, s.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedEnabled, s.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, s.template(), s), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, s.template(), s), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -7,12 +7,13 @@ import (
"math" "math"
"net/http" "net/http"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"time" "time"
) )
// segment struct, makes templating easier // segment struct, makes templating easier
type strava struct { type strava struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
StravaData StravaData
@ -25,11 +26,11 @@ type strava struct {
} }
const ( const (
RideIcon Property = "ride_icon" RideIcon properties.Property = "ride_icon"
RunIcon Property = "run_icon" RunIcon properties.Property = "run_icon"
SkiingIcon Property = "skiing_icon" SkiingIcon properties.Property = "skiing_icon"
WorkOutIcon Property = "workout_icon" WorkOutIcon properties.Property = "workout_icon"
UnknownActivityIcon Property = "unknown_activity_icon" UnknownActivityIcon properties.Property = "unknown_activity_icon"
StravaAccessToken = "strava_access_token" StravaAccessToken = "strava_access_token"
StravaRefreshToken = "strava_refresh_token" StravaRefreshToken = "strava_refresh_token"
@ -135,7 +136,7 @@ func (s *strava) getAccessToken() (string, error) {
} }
} }
// use initial refresh token from property // use initial refresh token from property
refreshToken := s.props.GetString(RefreshToken, "") refreshToken := s.props.GetString(properties.RefreshToken, "")
if len(refreshToken) == 0 { if len(refreshToken) == 0 {
return "", &AuthError{ return "", &AuthError{
message: InvalidRefreshToken, message: InvalidRefreshToken,
@ -230,7 +231,7 @@ func (s *strava) getResult() (*StravaData, error) {
return data, nil return data, nil
} }
func (s *strava) init(props Properties, env environment.Environment) { func (s *strava) init(props properties.Properties, env environment.Environment) {
s.props = props s.props = props
s.env = env s.env = env
} }

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"time" "time"
@ -139,7 +140,7 @@ func TestStravaSegment(t *testing.T) {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
url := "https://www.strava.com/api/v3/athlete/activities?page=1&per_page=1" url := "https://www.strava.com/api/v3/athlete/activities?page=1&per_page=1"
tokenURL := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=strava&token=%s", tc.TokenRefreshToken) tokenURL := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=strava&token=%s", tc.TokenRefreshToken)
var props properties = map[Property]interface{}{ var props properties.Map = map[properties.Property]interface{}{
CacheTimeout: tc.CacheTimeout, CacheTimeout: tc.CacheTimeout,
} }
cache := &mock.MockedCache{} cache := &mock.MockedCache{}
@ -157,10 +158,10 @@ func TestStravaSegment(t *testing.T) {
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
if tc.InitialAccessToken != "" { if tc.InitialAccessToken != "" {
props[AccessToken] = tc.InitialAccessToken props[properties.AccessToken] = tc.InitialAccessToken
} }
if tc.InitialRefreshToken != "" { if tc.InitialRefreshToken != "" {
props[RefreshToken] = tc.InitialRefreshToken props[properties.RefreshToken] = tc.InitialRefreshToken
} }
ns := &strava{ ns := &strava{

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
cpu "github.com/shirou/gopsutil/v3/cpu" cpu "github.com/shirou/gopsutil/v3/cpu"
load "github.com/shirou/gopsutil/v3/load" load "github.com/shirou/gopsutil/v3/load"
@ -9,8 +10,9 @@ import (
) )
type sysinfo struct { type sysinfo struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Precision int Precision int
// mem // mem
PhysicalTotalMemory uint64 PhysicalTotalMemory uint64
@ -30,7 +32,7 @@ type sysinfo struct {
const ( const (
// Precision number of decimal places to show // Precision number of decimal places to show
Precision Property = "precision" Precision properties.Property = "precision"
) )
func (s *sysinfo) template() string { func (s *sysinfo) template() string {
@ -44,7 +46,7 @@ func (s *sysinfo) enabled() bool {
return true return true
} }
func (s *sysinfo) init(props Properties, env environment.Environment) { func (s *sysinfo) init(props properties.Properties, env environment.Environment) {
s.props = props s.props = props
s.env = env s.env = env
s.Precision = s.props.GetInt(Precision, 2) s.Precision = s.props.GetInt(Precision, 2)

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/shirou/gopsutil/v3/cpu" "github.com/shirou/gopsutil/v3/cpu"
@ -52,7 +53,7 @@ func TestSysInfo(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
tc.SysInfo.env = env tc.SysInfo.env = env
tc.SysInfo.props = properties{ tc.SysInfo.props = properties.Map{
Precision: tc.Precision, Precision: tc.Precision,
} }
enabled := tc.SysInfo.enabled() enabled := tc.SysInfo.enabled()

View file

@ -2,10 +2,11 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type terraform struct { type terraform struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
WorkspaceName string WorkspaceName string
@ -15,7 +16,7 @@ func (tf *terraform) template() string {
return "{{ .WorkspaceName }}" return "{{ .WorkspaceName }}"
} }
func (tf *terraform) init(props Properties, env environment.Environment) { func (tf *terraform) init(props properties.Properties, env environment.Environment) {
tf.props = props tf.props = props
tf.env = env tf.env = env
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -21,7 +22,7 @@ func bootStrapTerraformTest(args *terraformArgs) *terraform {
env.On("RunCommand", "terraform", []string{"workspace", "show"}).Return(args.workspaceName, nil) env.On("RunCommand", "terraform", []string{"workspace", "show"}).Return(args.workspaceName, nil)
k := &terraform{ k := &terraform{
env: env, env: env,
props: properties{}, props: properties.Map{},
} }
return k return k
} }

View file

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -86,9 +87,9 @@ func TestShouldIncludeFolder(t *testing.T) {
env.On("Home").Return("") env.On("Home").Return("")
env.On("Pwd").Return(cwd) env.On("Pwd").Return(cwd)
segment := &Segment{ segment := &Segment{
Properties: properties{ Properties: properties.Map{
IncludeFolders: tc.IncludeFolders, properties.IncludeFolders: tc.IncludeFolders,
ExcludeFolders: tc.ExcludeFolders, properties.ExcludeFolders: tc.ExcludeFolders,
}, },
env: env, env: env,
} }
@ -103,8 +104,8 @@ func TestShouldIncludeFolderRegexInverted(t *testing.T) {
env.On("Home").Return("") env.On("Home").Return("")
env.On("Pwd").Return(cwd) env.On("Pwd").Return(cwd)
segment := &Segment{ segment := &Segment{
Properties: properties{ Properties: properties.Map{
ExcludeFolders: []string{"(?!Projects[\\/]).*"}, properties.ExcludeFolders: []string{"(?!Projects[\\/]).*"},
}, },
env: env, env: env,
} }
@ -124,8 +125,8 @@ func TestShouldIncludeFolderRegexInvertedNonEscaped(t *testing.T) {
env.On("Home").Return("") env.On("Home").Return("")
env.On("Pwd").Return(cwd) env.On("Pwd").Return(cwd)
segment := &Segment{ segment := &Segment{
Properties: properties{ Properties: properties.Map{
ExcludeFolders: []string{"(?!Projects/).*"}, properties.ExcludeFolders: []string{"(?!Projects/).*"},
}, },
env: env, env: env,
} }

View file

@ -1,9 +1,12 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type text struct { type text struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Text string Text string
@ -17,7 +20,7 @@ func (t *text) enabled() bool {
return true return true
} }
func (t *text) init(props Properties, env environment.Environment) { func (t *text) init(props properties.Properties, env environment.Environment) {
t.props = props t.props = props
t.env = env t.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -40,8 +41,8 @@ func TestTextSegment(t *testing.T) {
}) })
txt := &text{ txt := &text{
env: env, env: env,
props: properties{ props: properties.Map{
SegmentTemplate: tc.Template, properties.SegmentTemplate: tc.Template,
}, },
} }
assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, txt), tc.Case) assert.Equal(t, tc.ExpectedString, renderTemplate(env, tc.Template, txt), tc.Case)

View file

@ -2,11 +2,12 @@ package main
import ( import (
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
"time" "time"
) )
type tempus struct { type tempus struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
CurrentDate time.Time CurrentDate time.Time
@ -14,7 +15,7 @@ type tempus struct {
const ( const (
// TimeFormat uses the reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to format the current time // TimeFormat uses the reference time Mon Jan 2 15:04:05 MST 2006 to show the pattern with which to format the current time
TimeFormat Property = "time_format" TimeFormat properties.Property = "time_format"
) )
func (t *tempus) template() string { func (t *tempus) template() string {
@ -29,7 +30,7 @@ func (t *tempus) enabled() bool {
return true return true
} }
func (t *tempus) init(props Properties, env environment.Environment) { func (t *tempus) init(props properties.Properties, env environment.Environment) {
t.props = props t.props = props
t.env = env t.env = env
} }

View file

@ -2,6 +2,7 @@ package main
import ( import (
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -42,7 +43,7 @@ func TestTimeSegmentTemplate(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
tempus := &tempus{ tempus := &tempus{
env: env, env: env,
props: properties{}, props: properties.Map{},
CurrentDate: currentDate, CurrentDate: currentDate,
} }
assert.Equal(t, tc.ExpectedEnabled, tempus.enabled()) assert.Equal(t, tc.ExpectedEnabled, tempus.enabled())

View file

@ -3,10 +3,11 @@ package main
import ( import (
"encoding/json" "encoding/json"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type wakatime struct { type wakatime struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
wtData wtData
@ -63,7 +64,7 @@ func (w *wakatime) setAPIData() error {
return nil return nil
} }
func (w *wakatime) init(props Properties, env environment.Environment) { func (w *wakatime) init(props properties.Properties, env environment.Environment) {
w.props = props w.props = props
w.env = env w.env = env
} }

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -80,7 +81,7 @@ func TestWTTrackedTime(t *testing.T) {
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
w := &wakatime{ w := &wakatime{
props: properties{ props: properties.Map{
APIKey: "key", APIKey: "key",
CacheTimeout: tc.CacheTimeout, CacheTimeout: tc.CacheTimeout,
URL: FAKEAPIURL, URL: FAKEAPIURL,

View file

@ -1,9 +1,12 @@
package main package main
import "oh-my-posh/environment" import (
"oh-my-posh/environment"
"oh-my-posh/properties"
)
type wifi struct { type wifi struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Error string Error string
@ -25,7 +28,7 @@ func (w *wifi) enabled() bool {
return false return false
} }
wifiInfo, err := w.env.WifiNetwork() wifiInfo, err := w.env.WifiNetwork()
displayError := w.props.GetBool(DisplayError, false) displayError := w.props.GetBool(properties.DisplayError, false)
if err != nil && displayError { if err != nil && displayError {
w.Error = err.Error() w.Error = err.Error()
return true return true
@ -37,7 +40,7 @@ func (w *wifi) enabled() bool {
return true return true
} }
func (w *wifi) init(props Properties, env environment.Environment) { func (w *wifi) init(props properties.Properties, env environment.Environment) {
w.props = props w.props = props
w.env = env w.env = env
} }

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -50,8 +51,8 @@ func TestWiFiSegment(t *testing.T) {
w := &wifi{ w := &wifi{
env: env, env: env,
props: properties{ props: properties.Map{
DisplayError: tc.DisplayError, properties.DisplayError: tc.DisplayError,
}, },
} }

View file

@ -4,10 +4,11 @@ import (
"errors" "errors"
"fmt" "fmt"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type winreg struct { type winreg struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
Value string Value string
@ -15,16 +16,16 @@ type winreg struct {
const ( const (
// full path to the key; if ends in \, gets "(Default)" key in that path // full path to the key; if ends in \, gets "(Default)" key in that path
RegistryPath Property = "path" RegistryPath properties.Property = "path"
// Fallback is the text to display if the key is not found // Fallback is the text to display if the key is not found
Fallback Property = "fallback" Fallback properties.Property = "fallback"
) )
func (wr *winreg) template() string { func (wr *winreg) template() string {
return "{{ .Value }}" return "{{ .Value }}"
} }
func (wr *winreg) init(props Properties, env environment.Environment) { func (wr *winreg) init(props properties.Properties, env environment.Environment) {
wr.props = props wr.props = props
wr.env = env wr.env = env
} }

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -77,7 +78,7 @@ func TestWinReg(t *testing.T) {
env.On("WindowsRegistryKeyValue", tc.Path).Return(tc.getWRKVOutput, tc.Err) env.On("WindowsRegistryKeyValue", tc.Path).Return(tc.getWRKVOutput, tc.Err)
r := &winreg{ r := &winreg{
env: env, env: env,
props: properties{ props: properties.Map{
RegistryPath: tc.Path, RegistryPath: tc.Path,
Fallback: tc.Fallback, Fallback: tc.Fallback,
}, },

View file

@ -3,10 +3,11 @@ package main
import ( import (
"encoding/json" "encoding/json"
"oh-my-posh/environment" "oh-my-posh/environment"
"oh-my-posh/properties"
) )
type ytm struct { type ytm struct {
props Properties props properties.Properties
env environment.Environment env environment.Environment
MusicPlayer MusicPlayer
@ -14,7 +15,7 @@ type ytm struct {
const ( const (
// APIURL is the YTMDA Remote Control API URL property. // APIURL is the YTMDA Remote Control API URL property.
APIURL Property = "api_url" APIURL properties.Property = "api_url"
) )
func (y *ytm) template() string { func (y *ytm) template() string {
@ -28,7 +29,7 @@ func (y *ytm) enabled() bool {
return err == nil return err == nil
} }
func (y *ytm) init(props Properties, env environment.Environment) { func (y *ytm) init(props properties.Properties, env environment.Environment) {
y.props = props y.props = props
y.env = env y.env = env
} }

View file

@ -3,6 +3,7 @@ package main
import ( import (
"errors" "errors"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/properties"
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -14,7 +15,7 @@ func bootstrapYTMDATest(json string, err error) *ytm {
env.On("HTTPRequest", url+"/query").Return([]byte(json), err) env.On("HTTPRequest", url+"/query").Return([]byte(json), err)
ytm := &ytm{ ytm := &ytm{
env: env, env: env,
props: properties{ props: properties.Map{
APIURL: url, APIURL: url,
}, },
} }