refactor: naming standard for segments

This commit is contained in:
Jan De Dobbeleer 2022-01-26 14:10:18 +01:00 committed by Jan De Dobbeleer
parent bdd13cb32f
commit 59756813d3
90 changed files with 528 additions and 528 deletions

View file

@ -183,7 +183,7 @@ func getDefaultConfig(info string) *Config {
Alignment: Left, Alignment: Left,
Segments: []*Segment{ Segments: []*Segment{
{ {
Type: Session, Type: SESSION,
Style: Diamond, Style: Diamond,
Background: "#c386f1", Background: "#c386f1",
Foreground: "#ffffff", Foreground: "#ffffff",
@ -191,7 +191,7 @@ func getDefaultConfig(info string) *Config {
TrailingDiamond: "\uE0B0", TrailingDiamond: "\uE0B0",
}, },
{ {
Type: Path, Type: PATH,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#ff479c", Background: "#ff479c",
@ -202,7 +202,7 @@ func getDefaultConfig(info string) *Config {
}, },
}, },
{ {
Type: Git, Type: GIT,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#fffb38", Background: "#fffb38",
@ -213,7 +213,7 @@ func getDefaultConfig(info string) *Config {
}, },
}, },
{ {
Type: Battery, Type: BATTERY,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#f36943", Background: "#f36943",
@ -223,7 +223,7 @@ func getDefaultConfig(info string) *Config {
}, },
}, },
{ {
Type: Node, Type: NODE,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#6CA35E", Background: "#6CA35E",
@ -234,7 +234,7 @@ func getDefaultConfig(info string) *Config {
}, },
}, },
{ {
Type: ShellInfo, Type: SHELL,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#0077c2", Background: "#0077c2",
@ -244,14 +244,14 @@ func getDefaultConfig(info string) *Config {
}, },
}, },
{ {
Type: Root, Type: ROOT,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#ffff66", Background: "#ffff66",
Foreground: "#ffffff", Foreground: "#ffffff",
}, },
{ {
Type: Text, Type: TEXT,
Style: Powerline, Style: Powerline,
PowerlineSymbol: "\uE0B0", PowerlineSymbol: "\uE0B0",
Background: "#ffffff", Background: "#ffffff",
@ -261,7 +261,7 @@ func getDefaultConfig(info string) *Config {
}, },
}, },
{ {
Type: Exit, Type: EXIT,
Style: Diamond, Style: Diamond,
Background: "#2e9599", Background: "#2e9599",
Foreground: "#ffffff", Foreground: "#ffffff",

View file

@ -111,7 +111,7 @@ func TestTruncateBranch(t *testing.T) {
BranchMaxLength: tc.MaxLength, BranchMaxLength: tc.MaxLength,
FullBranchPath: tc.FullBranch, FullBranchPath: tc.FullBranch,
} }
p := &plastic{ p := &Plastic{
scm: scm{ scm: scm{
props: props, props: props,
}, },
@ -148,7 +148,7 @@ func TestTruncateBranchWithSymbol(t *testing.T) {
TruncateSymbol: tc.TruncateSymbol, TruncateSymbol: tc.TruncateSymbol,
FullBranchPath: tc.FullBranch, FullBranchPath: tc.FullBranch,
} }
p := &plastic{ p := &Plastic{
scm: scm{ scm: scm{
props: props, props: props,
}, },

View file

@ -53,48 +53,48 @@ type SegmentStyle string
type SegmentType string type SegmentType string
const ( const (
// Session represents the user info segment // SESSION represents the user info segment
Session SegmentType = "session" SESSION SegmentType = "session"
// Path represents the current path segment // PATH represents the current path segment
Path SegmentType = "path" PATH SegmentType = "path"
// Git represents the git status and information // GIT represents the git status and information
Git SegmentType = "git" GIT SegmentType = "git"
// Plastic represents the plastic scm status and information // PLASTIC represents the plastic scm status and information
Plastic SegmentType = "plastic" PLASTIC SegmentType = "plastic"
// Exit writes the last exit code // EXIT writes the last exit code
Exit SegmentType = "exit" EXIT SegmentType = "exit"
// Python writes the virtual env name // PYTHON writes the virtual env name
Python SegmentType = "python" PYTHON SegmentType = "python"
// Root writes root symbol // ROOT writes root symbol
Root SegmentType = "root" ROOT SegmentType = "root"
// Time writes the current timestamp // TIME writes the current timestamp
Time SegmentType = "time" TIME SegmentType = "time"
// Text writes a text // TEXT writes a text
Text SegmentType = "text" TEXT SegmentType = "text"
// Cmd writes the output of a shell command // CMD writes the output of a shell command
Cmd SegmentType = "command" CMD SegmentType = "command"
// Battery writes the battery percentage // BATTERY writes the battery percentage
Battery SegmentType = "battery" BATTERY SegmentType = "battery"
// Spotify writes the Spotify status for Mac // SPOTIFY writes the SPOTIFY status for Mac
Spotify SegmentType = "spotify" SPOTIFY SegmentType = "spotify"
// ShellInfo writes which shell we're currently in // SHELL writes which shell we're currently in
ShellInfo SegmentType = "shell" SHELL SegmentType = "shell"
// Node writes which node version is currently active // NODE writes which node version is currently active
Node SegmentType = "node" NODE SegmentType = "node"
// Os write os specific icon // OS write os specific icon
Os SegmentType = "os" OS SegmentType = "os"
// Az writes the Azure subscription info we're currently in // AZ writes the Azure subscription info we're currently in
Az SegmentType = "az" AZ SegmentType = "az"
// Kubectl writes the Kubernetes context we're currently in // KUBECTL writes the Kubernetes context we're currently in
Kubectl SegmentType = "kubectl" KUBECTL SegmentType = "kubectl"
// Dotnet writes which dotnet version is currently active // DOTNET writes which dotnet version is currently active
Dotnet SegmentType = "dotnet" DOTNET SegmentType = "dotnet"
// Terraform writes the terraform workspace we're currently in // TERRAFORM writes the terraform workspace we're currently in
Terraform SegmentType = "terraform" TERRAFORM SegmentType = "terraform"
// Golang writes which go version is currently active // GOLANG writes which go version is currently active
Golang SegmentType = "go" GOLANG SegmentType = "go"
// Julia writes which julia version is currently active // JULIA writes which julia version is currently active
Julia SegmentType = "julia" JULIA SegmentType = "julia"
// Powerline writes it Powerline style // Powerline writes it Powerline style
Powerline SegmentStyle = "powerline" Powerline SegmentStyle = "powerline"
// Plain writes it without ornaments // Plain writes it without ornaments
@ -103,48 +103,48 @@ const (
Diamond SegmentStyle = "diamond" Diamond SegmentStyle = "diamond"
// YTM writes YouTube Music information and status // YTM writes YouTube Music information and status
YTM SegmentType = "ytm" YTM SegmentType = "ytm"
// ExecutionTime writes the execution time of the last run command // EXECUTIONTIME writes the execution time of the last run command
ExecutionTime SegmentType = "executiontime" EXECUTIONTIME SegmentType = "executiontime"
// Ruby writes which ruby version is currently active // RUBY writes which ruby version is currently active
Ruby SegmentType = "ruby" RUBY SegmentType = "ruby"
// Aws writes the active aws context // AWS writes the active aws context
Aws SegmentType = "aws" AWS SegmentType = "aws"
// Java writes the active java version // JAVA writes the active java version
Java SegmentType = "java" JAVA SegmentType = "java"
// PoshGit writes the posh git prompt // POSHGIT writes the posh git prompt
PoshGit SegmentType = "poshgit" POSHGIT SegmentType = "poshgit"
// AZFunc writes current AZ func version // AZFUNC writes current AZ func version
AZFunc SegmentType = "azfunc" AZFUNC SegmentType = "azfunc"
// Crystal writes the active crystal version // CRYSTAL writes the active crystal version
Crystal SegmentType = "crystal" CRYSTAL SegmentType = "crystal"
// Dart writes the active dart version // DART writes the active dart version
Dart SegmentType = "dart" DART SegmentType = "dart"
// Nbgv writes the nbgv version information // NBGV writes the nbgv version information
Nbgv SegmentType = "nbgv" NBGV SegmentType = "nbgv"
// Rust writes the cargo version information if cargo.toml is present // RUST writes the cargo version information if cargo.toml is present
Rust SegmentType = "rust" RUST SegmentType = "rust"
// OWM writes the weather coming from openweatherdata // OWM writes the weather coming from openweatherdata
OWM SegmentType = "owm" OWM SegmentType = "owm"
// SysInfo writes system information (memory, cpu, load) // SYSTEMINFO writes system information (memory, cpu, load)
SysInfo SegmentType = "sysinfo" SYSTEMINFO SegmentType = "sysinfo"
// Angular writes which angular cli version us currently active // ANGULAR writes which angular cli version us currently active
Angular SegmentType = "angular" ANGULAR SegmentType = "angular"
// PHP writes which php version is currently active // PHP writes which php version is currently active
PHP SegmentType = "php" PHP SegmentType = "php"
// Nightscout is an open source diabetes system // NIGHTSCOUT is an open source diabetes system
Nightscout SegmentType = "nightscout" NIGHTSCOUT SegmentType = "nightscout"
// Strava is a sports activity tracker // STRAVA is a sports activity tracker
Strava SegmentType = "strava" STRAVA SegmentType = "strava"
// Wakatime writes tracked time spend in dev editors // WAKATIME writes tracked time spend in dev editors
Wakatime SegmentType = "wakatime" WAKATIME SegmentType = "wakatime"
// WiFi writes details about the current WiFi connection // WIFI writes details about the current WIFI connection
WiFi SegmentType = "wifi" WIFI SegmentType = "wifi"
// WinReg queries the Windows registry. // WINREG queries the Windows registry.
WinReg SegmentType = "winreg" WINREG SegmentType = "winreg"
// Brewfather segment // Brewfather segment
BrewFather SegmentType = "brewfather" BREWFATHER SegmentType = "brewfather"
// Ipify segment // IPIFY segment
Ipify SegmentType = "ipify" IPIFY SegmentType = "ipify"
) )
func (segment *Segment) string() string { func (segment *Segment) string() string {
@ -243,49 +243,49 @@ func (segment *Segment) background() string {
func (segment *Segment) mapSegmentWithWriter(env environment.Environment) error { func (segment *Segment) mapSegmentWithWriter(env environment.Environment) error {
segment.env = env segment.env = env
functions := map[SegmentType]SegmentWriter{ functions := map[SegmentType]SegmentWriter{
OWM: &owm{}, OWM: &Owm{},
Session: &session{}, SESSION: &Session{},
Path: &path{}, PATH: &Path{},
Git: &git{}, GIT: &Git{},
Plastic: &plastic{}, PLASTIC: &Plastic{},
Exit: &exit{}, EXIT: &Exit{},
Python: &python{}, PYTHON: &Python{},
Root: &root{}, ROOT: &Root{},
Text: &text{}, TEXT: &Text{},
Time: &tempus{}, TIME: &Time{},
Cmd: &command{}, CMD: &Cmd{},
Battery: &batt{}, BATTERY: &Battery{},
Spotify: &spotify{}, SPOTIFY: &Spotify{},
ShellInfo: &shell{}, SHELL: &Shell{},
Node: &node{}, NODE: &Node{},
Os: &osInfo{}, OS: &Os{},
Az: &az{}, AZ: &Az{},
Kubectl: &kubectl{}, KUBECTL: &Kubectl{},
Dotnet: &dotnet{}, DOTNET: &Dotnet{},
Terraform: &terraform{}, TERRAFORM: &Terraform{},
Golang: &golang{}, GOLANG: &Golang{},
Julia: &julia{}, JULIA: &Julia{},
YTM: &ytm{}, YTM: &Ytm{},
ExecutionTime: &executiontime{}, EXECUTIONTIME: &Executiontime{},
Ruby: &ruby{}, RUBY: &Ruby{},
Aws: &aws{}, AWS: &Aws{},
Java: &java{}, JAVA: &Java{},
PoshGit: &poshgit{}, POSHGIT: &PoshGit{},
AZFunc: &azfunc{}, AZFUNC: &AzFunc{},
Crystal: &crystal{}, CRYSTAL: &Crystal{},
Dart: &dart{}, DART: &Dart{},
Nbgv: &nbgv{}, NBGV: &Nbgv{},
Rust: &rust{}, RUST: &Rust{},
SysInfo: &sysinfo{}, SYSTEMINFO: &SystemInfo{},
Angular: &angular{}, ANGULAR: &Angular{},
PHP: &php{}, PHP: &Php{},
Nightscout: &nightscout{}, NIGHTSCOUT: &Nightscout{},
Strava: &strava{}, STRAVA: &Strava{},
Wakatime: &wakatime{}, WAKATIME: &Wakatime{},
WiFi: &wifi{}, WIFI: &Wifi{},
WinReg: &winreg{}, WINREG: &WindowsRegistry{},
BrewFather: &brewfather{}, BREWFATHER: &Brewfather{},
Ipify: &ipify{}, IPIFY: &IPify{},
} }
if segment.Properties == nil { if segment.Properties == nil {
segment.Properties = make(properties.Map) segment.Properties = make(properties.Map)

View file

@ -7,15 +7,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type angular struct { type Angular struct {
language language
} }
func (a *angular) template() string { func (a *Angular) template() string {
return languageTemplate return languageTemplate
} }
func (a *angular) init(props properties.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,
@ -50,6 +50,6 @@ func (a *angular) init(props properties.Properties, env environment.Environment)
} }
} }
func (a *angular) enabled() bool { func (a *Angular) enabled() bool {
return a.language.enabled() return a.language.enabled()
} }

View file

@ -36,7 +36,7 @@ func TestAngularCliVersionDisplayed(t *testing.T) {
Env: make(map[string]string), Env: make(map[string]string),
}) })
props := properties.Map{} 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))
assert.Equal(t, ta.FullVersion, renderTemplate(env, angular.template(), angular), fmt.Sprintf("Failed in case: %s", ta.Case)) assert.Equal(t, ta.FullVersion, renderTemplate(env, angular.template(), angular), fmt.Sprintf("Failed in case: %s", ta.Case))

View file

@ -7,7 +7,7 @@ import (
"strings" "strings"
) )
type aws struct { type Aws struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -19,16 +19,16 @@ const (
defaultUser = "default" defaultUser = "default"
) )
func (a *aws) template() string { func (a *Aws) template() string {
return "{{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }}" return "{{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }}"
} }
func (a *aws) init(props properties.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
} }
func (a *aws) enabled() bool { func (a *Aws) enabled() bool {
getEnvFirstMatch := func(envs ...string) string { getEnvFirstMatch := func(envs ...string) string {
for _, env := range envs { for _, env := range envs {
value := a.env.Getenv(env) value := a.env.Getenv(env)
@ -58,7 +58,7 @@ func (a *aws) enabled() bool {
return a.Profile != "" return a.Profile != ""
} }
func (a *aws) getConfigFileInfo() { func (a *Aws) getConfigFileInfo() {
configPath := a.env.Getenv("AWS_CONFIG_FILE") configPath := a.env.Getenv("AWS_CONFIG_FILE")
if configPath == "" { if configPath == "" {
configPath = fmt.Sprintf("%s/.aws/config", a.env.Home()) configPath = fmt.Sprintf("%s/.aws/config", a.env.Home())

View file

@ -59,7 +59,7 @@ func TestAWSSegment(t *testing.T) {
props := properties.Map{ props := properties.Map{
properties.DisplayDefault: tc.DisplayDefault, properties.DisplayDefault: tc.DisplayDefault,
} }
aws := &aws{ aws := &Aws{
env: env, env: env,
props: props, props: props,
} }

View file

@ -8,7 +8,7 @@ import (
"strings" "strings"
) )
type az struct { type Az struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -80,26 +80,26 @@ type AzurePowerShellSubscription struct {
} `json:"Environment"` } `json:"Environment"`
} }
func (a *az) template() string { func (a *Az) template() string {
return "{{ .Name }}" return "{{ .Name }}"
} }
func (a *az) init(props properties.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
} }
func (a *az) enabled() bool { func (a *Az) enabled() bool {
return a.getAzureProfile() || a.getAzureRmContext() return a.getAzureProfile() || a.getAzureRmContext()
} }
func (a *az) FileContentWithoutBom(file string) string { func (a *Az) FileContentWithoutBom(file string) string {
config := a.env.FileContent(file) config := a.env.FileContent(file)
const ByteOrderMark = "\ufeff" const ByteOrderMark = "\ufeff"
return strings.TrimLeft(config, ByteOrderMark) return strings.TrimLeft(config, ByteOrderMark)
} }
func (a *az) getAzureProfile() bool { func (a *Az) getAzureProfile() bool {
var content string var content string
profile := filepath.Join(a.env.Home(), ".azure", "azureProfile.json") profile := filepath.Join(a.env.Home(), ".azure", "azureProfile.json")
if content = a.FileContentWithoutBom(profile); len(content) == 0 { if content = a.FileContentWithoutBom(profile); len(content) == 0 {
@ -119,7 +119,7 @@ func (a *az) getAzureProfile() bool {
return false return false
} }
func (a *az) getAzureRmContext() bool { func (a *Az) getAzureRmContext() bool {
var content string var content string
profiles := []string{ profiles := []string{
filepath.Join(a.env.Home(), ".azure", "AzureRmContext.json"), filepath.Join(a.env.Home(), ".azure", "AzureRmContext.json"),

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type azfunc struct { type AzFunc struct {
language language
} }
func (az *azfunc) template() string { func (az *AzFunc) template() string {
return languageTemplate return languageTemplate
} }
func (az *azfunc) init(props properties.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,
@ -28,6 +28,6 @@ func (az *azfunc) init(props properties.Properties, env environment.Environment)
} }
} }
func (az *azfunc) enabled() bool { func (az *AzFunc) enabled() bool {
return az.language.enabled() return az.language.enabled()
} }

View file

@ -90,7 +90,7 @@ func TestAzSegment(t *testing.T) {
env.On("FileContent", filepath.Join(home, ".azure", "azureProfile.json")).Return(azureProfile) env.On("FileContent", filepath.Join(home, ".azure", "azureProfile.json")).Return(azureProfile)
env.On("FileContent", filepath.Join(home, ".Azure", "AzureRmContext.json")).Return(azureRmContext) env.On("FileContent", filepath.Join(home, ".Azure", "AzureRmContext.json")).Return(azureRmContext)
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.Map{}, props: properties.Map{},
} }

View file

@ -8,7 +8,7 @@ import (
"github.com/distatus/battery" "github.com/distatus/battery"
) )
type batt struct { type Battery struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -27,11 +27,11 @@ const (
ChargedIcon properties.Property = "charged_icon" ChargedIcon properties.Property = "charged_icon"
) )
func (b *batt) template() string { func (b *Battery) template() string {
return "{{ if not .Error }}{{.Icon}}{{.Percentage}}{{ end }}{{.Error}}" return "{{ if not .Error }}{{.Icon}}{{.Percentage}}{{ end }}{{.Error}}"
} }
func (b *batt) enabled() bool { func (b *Battery) enabled() bool {
batteries, err := b.env.BatteryInfo() batteries, err := b.env.BatteryInfo()
if !b.enabledWhileError(err) { if !b.enabledWhileError(err) {
@ -64,7 +64,7 @@ func (b *batt) enabled() bool {
return true return true
} }
func (b *batt) enabledWhileError(err error) bool { func (b *Battery) enabledWhileError(err error) bool {
if err == nil { if err == nil {
return true return true
} }
@ -86,7 +86,7 @@ func (b *batt) enabledWhileError(err error) bool {
return true return true
} }
func (b *batt) mapMostLogicalState(currentState, newState battery.State) battery.State { func (b *Battery) mapMostLogicalState(currentState, newState battery.State) battery.State {
switch currentState { switch currentState {
case battery.Discharging, battery.NotCharging: case battery.Discharging, battery.NotCharging:
return battery.Discharging return battery.Discharging
@ -105,7 +105,7 @@ func (b *batt) mapMostLogicalState(currentState, newState battery.State) battery
return newState return newState
} }
func (b *batt) init(props properties.Properties, env environment.Environment) { func (b *Battery) init(props properties.Properties, env environment.Environment) {
b.props = props b.props = props
b.env = env b.env = env
} }

View file

@ -24,7 +24,7 @@ func TestMapBatteriesState(t *testing.T) {
{Case: "discharging > empty", ExpectedState: battery.Discharging, CurrentState: battery.Empty, NewState: battery.Discharging}, {Case: "discharging > empty", ExpectedState: battery.Discharging, CurrentState: battery.Empty, NewState: battery.Discharging},
} }
for _, tc := range cases { for _, tc := range cases {
batt := &batt{} batt := &Battery{}
assert.Equal(t, tc.ExpectedState, batt.mapMostLogicalState(tc.CurrentState, tc.NewState), tc.Case) assert.Equal(t, tc.ExpectedState, batt.mapMostLogicalState(tc.CurrentState, tc.NewState), tc.Case)
} }
} }

View file

@ -14,7 +14,7 @@ import (
) )
// segment struct, makes templating easier // segment struct, makes templating easier
type brewfather struct { type Brewfather struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -100,11 +100,11 @@ type Batch struct {
TemperatureTrend float64 // diff between this and last, short term trend TemperatureTrend float64 // diff between this and last, short term trend
} }
func (bf *brewfather) template() string { func (bf *Brewfather) template() string {
return DefaultTemplate return DefaultTemplate
} }
func (bf *brewfather) enabled() bool { func (bf *Brewfather) enabled() bool {
data, err := bf.getResult() data, err := bf.getResult()
if err != nil { if err != nil {
return false return false
@ -151,7 +151,7 @@ func (bf *brewfather) enabled() bool {
return true return true
} }
func (bf *brewfather) getTrendIcon(trend float64) string { func (bf *Brewfather) getTrendIcon(trend float64) string {
// Not a fan of this logic - wondering if Go lets us do something cleaner... // Not a fan of this logic - wondering if Go lets us do something cleaner...
if trend >= 0 { if trend >= 0 {
if trend > 4 { if trend > 4 {
@ -184,7 +184,7 @@ func (bf *brewfather) getTrendIcon(trend float64) string {
return bf.props.GetString(BFFlatIcon, "→") return bf.props.GetString(BFFlatIcon, "→")
} }
func (bf *brewfather) getBatchStatusIcon(batchStatus string) string { func (bf *Brewfather) getBatchStatusIcon(batchStatus string) string {
switch batchStatus { switch batchStatus {
case BFStatusPlanning: case BFStatusPlanning:
return bf.props.GetString(BFPlanningStatusIcon, "\uF8EA") return bf.props.GetString(BFPlanningStatusIcon, "\uF8EA")
@ -203,7 +203,7 @@ func (bf *brewfather) getBatchStatusIcon(batchStatus string) string {
} }
} }
func (bf *brewfather) getResult() (*Batch, error) { func (bf *Brewfather) getResult() (*Batch, error) {
getFromCache := func(key string) (*Batch, error) { getFromCache := func(key string) (*Batch, error) {
val, found := bf.env.Cache().Get(key) val, found := bf.env.Cache().Get(key)
// we got something from the cache // we got something from the cache
@ -308,25 +308,25 @@ func (bf *brewfather) getResult() (*Batch, error) {
} }
// Unit conversion functions available to template. // Unit conversion functions available to template.
func (bf *brewfather) DegCToF(degreesC float64) float64 { func (bf *Brewfather) DegCToF(degreesC float64) float64 {
return math.Round(10*((degreesC*1.8)+32)) / 10 // 1 decimal place return math.Round(10*((degreesC*1.8)+32)) / 10 // 1 decimal place
} }
func (bf *brewfather) DegCToKelvin(degreesC float64) float64 { func (bf *Brewfather) DegCToKelvin(degreesC float64) float64 {
return math.Round(10*(degreesC+273.15)) / 10 // 1 decimal place, only addition, but just to be sure return math.Round(10*(degreesC+273.15)) / 10 // 1 decimal place, only addition, but just to be sure
} }
func (bf *brewfather) SGToBrix(sg float64) float64 { func (bf *Brewfather) SGToBrix(sg float64) float64 {
// from https://en.wikipedia.org/wiki/Brix#Specific_gravity_2 // from https://en.wikipedia.org/wiki/Brix#Specific_gravity_2
return math.Round(100*((182.4601*sg*sg*sg)-(775.6821*sg*sg)+(1262.7794*sg)-669.5622)) / 100 return math.Round(100*((182.4601*sg*sg*sg)-(775.6821*sg*sg)+(1262.7794*sg)-669.5622)) / 100
} }
func (bf *brewfather) SGToPlato(sg float64) float64 { func (bf *Brewfather) SGToPlato(sg float64) float64 {
// from https://en.wikipedia.org/wiki/Brix#Specific_gravity_2 // from https://en.wikipedia.org/wiki/Brix#Specific_gravity_2
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.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

@ -154,7 +154,7 @@ func TestBrewfatherSegment(t *testing.T) {
env.On("HTTPRequest", BFBatchReadingsURL).Return([]byte(tc.BatchReadingsJSONResponse), tc.Error) env.On("HTTPRequest", BFBatchReadingsURL).Return([]byte(tc.BatchReadingsJSONResponse), tc.Error)
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
ns := &brewfather{ ns := &Brewfather{
props: props, props: props,
env: env, env: env,
} }

View file

@ -6,7 +6,7 @@ import (
"strings" "strings"
) )
type command struct { type Cmd struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -20,11 +20,11 @@ const (
Command properties.Property = "command" Command properties.Property = "command"
) )
func (c *command) template() string { func (c *Cmd) template() string {
return "{{ .Output }}" return "{{ .Output }}"
} }
func (c *command) enabled() bool { func (c *Cmd) enabled() bool {
shell := c.props.GetString(ExecutableShell, "bash") shell := c.props.GetString(ExecutableShell, "bash")
if !c.env.HasCommand(shell) { if !c.env.HasCommand(shell) {
return false return false
@ -53,7 +53,7 @@ func (c *command) enabled() bool {
return c.Output != "" return c.Output != ""
} }
func (c *command) init(props properties.Properties, env environment.Environment) { func (c *Cmd) init(props properties.Properties, env environment.Environment) {
c.props = props c.props = props
c.env = env c.env = env
} }

View file

@ -15,7 +15,7 @@ func TestExecuteCommand(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "echo hello", Command: "echo hello",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -33,7 +33,7 @@ func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "exit 1 || echo hello", Command: "exit 1 || echo hello",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -50,7 +50,7 @@ func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "echo hello || echo world", Command: "echo hello || echo world",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -67,7 +67,7 @@ func TestExecuteMultipleCommandsAnd(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "echo hello && echo world", Command: "echo hello && echo world",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -83,7 +83,7 @@ func TestExecuteSingleCommandEmpty(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "", Command: "",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -96,7 +96,7 @@ func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
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.Map var props properties.Map
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -112,7 +112,7 @@ func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "echo && echo", Command: "echo && echo",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }
@ -128,7 +128,7 @@ func TestExecuteMultipleCommandsOrDisabled(t *testing.T) {
props := properties.Map{ props := properties.Map{
Command: "echo|| echo", Command: "echo|| echo",
} }
c := &command{ c := &Cmd{
props: props, props: props,
env: env, env: env,
} }

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type crystal struct { type Crystal struct {
language language
} }
func (c *crystal) template() string { func (c *Crystal) template() string {
return languageTemplate return languageTemplate
} }
func (c *crystal) init(props properties.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,
@ -29,6 +29,6 @@ func (c *crystal) init(props properties.Properties, env environment.Environment)
} }
} }
func (c *crystal) enabled() bool { func (c *Crystal) enabled() bool {
return c.language.enabled() return c.language.enabled()
} }

View file

@ -23,7 +23,7 @@ func TestCrystal(t *testing.T) {
extension: "*.cr", extension: "*.cr",
} }
env, props := getMockedLanguageEnv(params) env, props := getMockedLanguageEnv(params)
c := &crystal{} c := &Crystal{}
c.init(props, env) c.init(props, env)
assert.True(t, c.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, c.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, c.template(), c), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, c.template(), c), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type dart struct { type Dart struct {
language language
} }
func (d *dart) template() string { func (d *Dart) template() string {
return languageTemplate return languageTemplate
} }
func (d *dart) init(props properties.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,
@ -29,6 +29,6 @@ func (d *dart) init(props properties.Properties, env environment.Environment) {
} }
} }
func (d *dart) enabled() bool { func (d *Dart) enabled() bool {
return d.language.enabled() return d.language.enabled()
} }

View file

@ -23,7 +23,7 @@ func TestDart(t *testing.T) {
extension: "*.dart", extension: "*.dart",
} }
env, props := getMockedLanguageEnv(params) env, props := getMockedLanguageEnv(params)
d := &dart{} d := &Dart{}
d.init(props, env) d.init(props, env)
assert.True(t, d.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, d.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, d.template(), d), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, d.template(), d), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -5,17 +5,17 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type dotnet struct { type Dotnet struct {
language language
Unsupported bool Unsupported bool
} }
func (d *dotnet) template() string { 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.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,
@ -32,7 +32,7 @@ func (d *dotnet) init(props properties.Properties, env environment.Environment)
} }
} }
func (d *dotnet) enabled() bool { func (d *Dotnet) enabled() bool {
enabled := d.language.enabled() enabled := d.language.enabled()
if !enabled { if !enabled {
return false return false

View file

@ -44,7 +44,7 @@ func TestDotnetSegment(t *testing.T) {
props := properties.Map{ props := properties.Map{
properties.FetchVersion: tc.FetchVersion, properties.FetchVersion: tc.FetchVersion,
} }
dotnet := &dotnet{} dotnet := &Dotnet{}
dotnet.init(props, env) dotnet.init(props, env)
assert.True(t, dotnet.enabled()) assert.True(t, dotnet.enabled())
assert.Equal(t, tc.Expected, renderTemplate(env, dotnet.template(), dotnet), tc.Case) assert.Equal(t, tc.Expected, renderTemplate(env, dotnet.template(), dotnet), tc.Case)

View file

@ -10,7 +10,7 @@ import (
"golang.org/x/text/message" "golang.org/x/text/message"
) )
type executiontime struct { type Executiontime struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -48,7 +48,7 @@ const (
hoursPerDay = 24 hoursPerDay = 24
) )
func (t *executiontime) enabled() bool { func (t *Executiontime) enabled() bool {
alwaysEnabled := t.props.GetBool(properties.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))
@ -61,16 +61,16 @@ func (t *executiontime) enabled() bool {
return t.FormattedMs != "" return t.FormattedMs != ""
} }
func (t *executiontime) template() string { func (t *Executiontime) template() string {
return "{{ .FormattedMs }}" return "{{ .FormattedMs }}"
} }
func (t *executiontime) init(props properties.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
} }
func (t *executiontime) formatDuration(style DurationStyle) string { func (t *Executiontime) formatDuration(style DurationStyle) string {
switch style { switch style {
case Austin: case Austin:
return t.formatDurationAustin() return t.formatDurationAustin()
@ -91,7 +91,7 @@ func (t *executiontime) formatDuration(style DurationStyle) string {
} }
} }
func (t *executiontime) formatDurationAustin() string { func (t *Executiontime) formatDurationAustin() string {
if t.Ms < second { if t.Ms < second {
return fmt.Sprintf("%dms", t.Ms%second) return fmt.Sprintf("%dms", t.Ms%second)
} }
@ -111,7 +111,7 @@ func (t *executiontime) formatDurationAustin() string {
return result return result
} }
func (t *executiontime) formatDurationRoundrock() string { func (t *Executiontime) formatDurationRoundrock() string {
result := fmt.Sprintf("%dms", t.Ms%second) result := fmt.Sprintf("%dms", t.Ms%second)
if t.Ms >= second { if t.Ms >= second {
result = fmt.Sprintf("%ds %s", t.Ms/second%secondsPerMinute, result) result = fmt.Sprintf("%ds %s", t.Ms/second%secondsPerMinute, result)
@ -128,7 +128,7 @@ func (t *executiontime) formatDurationRoundrock() string {
return result return result
} }
func (t *executiontime) formatDurationDallas() string { func (t *Executiontime) formatDurationDallas() string {
seconds := float64(t.Ms%minute) / second seconds := float64(t.Ms%minute) / second
result := strconv.FormatFloat(seconds, 'f', -1, 64) result := strconv.FormatFloat(seconds, 'f', -1, 64)
@ -144,12 +144,12 @@ func (t *executiontime) formatDurationDallas() string {
return result return result
} }
func (t *executiontime) formatDurationGalveston() string { func (t *Executiontime) formatDurationGalveston() string {
result := fmt.Sprintf("%02d:%02d:%02d", t.Ms/hour, t.Ms/minute%minutesPerHour, t.Ms%minute/second) result := fmt.Sprintf("%02d:%02d:%02d", t.Ms/hour, t.Ms/minute%minutesPerHour, t.Ms%minute/second)
return result return result
} }
func (t *executiontime) formatDurationHouston() string { func (t *Executiontime) formatDurationHouston() string {
milliseconds := ".0" milliseconds := ".0"
if t.Ms%second > 0 { if t.Ms%second > 0 {
// format milliseconds as a string with truncated trailing zeros // format milliseconds as a string with truncated trailing zeros
@ -164,7 +164,7 @@ func (t *executiontime) formatDurationHouston() string {
return result return result
} }
func (t *executiontime) formatDurationAmarillo() string { func (t *Executiontime) formatDurationAmarillo() string {
// wholeNumber represents the value to the left of the decimal point (seconds) // wholeNumber represents the value to the left of the decimal point (seconds)
wholeNumber := t.Ms / second wholeNumber := t.Ms / second
// decimalNumber represents the value to the right of the decimal point (milliseconds) // decimalNumber represents the value to the right of the decimal point (milliseconds)
@ -188,7 +188,7 @@ func (t *executiontime) formatDurationAmarillo() string {
return result return result
} }
func (t *executiontime) formatDurationRound() string { func (t *Executiontime) formatDurationRound() string {
toRoundString := func(one, two int64, oneText, twoText string) string { toRoundString := func(one, two int64, oneText, twoText string) string {
if two == 0 { if two == 0 {
return fmt.Sprintf("%d%s", one, oneText) return fmt.Sprintf("%d%s", one, oneText)

View file

@ -12,7 +12,7 @@ import (
func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) { func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ExecutionTime").Return(1337) env.On("ExecutionTime").Return(1337)
executionTime := &executiontime{ executionTime := &Executiontime{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }
@ -22,7 +22,7 @@ func TestExecutionTimeWriterDefaultThresholdEnabled(t *testing.T) {
func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) { func TestExecutionTimeWriterDefaultThresholdDisabled(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ExecutionTime").Return(1) env.On("ExecutionTime").Return(1)
executionTime := &executiontime{ executionTime := &Executiontime{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }
@ -35,7 +35,7 @@ func TestExecutionTimeWriterCustomThresholdEnabled(t *testing.T) {
props := properties.Map{ props := properties.Map{
ThresholdProperty: float64(10), ThresholdProperty: float64(10),
} }
executionTime := &executiontime{ executionTime := &Executiontime{
env: env, env: env,
props: props, props: props,
} }
@ -48,7 +48,7 @@ func TestExecutionTimeWriterCustomThresholdDisabled(t *testing.T) {
props := properties.Map{ props := properties.Map{
ThresholdProperty: float64(100), ThresholdProperty: float64(100),
} }
executionTime := &executiontime{ executionTime := &Executiontime{
env: env, env: env,
props: props, props: props,
} }
@ -60,7 +60,7 @@ func TestExecutionTimeWriterDuration(t *testing.T) {
expected := "1.337s" expected := "1.337s"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ExecutionTime").Return(input) env.On("ExecutionTime").Return(input)
executionTime := &executiontime{ executionTime := &Executiontime{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }
@ -73,7 +73,7 @@ func TestExecutionTimeWriterDuration2(t *testing.T) {
expected := "3h 42m 51.337s" expected := "3h 42m 51.337s"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ExecutionTime").Return(input) env.On("ExecutionTime").Return(input)
executionTime := &executiontime{ executionTime := &Executiontime{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }
@ -100,7 +100,7 @@ func TestExecutionTimeFormatDurationAustin(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationAustin() output := executionTime.formatDurationAustin()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)
@ -126,7 +126,7 @@ func TestExecutionTimeFormatDurationRoundrock(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationRoundrock() output := executionTime.formatDurationRoundrock()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)
@ -152,7 +152,7 @@ func TestExecutionTimeFormatDallas(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationDallas() output := executionTime.formatDurationDallas()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)
@ -178,7 +178,7 @@ func TestExecutionTimeFormatGalveston(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationGalveston() output := executionTime.formatDurationGalveston()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)
@ -204,7 +204,7 @@ func TestExecutionTimeFormatHouston(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationHouston() output := executionTime.formatDurationHouston()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)
@ -230,7 +230,7 @@ func TestExecutionTimeFormatAmarillo(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationAmarillo() output := executionTime.formatDurationAmarillo()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)
@ -256,7 +256,7 @@ func TestExecutionTimeFormatDurationRound(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
duration, _ := time.ParseDuration(tc.Input) duration, _ := time.ParseDuration(tc.Input)
executionTime := &executiontime{} executionTime := &Executiontime{}
executionTime.Ms = duration.Milliseconds() executionTime.Ms = duration.Milliseconds()
output := executionTime.formatDurationRound() output := executionTime.formatDurationRound()
assert.Equal(t, tc.Expected, output) assert.Equal(t, tc.Expected, output)

View file

@ -6,18 +6,18 @@ import (
"strconv" "strconv"
) )
type exit struct { type Exit struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
Text string Text string
} }
func (e *exit) template() string { func (e *Exit) template() string {
return "{{ .Text }}" return "{{ .Text }}"
} }
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(properties.AlwaysEnabled, false) { if e.props.GetBool(properties.AlwaysEnabled, false) {
return true return true
@ -25,12 +25,12 @@ func (e *exit) enabled() bool {
return e.env.ErrorCode() != 0 return e.env.ErrorCode() != 0
} }
func (e *exit) init(props properties.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
} }
func (e *exit) getMeaningFromExitCode(code int) string { func (e *Exit) getMeaningFromExitCode(code int) string {
switch code { switch code {
case 1: case 1:
return "ERROR" return "ERROR"

View file

@ -22,7 +22,7 @@ func TestExitWriterEnabled(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("ErrorCode").Return(tc.ExitCode) env.On("ErrorCode").Return(tc.ExitCode)
e := &exit{ e := &Exit{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }
@ -61,7 +61,7 @@ func TestGetMeaningFromExitCode(t *testing.T) {
errorMap[151] = "151" errorMap[151] = "151"
errorMap[7000] = "7000" errorMap[7000] = "7000"
for exitcode, want := range errorMap { for exitcode, want := range errorMap {
e := &exit{} e := &Exit{}
assert.Equal(t, want, e.getMeaningFromExitCode(exitcode)) assert.Equal(t, want, e.getMeaningFromExitCode(exitcode))
} }
} }
@ -82,7 +82,7 @@ func TestExitWriterTemplateString(t *testing.T) {
env.On("TemplateCache").Return(&environment.TemplateCache{ env.On("TemplateCache").Return(&environment.TemplateCache{
Code: tc.ExitCode, Code: tc.ExitCode,
}) })
e := &exit{ e := &Exit{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }

View file

@ -31,7 +31,7 @@ func (s *GitStatus) add(code string) {
} }
} }
type git struct { type Git struct {
scm scm
Working *GitStatus Working *GitStatus
@ -107,11 +107,11 @@ const (
BRANCHPREFIX = "ref: refs/heads/" BRANCHPREFIX = "ref: refs/heads/"
) )
func (g *git) template() string { func (g *Git) template() string {
return "{{ .HEAD }} {{ .BranchStatus }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}" // nolint: lll return "{{ .HEAD }} {{ .BranchStatus }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}" // nolint: lll
} }
func (g *git) enabled() bool { func (g *Git) enabled() bool {
if !g.shouldDisplay() { if !g.shouldDisplay() {
return false return false
} }
@ -137,7 +137,7 @@ func (g *git) enabled() bool {
return true return true
} }
func (g *git) shouldDisplay() bool { func (g *Git) shouldDisplay() bool {
// when in wsl/wsl2 and in a windows shared folder // when in wsl/wsl2 and in a windows shared folder
// we must use git.exe and convert paths accordingly // we must use git.exe and convert paths accordingly
// for worktrees, stashes, and path to work // for worktrees, stashes, and path to work
@ -194,7 +194,7 @@ func (g *git) shouldDisplay() bool {
return false return false
} }
func (g *git) setBranchStatus() { func (g *Git) setBranchStatus() {
getBranchStatus := func() string { getBranchStatus := func() string {
if g.Ahead > 0 && g.Behind > 0 { if g.Ahead > 0 && g.Behind > 0 {
return fmt.Sprintf(" %s%d %s%d", g.props.GetString(BranchAheadIcon, "\u2191"), g.Ahead, g.props.GetString(BranchBehindIcon, "\u2193"), g.Behind) return fmt.Sprintf(" %s%d %s%d", g.props.GetString(BranchAheadIcon, "\u2191"), g.Ahead, g.props.GetString(BranchBehindIcon, "\u2193"), g.Behind)
@ -216,7 +216,7 @@ func (g *git) setBranchStatus() {
g.BranchStatus = getBranchStatus() g.BranchStatus = getBranchStatus()
} }
func (g *git) getUpstreamIcon() string { func (g *Git) getUpstreamIcon() string {
upstream := regex.ReplaceAllString("/.*", g.Upstream, "") upstream := regex.ReplaceAllString("/.*", g.Upstream, "")
g.UpstreamURL = g.getOriginURL(upstream) g.UpstreamURL = g.getOriginURL(upstream)
if strings.Contains(g.UpstreamURL, "github") { if strings.Contains(g.UpstreamURL, "github") {
@ -234,7 +234,7 @@ func (g *git) getUpstreamIcon() string {
return g.props.GetString(GitIcon, "\uE5FB ") return g.props.GetString(GitIcon, "\uE5FB ")
} }
func (g *git) setGitStatus() { func (g *Git) setGitStatus() {
addToStatus := func(status string) { addToStatus := func(status string) {
const UNTRACKED = "?" const UNTRACKED = "?"
if strings.HasPrefix(status, UNTRACKED) { if strings.HasPrefix(status, UNTRACKED) {
@ -285,7 +285,7 @@ func (g *git) setGitStatus() {
} }
} }
func (g *git) getGitCommand() string { func (g *Git) getGitCommand() string {
if len(g.gitCommand) > 0 { if len(g.gitCommand) > 0 {
return g.gitCommand return g.gitCommand
} }
@ -296,7 +296,7 @@ func (g *git) getGitCommand() string {
return g.gitCommand return g.gitCommand
} }
func (g *git) getGitCommandOutput(args ...string) string { func (g *Git) getGitCommandOutput(args ...string) string {
args = append([]string{"-C", g.gitRealFolder, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...) args = append([]string{"-C", g.gitRealFolder, "--no-optional-locks", "-c", "core.quotepath=false", "-c", "color.status=false"}, args...)
val, err := g.env.RunCommand(g.getGitCommand(), args...) val, err := g.env.RunCommand(g.getGitCommand(), args...)
if err != nil { if err != nil {
@ -305,7 +305,7 @@ func (g *git) getGitCommandOutput(args ...string) string {
return val return val
} }
func (g *git) setGitHEADContext() { func (g *Git) setGitHEADContext() {
branchIcon := g.props.GetString(BranchIcon, "\uE0A0") branchIcon := g.props.GetString(BranchIcon, "\uE0A0")
if g.Ref == DETACHED { if g.Ref == DETACHED {
g.setPrettyHEADName() g.setPrettyHEADName()
@ -413,7 +413,7 @@ func (g *git) setGitHEADContext() {
g.HEAD = formatDetached() g.HEAD = formatDetached()
} }
func (g *git) formatHEAD(head string) string { func (g *Git) formatHEAD(head string) string {
maxLength := g.props.GetInt(BranchMaxLength, 0) maxLength := g.props.GetInt(BranchMaxLength, 0)
if maxLength == 0 || len(head) < maxLength { if maxLength == 0 || len(head) < maxLength {
return head return head
@ -422,23 +422,23 @@ func (g *git) formatHEAD(head string) string {
return head[0:maxLength] + symbol return head[0:maxLength] + symbol
} }
func (g *git) formatSHA(sha string) string { func (g *Git) formatSHA(sha string) string {
if len(sha) <= 7 { if len(sha) <= 7 {
return sha return sha
} }
return sha[0:7] return sha[0:7]
} }
func (g *git) hasGitFile(file string) bool { func (g *Git) hasGitFile(file string) bool {
return g.env.HasFilesInDir(g.gitWorkingFolder, file) return g.env.HasFilesInDir(g.gitWorkingFolder, file)
} }
func (g *git) getGitRefFileSymbolicName(refFile string) string { func (g *Git) getGitRefFileSymbolicName(refFile string) string {
ref := g.FileContents(g.gitWorkingFolder, refFile) ref := g.FileContents(g.gitWorkingFolder, refFile)
return g.getGitCommandOutput("name-rev", "--name-only", "--exclude=tags/*", ref) return g.getGitCommandOutput("name-rev", "--name-only", "--exclude=tags/*", ref)
} }
func (g *git) setPrettyHEADName() { func (g *Git) setPrettyHEADName() {
// we didn't fetch status, fallback to parsing the HEAD file // we didn't fetch status, fallback to parsing the HEAD file
if len(g.Hash) == 0 { if len(g.Hash) == 0 {
HEADRef := g.FileContents(g.gitWorkingFolder, "HEAD") HEADRef := g.FileContents(g.gitWorkingFolder, "HEAD")
@ -466,7 +466,7 @@ func (g *git) setPrettyHEADName() {
g.HEAD = fmt.Sprintf("%s%s", g.props.GetString(CommitIcon, "\uF417"), g.Hash) g.HEAD = fmt.Sprintf("%s%s", g.props.GetString(CommitIcon, "\uF417"), g.Hash)
} }
func (g *git) getStashContext() int { func (g *Git) getStashContext() int {
stashContent := g.FileContents(g.gitRootFolder, "logs/refs/stash") stashContent := g.FileContents(g.gitRootFolder, "logs/refs/stash")
if stashContent == "" { if stashContent == "" {
return 0 return 0
@ -475,7 +475,7 @@ func (g *git) getStashContext() int {
return len(lines) return len(lines)
} }
func (g *git) getWorktreeContext() int { func (g *Git) getWorktreeContext() int {
if !g.env.HasFolder(g.gitRootFolder + "/worktrees") { if !g.env.HasFolder(g.gitRootFolder + "/worktrees") {
return 0 return 0
} }
@ -483,7 +483,7 @@ func (g *git) getWorktreeContext() int {
return len(worktreeFolders) return len(worktreeFolders)
} }
func (g *git) getOriginURL(upstream string) string { func (g *Git) getOriginURL(upstream string) string {
cleanSSHURL := func(url string) string { cleanSSHURL := func(url string) string {
if strings.HasPrefix(url, "http") { if strings.HasPrefix(url, "http") {
return url return url
@ -507,14 +507,14 @@ func (g *git) getOriginURL(upstream string) string {
return cleanSSHURL(url) return cleanSSHURL(url)
} }
func (g *git) convertToWindowsPath(path string) string { func (g *Git) convertToWindowsPath(path string) string {
if !g.IsWslSharedPath { if !g.IsWslSharedPath {
return path return path
} }
return g.env.ConvertToWindowsPath(path) return g.env.ConvertToWindowsPath(path)
} }
func (g *git) convertToLinuxPath(path string) string { func (g *Git) convertToLinuxPath(path string) string {
if !g.IsWslSharedPath { if !g.IsWslSharedPath {
return path return path
} }

View file

@ -21,7 +21,7 @@ func TestEnabledGitNotFound(t *testing.T) {
env.On("HasCommand", "git").Return(false) env.On("HasCommand", "git").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -44,7 +44,7 @@ func TestEnabledInWorkingDirectory(t *testing.T) {
env.MockGitCommand(fileInfo.Path, "", "describe", "--tags", "--exact-match") env.MockGitCommand(fileInfo.Path, "", "describe", "--tags", "--exact-match")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("HasParentFilePath", ".git").Return(fileInfo, nil) env.On("HasParentFilePath", ".git").Return(fileInfo, nil)
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -70,7 +70,7 @@ func TestEnabledInWorkingTree(t *testing.T) {
env.On("HasParentFilePath", ".git").Return(fileInfo, nil) env.On("HasParentFilePath", ".git").Return(fileInfo, nil)
env.On("FileContent", "/dev/folder_worktree/.git").Return("gitdir: /dev/real_folder/.git/worktrees/folder_worktree") env.On("FileContent", "/dev/folder_worktree/.git").Return("gitdir: /dev/real_folder/.git/worktrees/folder_worktree")
env.On("FileContent", "/dev/real_folder/.git/worktrees/folder_worktree/gitdir").Return("/dev/folder_worktree.git\n") env.On("FileContent", "/dev/real_folder/.git/worktrees/folder_worktree/gitdir").Return("/dev/folder_worktree.git\n")
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -97,7 +97,7 @@ func TestEnabledInSubmodule(t *testing.T) {
env.On("HasParentFilePath", ".git").Return(fileInfo, nil) env.On("HasParentFilePath", ".git").Return(fileInfo, nil)
env.On("FileContent", "/dev/parent/test-submodule/.git").Return("gitdir: ../.git/modules/test-submodule") env.On("FileContent", "/dev/parent/test-submodule/.git").Return("gitdir: ../.git/modules/test-submodule")
env.On("FileContent", "/dev/parent/.git/modules/test-submodule").Return("/dev/folder_worktree.git\n") env.On("FileContent", "/dev/parent/.git/modules/test-submodule").Return("/dev/folder_worktree.git\n")
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -117,7 +117,7 @@ func TestGetGitOutputForCommand(t *testing.T) {
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("RunCommand", "git", append(args, commandArgs...)).Return(want, nil) env.On("RunCommand", "git", append(args, commandArgs...)).Return(want, nil)
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -261,7 +261,7 @@ func TestSetGitHEADContextClean(t *testing.T) {
env.On("HasFilesInDir", "", "sequencer/todo").Return(tc.Sequencer) env.On("HasFilesInDir", "", "sequencer/todo").Return(tc.Sequencer)
env.On("FileContent", "/sequencer/todo").Return(tc.Theirs) env.On("FileContent", "/sequencer/todo").Return(tc.Theirs)
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{ props: properties.Map{
@ -303,7 +303,7 @@ func TestSetPrettyHEADName(t *testing.T) {
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.MockGitCommand("", tc.Tag, "describe", "--tags", "--exact-match") env.MockGitCommand("", tc.Tag, "describe", "--tags", "--exact-match")
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{ props: properties.Map{
@ -420,7 +420,7 @@ func TestSetGitStatus(t *testing.T) {
env.On("GOOS").Return("unix") env.On("GOOS").Return("unix")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.MockGitCommand("", strings.ReplaceAll(tc.Output, "\t", ""), "status", "-unormal", "--branch", "--porcelain=2") env.MockGitCommand("", strings.ReplaceAll(tc.Output, "\t", ""), "status", "-unormal", "--branch", "--porcelain=2")
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
}, },
@ -454,7 +454,7 @@ func TestGetStashContextZeroEntries(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("FileContent", "/logs/refs/stash").Return(tc.StashContent) env.On("FileContent", "/logs/refs/stash").Return(tc.StashContent)
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
}, },
@ -491,7 +491,7 @@ func TestGitUpstream(t *testing.T) {
AzureDevOpsIcon: "AD", AzureDevOpsIcon: "AD",
GitIcon: "G", GitIcon: "G",
} }
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
props: props, props: props,
@ -526,7 +526,7 @@ func TestGetBranchStatus(t *testing.T) {
BranchIdenticalIcon: "equal", BranchIdenticalIcon: "equal",
BranchGoneIcon: "gone", BranchGoneIcon: "gone",
} }
g := &git{ g := &Git{
scm: scm{ scm: scm{
props: props, props: props,
}, },
@ -566,7 +566,7 @@ func TestGetGitCommand(t *testing.T) {
wslUname = "4.4.0-19041-Microsoft" wslUname = "4.4.0-19041-Microsoft"
} }
env.On("RunCommand", "uname", []string{"-r"}).Return(wslUname, nil) env.On("RunCommand", "uname", []string{"-r"}).Return(wslUname, nil)
g := &git{ g := &Git{
scm: scm{ scm: scm{
env: env, env: env,
}, },
@ -586,13 +586,13 @@ func TestGitTemplateString(t *testing.T) {
Case string Case string
Expected string Expected string
Template string Template string
Git *git Git *Git
}{ }{
{ {
Case: "Only HEAD name", Case: "Only HEAD name",
Expected: branchName, Expected: branchName,
Template: "{{ .HEAD }}", Template: "{{ .HEAD }}",
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Behind: 2, Behind: 2,
}, },
@ -601,7 +601,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "Working area changes", Case: "Working area changes",
Expected: "main \uF044 +2 ~3", Expected: "main \uF044 +2 ~3",
Template: "{{ .HEAD }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}", Template: "{{ .HEAD }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}",
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Working: &GitStatus{ Working: &GitStatus{
ScmStatus: ScmStatus{ ScmStatus: ScmStatus{
@ -615,7 +615,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "No working area changes", Case: "No working area changes",
Expected: branchName, Expected: branchName,
Template: "{{ .HEAD }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}", Template: "{{ .HEAD }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}",
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Working: &GitStatus{}, Working: &GitStatus{},
}, },
@ -624,7 +624,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "Working and staging area changes", Case: "Working and staging area changes",
Expected: "main \uF046 +5 ~1 \uF044 +2 ~3", Expected: "main \uF046 +5 ~1 \uF044 +2 ~3",
Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}", Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}",
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Working: &GitStatus{ Working: &GitStatus{
ScmStatus: ScmStatus{ ScmStatus: ScmStatus{
@ -644,7 +644,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "Working and staging area changes with separator", Case: "Working and staging area changes with separator",
Expected: "main \uF046 +5 ~1 | \uF044 +2 ~3", Expected: "main \uF046 +5 ~1 | \uF044 +2 ~3",
Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}", //nolint:lll Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}", //nolint:lll
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Working: &GitStatus{ Working: &GitStatus{
ScmStatus: ScmStatus{ ScmStatus: ScmStatus{
@ -664,7 +664,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "Working and staging area changes with separator and stash count", Case: "Working and staging area changes with separator and stash count",
Expected: "main \uF046 +5 ~1 | \uF044 +2 ~3 \uf692 3", Expected: "main \uF046 +5 ~1 | \uF044 +2 ~3 \uf692 3",
Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}{{ if gt .StashCount 0 }} \uF692 {{ .StashCount }}{{ end }}", //nolint:lll Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046 {{ .Staging.String }}{{ end }}{{ if and (.Working.Changed) (.Staging.Changed) }} |{{ end }}{{ if .Working.Changed }} \uF044 {{ .Working.String }}{{ end }}{{ if gt .StashCount 0 }} \uF692 {{ .StashCount }}{{ end }}", //nolint:lll
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Working: &GitStatus{ Working: &GitStatus{
ScmStatus: ScmStatus{ ScmStatus: ScmStatus{
@ -685,7 +685,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "No local changes", Case: "No local changes",
Expected: branchName, Expected: branchName,
Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046{{ .Staging.String }}{{ end }}{{ if .Working.Changed }} \uF044{{ .Working.String }}{{ end }}", Template: "{{ .HEAD }}{{ if .Staging.Changed }} \uF046{{ .Staging.String }}{{ end }}{{ if .Working.Changed }} \uF044{{ .Working.String }}{{ end }}",
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Staging: &GitStatus{}, Staging: &GitStatus{},
Working: &GitStatus{}, Working: &GitStatus{},
@ -695,7 +695,7 @@ func TestGitTemplateString(t *testing.T) {
Case: "Upstream Icon", Case: "Upstream Icon",
Expected: "from GitHub on main", Expected: "from GitHub on main",
Template: "from {{ .UpstreamIcon }} on {{ .HEAD }}", Template: "from {{ .UpstreamIcon }} on {{ .HEAD }}",
Git: &git{ Git: &Git{
HEAD: branchName, HEAD: branchName,
Staging: &GitStatus{}, Staging: &GitStatus{},
Working: &GitStatus{}, Working: &GitStatus{},

View file

@ -7,7 +7,7 @@ import (
"golang.org/x/mod/modfile" "golang.org/x/mod/modfile"
) )
type golang struct { type Golang struct {
language language
} }
@ -15,11 +15,11 @@ const (
ParseModFile properties.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.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,
@ -39,7 +39,7 @@ func (g *golang) init(props properties.Properties, env environment.Environment)
} }
} }
func (g *golang) getVersion() (string, error) { func (g *Golang) getVersion() (string, error) {
if !g.props.GetBool(ParseModFile, false) { if !g.props.GetBool(ParseModFile, false) {
return "", nil return "", nil
} }
@ -55,6 +55,6 @@ func (g *golang) getVersion() (string, error) {
return file.Go.Version, nil return file.Go.Version, nil
} }
func (g *golang) enabled() bool { func (g *Golang) enabled() bool {
return g.language.enabled() return g.language.enabled()
} }

View file

@ -86,7 +86,7 @@ func TestGolang(t *testing.T) {
} }
env.On("FileContent", fileInfo.Path).Return(content) env.On("FileContent", fileInfo.Path).Return(content)
} }
g := &golang{} g := &Golang{}
g.init(props, env) g.init(props, env)
assert.True(t, g.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, g.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, g.template(), g), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, g.template(), g), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -5,7 +5,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type ipify struct { type IPify struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
IP string IP string
@ -15,11 +15,11 @@ const (
IpifyURL properties.Property = "url" IpifyURL properties.Property = "url"
) )
func (i *ipify) template() string { func (i *IPify) template() string {
return "{{ .IP }}" return "{{ .IP }}"
} }
func (i *ipify) enabled() bool { func (i *IPify) enabled() bool {
ip, err := i.getResult() ip, err := i.getResult()
if err != nil { if err != nil {
return false return false
@ -29,7 +29,7 @@ func (i *ipify) enabled() bool {
return true return true
} }
func (i *ipify) getResult() (string, error) { func (i *IPify) getResult() (string, error) {
cacheTimeout := i.props.GetInt(CacheTimeout, DefaultCacheTimeout) cacheTimeout := i.props.GetInt(CacheTimeout, DefaultCacheTimeout)
url := i.props.GetString(IpifyURL, "https://api.ipify.org") url := i.props.GetString(IpifyURL, "https://api.ipify.org")
@ -60,7 +60,7 @@ func (i *ipify) getResult() (string, error) {
return response, nil return response, nil
} }
func (i *ipify) init(props properties.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

@ -50,7 +50,7 @@ func TestIpifySegment(t *testing.T) {
} }
env.On("HTTPRequest", IPIFYAPIURL).Return([]byte(tc.Response), tc.Error) env.On("HTTPRequest", IPIFYAPIURL).Return([]byte(tc.Response), tc.Error)
ipify := &ipify{ ipify := &IPify{
props: props, props: props,
env: env, env: env,
} }

View file

@ -6,15 +6,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type java struct { type Java struct {
language language
} }
func (j *java) template() string { func (j *Java) template() string {
return languageTemplate return languageTemplate
} }
func (j *java) init(props properties.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",
@ -56,6 +56,6 @@ func (j *java) init(props properties.Properties, env environment.Environment) {
j.language.commands = []*cmd{javaCmd} j.language.commands = []*cmd{javaCmd}
} }
func (j *java) enabled() bool { func (j *Java) enabled() bool {
return j.language.enabled() return j.language.enabled()
} }

View file

@ -71,7 +71,7 @@ func TestJava(t *testing.T) {
props := properties.Map{ props := properties.Map{
properties.FetchVersion: true, properties.FetchVersion: true,
} }
j := &java{} j := &Java{}
j.init(props, env) j.init(props, env)
assert.True(t, j.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, j.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, j.template(), j), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, j.template(), j), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type julia struct { type Julia struct {
language language
} }
func (j *julia) template() string { func (j *Julia) template() string {
return languageTemplate return languageTemplate
} }
func (j *julia) init(props properties.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,
@ -29,6 +29,6 @@ func (j *julia) init(props properties.Properties, env environment.Environment) {
} }
} }
func (j *julia) enabled() bool { func (j *Julia) enabled() bool {
return j.language.enabled() return j.language.enabled()
} }

View file

@ -24,7 +24,7 @@ func TestJulia(t *testing.T) {
extension: "*.jl", extension: "*.jl",
} }
env, props := getMockedLanguageEnv(params) env, props := getMockedLanguageEnv(params)
j := &julia{} j := &Julia{}
j.init(props, env) j.init(props, env)
assert.True(t, j.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, j.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, j.template(), j), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, j.template(), j), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -11,7 +11,7 @@ import (
// Whether to use kubectl or read kubeconfig ourselves // Whether to use kubectl or read kubeconfig ourselves
const ParseKubeConfig properties.Property = "parse_kubeconfig" const ParseKubeConfig properties.Property = "parse_kubeconfig"
type kubectl struct { type Kubectl struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -34,16 +34,16 @@ type KubeContext struct {
Namespace string `yaml:"namespace"` Namespace string `yaml:"namespace"`
} }
func (k *kubectl) template() string { func (k *Kubectl) template() string {
return "{{ .Context }}{{ if .Namespace }} :: {{ .Namespace }}{{ end }}" return "{{ .Context }}{{ if .Namespace }} :: {{ .Namespace }}{{ end }}"
} }
func (k *kubectl) init(props properties.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
} }
func (k *kubectl) enabled() bool { func (k *Kubectl) enabled() bool {
parseKubeConfig := k.props.GetBool(ParseKubeConfig, false) parseKubeConfig := k.props.GetBool(ParseKubeConfig, false)
if parseKubeConfig { if parseKubeConfig {
return k.doParseKubeConfig() return k.doParseKubeConfig()
@ -51,7 +51,7 @@ func (k *kubectl) enabled() bool {
return k.doCallKubectl() return k.doCallKubectl()
} }
func (k *kubectl) doParseKubeConfig() bool { func (k *Kubectl) doParseKubeConfig() bool {
// Follow kubectl search rules (see https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#the-kubeconfig-environment-variable) // Follow kubectl search rules (see https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/#the-kubeconfig-environment-variable)
// TL;DR: KUBECONFIG can contain a list of files. If it's empty ~/.kube/config is used. First file in list wins when merging keys. // TL;DR: KUBECONFIG can contain a list of files. If it's empty ~/.kube/config is used. First file in list wins when merging keys.
kubeconfigs := filepath.SplitList(k.env.Getenv("KUBECONFIG")) kubeconfigs := filepath.SplitList(k.env.Getenv("KUBECONFIG"))
@ -101,7 +101,7 @@ func (k *kubectl) doParseKubeConfig() bool {
return true return true
} }
func (k *kubectl) doCallKubectl() bool { func (k *Kubectl) doCallKubectl() bool {
cmd := "kubectl" cmd := "kubectl"
if !k.env.HasCommand(cmd) { if !k.env.HasCommand(cmd) {
return false return false
@ -128,7 +128,7 @@ func (k *kubectl) doCallKubectl() bool {
return true return true
} }
func (k *kubectl) setError(message string) { func (k *Kubectl) setError(message string) {
if len(k.Context) == 0 { if len(k.Context) == 0 {
k.Context = message k.Context = message
} }

View file

@ -129,7 +129,7 @@ func TestKubectlSegment(t *testing.T) {
} }
env.On("Home").Return("testhome") env.On("Home").Return("testhome")
k := &kubectl{ k := &Kubectl{
env: env, env: env,
props: properties.Map{ props: properties.Map{
properties.DisplayError: tc.DisplayError, properties.DisplayError: tc.DisplayError,

View file

@ -6,7 +6,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type nbgv struct { type Nbgv struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -24,11 +24,11 @@ type VersionInfo struct {
SimpleVersion string `json:"SimpleVersion"` SimpleVersion string `json:"SimpleVersion"`
} }
func (n *nbgv) template() string { func (n *Nbgv) template() string {
return "{{ .Version }}" return "{{ .Version }}"
} }
func (n *nbgv) enabled() bool { func (n *Nbgv) enabled() bool {
nbgv := "nbgv" nbgv := "nbgv"
if !n.env.HasCommand(nbgv) { if !n.env.HasCommand(nbgv) {
return false return false
@ -45,7 +45,7 @@ func (n *nbgv) enabled() bool {
return n.VersionInfo.VersionFileFound return n.VersionInfo.VersionFileFound
} }
func (n *nbgv) init(props properties.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

@ -62,7 +62,7 @@ func TestNbgv(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", "nbgv").Return(tc.HasNbgv) env.On("HasCommand", "nbgv").Return(tc.HasNbgv)
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.Map{}, props: properties.Map{},
} }

View file

@ -9,7 +9,7 @@ import (
) )
// segment struct, makes templating easier // segment struct, makes templating easier
type nightscout struct { type Nightscout struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -47,11 +47,11 @@ type NightscoutData struct {
Mills int64 `json:"mills"` Mills int64 `json:"mills"`
} }
func (ns *nightscout) template() string { func (ns *Nightscout) template() string {
return "{{ .Sgv }}" return "{{ .Sgv }}"
} }
func (ns *nightscout) enabled() bool { func (ns *Nightscout) enabled() bool {
data, err := ns.getResult() data, err := ns.getResult()
if err != nil { if err != nil {
return false return false
@ -62,7 +62,7 @@ func (ns *nightscout) enabled() bool {
return true return true
} }
func (ns *nightscout) getTrendIcon() string { func (ns *Nightscout) getTrendIcon() string {
switch ns.Direction { switch ns.Direction {
case "DoubleUp": case "DoubleUp":
return ns.props.GetString(DoubleUpIcon, "↑↑") return ns.props.GetString(DoubleUpIcon, "↑↑")
@ -83,7 +83,7 @@ func (ns *nightscout) getTrendIcon() string {
} }
} }
func (ns *nightscout) getResult() (*NightscoutData, error) { func (ns *Nightscout) getResult() (*NightscoutData, error) {
parseSingleElement := func(data []byte) (*NightscoutData, error) { parseSingleElement := func(data []byte) (*NightscoutData, error) {
var result []*NightscoutData var result []*NightscoutData
err := json.Unmarshal(data, &result) err := json.Unmarshal(data, &result)
@ -139,7 +139,7 @@ func (ns *nightscout) getResult() (*NightscoutData, error) {
return data, nil return data, nil
} }
func (ns *nightscout) init(props properties.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

@ -144,7 +144,7 @@ func TestNSSegment(t *testing.T) {
env.On("HTTPRequest", FAKEAPIURL).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", FAKEAPIURL).Return([]byte(tc.JSONResponse), tc.Error)
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
ns := &nightscout{ ns := &Nightscout{
props: props, props: props,
env: env, env: env,
} }

View file

@ -7,7 +7,7 @@ import (
"oh-my-posh/regex" "oh-my-posh/regex"
) )
type node struct { type Node struct {
language language
PackageManagerIcon string PackageManagerIcon string
@ -22,11 +22,11 @@ const (
FetchPackageManager properties.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.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,
@ -44,11 +44,11 @@ func (n *node) init(props properties.Properties, env environment.Environment) {
} }
} }
func (n *node) enabled() bool { func (n *Node) enabled() bool {
return n.language.enabled() return n.language.enabled()
} }
func (n *node) loadContext() { func (n *Node) loadContext() {
if !n.language.props.GetBool(FetchPackageManager, false) { if !n.language.props.GetBool(FetchPackageManager, false) {
return return
} }
@ -61,7 +61,7 @@ func (n *node) loadContext() {
} }
} }
func (n *node) matchesVersionFile() bool { func (n *Node) matchesVersionFile() bool {
fileVersion := n.language.env.FileContent(".nvmrc") fileVersion := n.language.env.FileContent(".nvmrc")
if len(fileVersion) == 0 { if len(fileVersion) == 0 {
return true return true

View file

@ -34,7 +34,7 @@ func TestNodeMatchesVersionFile(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("FileContent", ".nvmrc").Return(tc.RCVersion) env.On("FileContent", ".nvmrc").Return(tc.RCVersion)
node := &node{ node := &Node{
language: language{ language: language{
env: env, env: env,
version: nodeVersion, version: nodeVersion,
@ -66,7 +66,7 @@ func TestNodeInContext(t *testing.T) {
env.On("HasFiles", "yarn.lock").Return(tc.HasYarn) env.On("HasFiles", "yarn.lock").Return(tc.HasYarn)
env.On("HasFiles", "package-lock.json").Return(tc.hasNPM) env.On("HasFiles", "package-lock.json").Return(tc.hasNPM)
env.On("HasFiles", "package.json").Return(tc.hasDefault) env.On("HasFiles", "package.json").Return(tc.hasDefault)
node := &node{ node := &Node{
language: language{ language: language{
env: env, env: env,
props: properties.Map{ props: properties.Map{

View file

@ -5,7 +5,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type osInfo struct { type Os struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -61,11 +61,11 @@ const (
DisplayDistroName properties.Property = "display_distro_name" DisplayDistroName properties.Property = "display_distro_name"
) )
func (oi *osInfo) template() string { func (oi *Os) template() string {
return "{{ if .WSL }}WSL at {{ end }}{{.Icon}}" return "{{ if .WSL }}WSL at {{ end }}{{.Icon}}"
} }
func (oi *osInfo) enabled() bool { func (oi *Os) enabled() bool {
goos := oi.env.GOOS() goos := oi.env.GOOS()
switch goos { switch goos {
case environment.WindowsPlatform: case environment.WindowsPlatform:
@ -86,7 +86,7 @@ func (oi *osInfo) enabled() bool {
return true return true
} }
func (oi *osInfo) getDistroIcon(distro string) string { func (oi *Os) getDistroIcon(distro string) string {
switch distro { switch distro {
case "alpine": case "alpine":
return oi.props.GetString(Alpine, "\uF300") return oi.props.GetString(Alpine, "\uF300")
@ -130,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.Properties, env environment.Environment) { func (oi *Os) init(props properties.Properties, env environment.Environment) {
oi.props = props oi.props = props
oi.env = env oi.env = env
} }

View file

@ -70,7 +70,7 @@ func TestOSInfo(t *testing.T) {
Env: make(map[string]string), Env: make(map[string]string),
WSL: tc.IsWSL, WSL: tc.IsWSL,
}) })
osInfo := &osInfo{ osInfo := &Os{
env: env, env: env,
props: properties.Map{ props: properties.Map{
DisplayDistroName: tc.DisplayDistroName, DisplayDistroName: tc.DisplayDistroName,

View file

@ -8,7 +8,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type owm struct { type Owm struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -48,16 +48,16 @@ type owmDataResponse struct {
temperature `json:"main"` temperature `json:"main"`
} }
func (d *owm) enabled() bool { func (d *Owm) enabled() bool {
err := d.setStatus() err := d.setStatus()
return err == nil return err == nil
} }
func (d *owm) template() string { func (d *Owm) template() string {
return "{{ .Weather }} ({{ .Temperature }}{{ .UnitIcon }})" return "{{ .Weather }} ({{ .Temperature }}{{ .UnitIcon }})"
} }
func (d *owm) getResult() (*owmDataResponse, error) { func (d *Owm) getResult() (*owmDataResponse, error) {
cacheTimeout := d.props.GetInt(CacheTimeout, DefaultCacheTimeout) cacheTimeout := d.props.GetInt(CacheTimeout, DefaultCacheTimeout)
response := new(owmDataResponse) response := new(owmDataResponse)
if cacheTimeout > 0 { if cacheTimeout > 0 {
@ -97,7 +97,7 @@ func (d *owm) getResult() (*owmDataResponse, error) {
return response, nil return response, nil
} }
func (d *owm) setStatus() error { func (d *Owm) setStatus() error {
units := d.props.GetString(Units, "standard") units := d.props.GetString(Units, "standard")
q, err := d.getResult() q, err := d.getResult()
if err != nil { if err != nil {
@ -164,7 +164,7 @@ func (d *owm) setStatus() error {
return nil return nil
} }
func (d *owm) init(props properties.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

@ -62,7 +62,7 @@ func TestOWMSegmentSingle(t *testing.T) {
env.On("HTTPRequest", OWMAPIURL).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", OWMAPIURL).Return([]byte(tc.JSONResponse), tc.Error)
o := &owm{ o := &Owm{
props: props, props: props,
env: env, env: env,
} }
@ -187,7 +187,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.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
@ -210,7 +210,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.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
@ -230,7 +230,7 @@ func TestOWMSegmentFromCache(t *testing.T) {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
cache := &mock.MockedCache{} cache := &mock.MockedCache{}
o := &owm{ o := &Owm{
props: properties.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",
@ -254,7 +254,7 @@ func TestOWMSegmentFromCacheWithHyperlink(t *testing.T) {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
cache := &mock.MockedCache{} cache := &mock.MockedCache{}
o := &owm{ o := &Owm{
props: properties.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",
Location: "AMSTERDAM,NL", Location: "AMSTERDAM,NL",

View file

@ -9,7 +9,7 @@ import (
"strings" "strings"
) )
type path struct { type Path struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -56,11 +56,11 @@ const (
MaxDepth properties.Property = "max_depth" MaxDepth properties.Property = "max_depth"
) )
func (pt *path) template() string { func (pt *Path) template() string {
return "{{ .Path }}" return "{{ .Path }}"
} }
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(properties.Style, Agnoster); style { switch style := pt.props.GetString(properties.Style, Agnoster); style {
case Agnoster: case Agnoster:
@ -96,19 +96,19 @@ func (pt *path) enabled() bool {
return true return true
} }
func (pt *path) formatWindowsDrive(pwd string) string { func (pt *Path) formatWindowsDrive(pwd string) string {
if pt.env.GOOS() != environment.WindowsPlatform || !strings.HasSuffix(pwd, ":") { if pt.env.GOOS() != environment.WindowsPlatform || !strings.HasSuffix(pwd, ":") {
return pwd return pwd
} }
return pwd + "\\" return pwd + "\\"
} }
func (pt *path) init(props properties.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
} }
func (pt *path) getMixedPath() string { func (pt *Path) getMixedPath() string {
var buffer strings.Builder var buffer strings.Builder
pwd := pt.getPwd() pwd := pt.getPwd()
splitted := strings.Split(pwd, pt.env.PathSeperator()) splitted := strings.Split(pwd, pt.env.PathSeperator())
@ -132,7 +132,7 @@ func (pt *path) getMixedPath() string {
return buffer.String() return buffer.String()
} }
func (pt *path) getAgnosterPath() string { func (pt *Path) getAgnosterPath() string {
var buffer strings.Builder var buffer strings.Builder
pwd := pt.getPwd() pwd := pt.getPwd()
buffer.WriteString(pt.rootLocation()) buffer.WriteString(pt.rootLocation())
@ -148,7 +148,7 @@ func (pt *path) getAgnosterPath() string {
return buffer.String() return buffer.String()
} }
func (pt *path) getAgnosterLeftPath() string { func (pt *Path) getAgnosterLeftPath() string {
pwd := pt.getPwd() pwd := pt.getPwd()
separator := pt.env.PathSeperator() separator := pt.env.PathSeperator()
pwd = strings.Trim(pwd, separator) pwd = strings.Trim(pwd, separator)
@ -171,7 +171,7 @@ func (pt *path) getAgnosterLeftPath() string {
return buffer.String() return buffer.String()
} }
func (pt *path) getLetterPath() string { func (pt *Path) getLetterPath() string {
var buffer strings.Builder var buffer strings.Builder
pwd := pt.getPwd() pwd := pt.getPwd()
splitted := strings.Split(pwd, pt.env.PathSeperator()) splitted := strings.Split(pwd, pt.env.PathSeperator())
@ -203,7 +203,7 @@ func (pt *path) getLetterPath() string {
return buffer.String() return buffer.String()
} }
func (pt *path) getAgnosterFullPath() string { func (pt *Path) getAgnosterFullPath() string {
pwd := pt.getPwd() pwd := pt.getPwd()
if len(pwd) > 1 && string(pwd[0]) == pt.env.PathSeperator() { if len(pwd) > 1 && string(pwd[0]) == pt.env.PathSeperator() {
pwd = pwd[1:] pwd = pwd[1:]
@ -211,7 +211,7 @@ func (pt *path) getAgnosterFullPath() string {
return pt.replaceFolderSeparators(pwd) return pt.replaceFolderSeparators(pwd)
} }
func (pt *path) getAgnosterShortPath() string { func (pt *Path) getAgnosterShortPath() string {
pwd := pt.getPwd() pwd := pt.getPwd()
pathDepth := pt.pathDepth(pwd) pathDepth := pt.pathDepth(pwd)
maxDepth := pt.props.GetInt(MaxDepth, 1) maxDepth := pt.props.GetInt(MaxDepth, 1)
@ -236,18 +236,18 @@ func (pt *path) getAgnosterShortPath() string {
return buffer.String() return buffer.String()
} }
func (pt *path) getFullPath() string { func (pt *Path) getFullPath() string {
pwd := pt.getPwd() pwd := pt.getPwd()
return pt.replaceFolderSeparators(pwd) return pt.replaceFolderSeparators(pwd)
} }
func (pt *path) getFolderPath() string { func (pt *Path) getFolderPath() string {
pwd := pt.getPwd() pwd := pt.getPwd()
pwd = environment.Base(pt.env, pwd) pwd = environment.Base(pt.env, pwd)
return pt.replaceFolderSeparators(pwd) return pt.replaceFolderSeparators(pwd)
} }
func (pt *path) getPwd() string { func (pt *Path) getPwd() string {
pwd := *pt.env.Args().PSWD pwd := *pt.env.Args().PSWD
if pwd == "" { if pwd == "" {
pwd = pt.env.Pwd() pwd = pt.env.Pwd()
@ -256,7 +256,7 @@ func (pt *path) getPwd() string {
return pwd return pwd
} }
func (pt *path) normalize(inputPath string) string { func (pt *Path) normalize(inputPath string) string {
normalized := inputPath normalized := inputPath
if strings.HasPrefix(inputPath, "~") { if strings.HasPrefix(inputPath, "~") {
normalized = pt.env.Home() + normalized[1:] normalized = pt.env.Home() + normalized[1:]
@ -269,7 +269,7 @@ func (pt *path) normalize(inputPath string) string {
return normalized return normalized
} }
func (pt *path) replaceMappedLocations(pwd string) string { func (pt *Path) replaceMappedLocations(pwd string) string {
if strings.HasPrefix(pwd, "Microsoft.PowerShell.Core\\FileSystem::") { if strings.HasPrefix(pwd, "Microsoft.PowerShell.Core\\FileSystem::") {
pwd = strings.Replace(pwd, "Microsoft.PowerShell.Core\\FileSystem::", "", 1) pwd = strings.Replace(pwd, "Microsoft.PowerShell.Core\\FileSystem::", "", 1)
} }
@ -309,7 +309,7 @@ func (pt *path) replaceMappedLocations(pwd string) string {
return pwd return pwd
} }
func (pt *path) replaceFolderSeparators(pwd string) string { func (pt *Path) replaceFolderSeparators(pwd string) string {
defaultSeparator := pt.env.PathSeperator() defaultSeparator := pt.env.PathSeperator()
if pwd == defaultSeparator { if pwd == defaultSeparator {
return pwd return pwd
@ -323,11 +323,11 @@ func (pt *path) replaceFolderSeparators(pwd string) string {
return pwd return pwd
} }
func (pt *path) inHomeDir(pwd string) bool { func (pt *Path) inHomeDir(pwd string) bool {
return strings.HasPrefix(pwd, pt.env.Home()) return strings.HasPrefix(pwd, pt.env.Home())
} }
func (pt *path) rootLocation() string { func (pt *Path) rootLocation() string {
pwd := pt.getPwd() pwd := pt.getPwd()
pwd = strings.TrimPrefix(pwd, pt.env.PathSeperator()) pwd = strings.TrimPrefix(pwd, pt.env.PathSeperator())
splitted := strings.Split(pwd, pt.env.PathSeperator()) splitted := strings.Split(pwd, pt.env.PathSeperator())
@ -335,7 +335,7 @@ func (pt *path) rootLocation() string {
return rootLocation return rootLocation
} }
func (pt *path) pathDepth(pwd string) int { func (pt *Path) pathDepth(pwd string) int {
splitted := strings.Split(pwd, pt.env.PathSeperator()) splitted := strings.Split(pwd, pt.env.PathSeperator())
depth := 0 depth := 0
for _, part := range splitted { for _, part := range splitted {

View file

@ -47,7 +47,7 @@ func TestIsInHomeDirTrue(t *testing.T) {
home := homeBill home := homeBill
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Home").Return(home) env.On("Home").Return(home)
path := &path{ path := &Path{
env: env, env: env,
} }
got := path.inHomeDir(home) got := path.inHomeDir(home)
@ -62,7 +62,7 @@ func TestIsInHomeDirLevelTrue(t *testing.T) {
} }
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Home").Return(home) env.On("Home").Return(home)
path := &path{ path := &Path{
env: env, env: env,
} }
got := path.inHomeDir(pwd) got := path.inHomeDir(pwd)
@ -98,7 +98,7 @@ func TestRootLocationHome(t *testing.T) {
env.On("Args").Return(args) env.On("Args").Return(args)
env.On("PathSeperator").Return(tc.PathSeperator) env.On("PathSeperator").Return(tc.PathSeperator)
env.On("GOOS").Return("") env.On("GOOS").Return("")
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
HomeIcon: tc.HomeIcon, HomeIcon: tc.HomeIcon,
@ -114,7 +114,7 @@ func TestIsInHomeDirFalse(t *testing.T) {
home := homeBill home := homeBill
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Home").Return(home) env.On("Home").Return(home)
path := &path{ path := &Path{
env: env, env: env,
} }
got := path.inHomeDir("/usr/error") got := path.inHomeDir("/usr/error")
@ -129,7 +129,7 @@ func TestPathDepthMultipleLevelsDeep(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("PathSeperator").Return("/") env.On("PathSeperator").Return("/")
env.On("getRunteGOOS").Return("") env.On("getRunteGOOS").Return("")
path := &path{ path := &Path{
env: env, env: env,
} }
got := path.pathDepth(pwd) got := path.pathDepth(pwd)
@ -140,7 +140,7 @@ func TestPathDepthZeroLevelsDeep(t *testing.T) {
pwd := "/usr/" pwd := "/usr/"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("PathSeperator").Return("/") env.On("PathSeperator").Return("/")
path := &path{ path := &Path{
env: env, env: env,
} }
got := path.pathDepth(pwd) got := path.pathDepth(pwd)
@ -151,7 +151,7 @@ func TestPathDepthOneLevelDeep(t *testing.T) {
pwd := "/usr/location" pwd := "/usr/location"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("PathSeperator").Return("/") env.On("PathSeperator").Return("/")
path := &path{ path := &Path{
env: env, env: env,
} }
got := path.pathDepth(pwd) got := path.pathDepth(pwd)
@ -251,7 +251,7 @@ func TestAgnosterPathStyles(t *testing.T) {
PSWD: &tc.Pswd, PSWD: &tc.Pswd,
} }
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
FolderSeparatorIcon: tc.FolderSeparatorIcon, FolderSeparatorIcon: tc.FolderSeparatorIcon,
@ -384,7 +384,7 @@ func TestGetFullPath(t *testing.T) {
if tc.DisableMappedLocations { if tc.DisableMappedLocations {
props[MappedLocationsEnabled] = false props[MappedLocationsEnabled] = false
} }
path := &path{ path := &Path{
env: env, env: env,
props: props, props: props,
} }
@ -421,7 +421,7 @@ func TestGetFullPathCustomMappedLocations(t *testing.T) {
PSWD: &tc.Pwd, PSWD: &tc.Pwd,
} }
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
MappedLocationsEnabled: false, MappedLocationsEnabled: false,
@ -453,7 +453,7 @@ func TestNormalizePath(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Home").Return("/usr/home") env.On("Home").Return("/usr/home")
env.On("GOOS").Return(tc.GOOS) env.On("GOOS").Return(tc.GOOS)
pt := &path{ pt := &Path{
env: env, env: env,
} }
got := pt.normalize(tc.Input) got := pt.normalize(tc.Input)
@ -472,7 +472,7 @@ func TestGetFolderPathCustomMappedLocations(t *testing.T) {
PSWD: &pwd, PSWD: &pwd,
} }
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
MappedLocations: map[string]string{ MappedLocations: map[string]string{
@ -519,7 +519,7 @@ func TestAgnosterPath(t *testing.T) { // nolint:dupl
PSWD: &tc.PWD, PSWD: &tc.PWD,
} }
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
FolderSeparatorIcon: " > ", FolderSeparatorIcon: " > ",
@ -567,7 +567,7 @@ func TestAgnosterLeftPath(t *testing.T) { // nolint:dupl
PSWD: &tc.PWD, PSWD: &tc.PWD,
} }
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
FolderSeparatorIcon: " > ", FolderSeparatorIcon: " > ",
@ -615,7 +615,7 @@ func TestGetPwd(t *testing.T) {
PSWD: &tc.Pswd, PSWD: &tc.Pswd,
} }
env.On("Args").Return(args) env.On("Args").Return(args)
path := &path{ path := &Path{
env: env, env: env,
props: properties.Map{ props: properties.Map{
MappedLocationsEnabled: tc.MappedLocationsEnabled, MappedLocationsEnabled: tc.MappedLocationsEnabled,

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type php struct { type Php struct {
language language
} }
func (p *php) template() string { func (p *Php) template() string {
return languageTemplate return languageTemplate
} }
func (p *php) init(props properties.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,
@ -29,6 +29,6 @@ func (p *php) init(props properties.Properties, env environment.Environment) {
} }
} }
func (p *php) enabled() bool { func (p *Php) enabled() bool {
return p.language.enabled() return p.language.enabled()
} }

View file

@ -24,7 +24,7 @@ func TestPhp(t *testing.T) {
extension: "*.php", extension: "*.php",
} }
env, props := getMockedLanguageEnv(params) env, props := getMockedLanguageEnv(params)
j := &php{} j := &Php{}
j.init(props, env) j.init(props, env)
assert.True(t, j.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, j.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, j.template(), j), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, j.template(), j), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -26,7 +26,7 @@ func (s *PlasticStatus) add(code string) {
} }
} }
type plastic struct { type Plastic struct {
scm scm
Status *PlasticStatus Status *PlasticStatus
@ -37,16 +37,16 @@ type plastic struct {
plasticWorkspaceFolder string // root folder of workspace plasticWorkspaceFolder string // root folder of workspace
} }
func (p *plastic) init(props properties.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
} }
func (p *plastic) template() string { func (p *Plastic) template() string {
return "{{ .Selector }}" return "{{ .Selector }}"
} }
func (p *plastic) enabled() bool { func (p *Plastic) enabled() bool {
if !p.env.HasCommand("cm") { if !p.env.HasCommand("cm") {
return false return false
} }
@ -69,7 +69,7 @@ func (p *plastic) enabled() bool {
return true return true
} }
func (p *plastic) setPlasticStatus() { func (p *Plastic) setPlasticStatus() {
output := p.getCmCommandOutput("status", "--all", "--machinereadable") output := p.getCmCommandOutput("status", "--all", "--machinereadable")
splittedOutput := strings.Split(output, "\n") splittedOutput := strings.Split(output, "\n")
// compare to head // compare to head
@ -83,7 +83,7 @@ func (p *plastic) setPlasticStatus() {
p.parseFilesStatus(splittedOutput) p.parseFilesStatus(splittedOutput)
} }
func (p *plastic) parseFilesStatus(output []string) { func (p *Plastic) parseFilesStatus(output []string) {
if len(output) <= 1 { if len(output) <= 1 {
return return
} }
@ -104,7 +104,7 @@ func (p *plastic) parseFilesStatus(output []string) {
} }
} }
func (p *plastic) parseStringPattern(output, pattern, name string) string { func (p *Plastic) parseStringPattern(output, pattern, name string) string {
match := regex.FindNamedRegexMatch(pattern, output) match := regex.FindNamedRegexMatch(pattern, output)
if sValue, ok := match[name]; ok { if sValue, ok := match[name]; ok {
return sValue return sValue
@ -112,7 +112,7 @@ func (p *plastic) parseStringPattern(output, pattern, name string) string {
return "" return ""
} }
func (p *plastic) parseIntPattern(output, pattern, name string, defValue int) int { func (p *Plastic) parseIntPattern(output, pattern, name string, defValue int) int {
sValue := p.parseStringPattern(output, pattern, name) sValue := p.parseStringPattern(output, pattern, name)
if len(sValue) > 0 { if len(sValue) > 0 {
iValue, _ := strconv.Atoi(sValue) iValue, _ := strconv.Atoi(sValue)
@ -121,16 +121,16 @@ func (p *plastic) parseIntPattern(output, pattern, name string, defValue int) in
return defValue return defValue
} }
func (p *plastic) parseStatusChangeset(status string) int { func (p *Plastic) parseStatusChangeset(status string) int {
return p.parseIntPattern(status, `STATUS\s+(?P<cs>[0-9]+?)\s`, "cs", 0) return p.parseIntPattern(status, `STATUS\s+(?P<cs>[0-9]+?)\s`, "cs", 0)
} }
func (p *plastic) getHeadChangeset() int { func (p *Plastic) getHeadChangeset() int {
output := p.getCmCommandOutput("status", "--head", "--machinereadable") output := p.getCmCommandOutput("status", "--head", "--machinereadable")
return p.parseIntPattern(output, `\bcs:(?P<cs>[0-9]+?)\s`, "cs", 0) return p.parseIntPattern(output, `\bcs:(?P<cs>[0-9]+?)\s`, "cs", 0)
} }
func (p *plastic) setSelector() { func (p *Plastic) setSelector() {
var ref string var ref string
selector := p.FileContents(p.plasticWorkspaceFolder+"/.plastic/", "plastic.selector") selector := p.FileContents(p.plasticWorkspaceFolder+"/.plastic/", "plastic.selector")
// changeset // changeset
@ -153,19 +153,19 @@ func (p *plastic) setSelector() {
p.Selector = fmt.Sprintf("%s%s", p.props.GetString(BranchIcon, "\uE0A0"), ref) p.Selector = fmt.Sprintf("%s%s", p.props.GetString(BranchIcon, "\uE0A0"), ref)
} }
func (p *plastic) parseChangesetSelector(selector string) string { func (p *Plastic) parseChangesetSelector(selector string) string {
return p.parseStringPattern(selector, `\bchangeset "(?P<cs>[0-9]+?)"`, "cs") return p.parseStringPattern(selector, `\bchangeset "(?P<cs>[0-9]+?)"`, "cs")
} }
func (p *plastic) parseLabelSelector(selector string) string { func (p *Plastic) parseLabelSelector(selector string) string {
return p.parseStringPattern(selector, `label "(?P<label>[a-zA-Z0-9\-\_]+?)"`, "label") return p.parseStringPattern(selector, `label "(?P<label>[a-zA-Z0-9\-\_]+?)"`, "label")
} }
func (p *plastic) parseBranchSelector(selector string) string { func (p *Plastic) parseBranchSelector(selector string) string {
return p.parseStringPattern(selector, `branch "(?P<branch>[\/a-zA-Z0-9\-\_]+?)"`, "branch") return p.parseStringPattern(selector, `branch "(?P<branch>[\/a-zA-Z0-9\-\_]+?)"`, "branch")
} }
func (p *plastic) getCmCommandOutput(args ...string) string { func (p *Plastic) getCmCommandOutput(args ...string) string {
val, _ := p.env.RunCommand("cm", args...) val, _ := p.env.RunCommand("cm", args...)
return val return val
} }

View file

@ -14,7 +14,7 @@ func TestPlasticEnabledNotFound(t *testing.T) {
env.On("HasCommand", "cm").Return(false) env.On("HasCommand", "cm").Return(false)
env.On("GOOS").Return("") env.On("GOOS").Return("")
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
p := &plastic{ p := &Plastic{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -35,7 +35,7 @@ func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) {
IsDir: true, IsDir: true,
} }
env.On("HasParentFilePath", ".plastic").Return(fileInfo, nil) env.On("HasParentFilePath", ".plastic").Return(fileInfo, nil)
p := &plastic{ p := &Plastic{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -45,11 +45,11 @@ func TestPlasticEnabledInWorkspaceDirectory(t *testing.T) {
assert.Equal(t, fileInfo.ParentFolder, p.plasticWorkspaceFolder) assert.Equal(t, fileInfo.ParentFolder, p.plasticWorkspaceFolder)
} }
func setupCmStatusEnv(status, headStatus string) *plastic { func setupCmStatusEnv(status, headStatus string) *Plastic {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("RunCommand", "cm", []string{"status", "--all", "--machinereadable"}).Return(status, nil) env.On("RunCommand", "cm", []string{"status", "--all", "--machinereadable"}).Return(status, nil)
env.On("RunCommand", "cm", []string{"status", "--head", "--machinereadable"}).Return(headStatus, nil) env.On("RunCommand", "cm", []string{"status", "--head", "--machinereadable"}).Return(headStatus, nil)
p := &plastic{ p := &Plastic{
scm: scm{ scm: scm{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
@ -219,7 +219,7 @@ func TestPlasticParseIntPattern(t *testing.T) {
}, },
} }
p := &plastic{} p := &Plastic{}
for _, tc := range cases { for _, tc := range cases {
value := p.parseIntPattern(tc.Text, tc.Pattern, tc.Name, tc.Default) value := p.parseIntPattern(tc.Text, tc.Pattern, tc.Name, tc.Default)
assert.Equal(t, tc.Expected, value, tc.Case) assert.Equal(t, tc.Expected, value, tc.Case)
@ -227,7 +227,7 @@ func TestPlasticParseIntPattern(t *testing.T) {
} }
func TestPlasticParseStatusChangeset(t *testing.T) { func TestPlasticParseStatusChangeset(t *testing.T) {
p := &plastic{} p := &Plastic{}
cs := p.parseStatusChangeset("STATUS 321 default localhost:8087") cs := p.parseStatusChangeset("STATUS 321 default localhost:8087")
assert.Equal(t, 321, cs) assert.Equal(t, 321, cs)
} }
@ -241,34 +241,34 @@ func TestPlasticGetHeadChangeset(t *testing.T) {
func TestPlasticParseChangesetSelector(t *testing.T) { func TestPlasticParseChangesetSelector(t *testing.T) {
content := "repository \"default\"\r\n path \"/\"\r\n smartbranch \"/main\" changeset \"321\"" content := "repository \"default\"\r\n path \"/\"\r\n smartbranch \"/main\" changeset \"321\""
p := &plastic{} p := &Plastic{}
selector := p.parseChangesetSelector(content) selector := p.parseChangesetSelector(content)
assert.Equal(t, "321", selector) assert.Equal(t, "321", selector)
} }
func TestPlasticParseLabelSelector(t *testing.T) { func TestPlasticParseLabelSelector(t *testing.T) {
content := "repository \"default\"\r\n path \"/\"\r\n label \"BL003\"" content := "repository \"default\"\r\n path \"/\"\r\n label \"BL003\""
p := &plastic{} p := &Plastic{}
selector := p.parseLabelSelector(content) selector := p.parseLabelSelector(content)
assert.Equal(t, "BL003", selector) assert.Equal(t, "BL003", selector)
} }
func TestPlasticParseBranchSelector(t *testing.T) { func TestPlasticParseBranchSelector(t *testing.T) {
content := "repository \"default\"\r\n path \"/\"\r\n branch \"/main/fix-004\"" content := "repository \"default\"\r\n path \"/\"\r\n branch \"/main/fix-004\""
p := &plastic{} p := &Plastic{}
selector := p.parseBranchSelector(content) selector := p.parseBranchSelector(content)
assert.Equal(t, "/main/fix-004", selector) assert.Equal(t, "/main/fix-004", selector)
} }
func TestPlasticParseSmartbranchSelector(t *testing.T) { func TestPlasticParseSmartbranchSelector(t *testing.T) {
content := "repository \"default\"\r\n path \"/\"\r\n smartbranch \"/main/fix-002\"" content := "repository \"default\"\r\n path \"/\"\r\n smartbranch \"/main/fix-002\""
p := &plastic{} p := &Plastic{}
selector := p.parseBranchSelector(content) selector := p.parseBranchSelector(content)
assert.Equal(t, "/main/fix-002", selector) assert.Equal(t, "/main/fix-002", selector)
} }
func TestPlasticStatus(t *testing.T) { func TestPlasticStatus(t *testing.T) {
p := &plastic{ p := &Plastic{
Status: &PlasticStatus{ Status: &PlasticStatus{
ScmStatus: ScmStatus{ ScmStatus: ScmStatus{
Added: 1, Added: 1,
@ -289,13 +289,13 @@ func TestPlasticTemplateString(t *testing.T) {
Case string Case string
Expected string Expected string
Template string Template string
Plastic *plastic Plastic *Plastic
}{ }{
{ {
Case: "Default template", Case: "Default template",
Expected: "/main", Expected: "/main",
Template: "{{ .Selector }}", Template: "{{ .Selector }}",
Plastic: &plastic{ Plastic: &Plastic{
Selector: "/main", Selector: "/main",
Behind: false, Behind: false,
}, },
@ -304,7 +304,7 @@ func TestPlasticTemplateString(t *testing.T) {
Case: "Workspace changes", Case: "Workspace changes",
Expected: "/main \uF044 +2 ~3 -1 >4", Expected: "/main \uF044 +2 ~3 -1 >4",
Template: "{{ .Selector }}{{ if .Status.Changed }} \uF044 {{ .Status.String }}{{ end }}", Template: "{{ .Selector }}{{ if .Status.Changed }} \uF044 {{ .Status.String }}{{ end }}",
Plastic: &plastic{ Plastic: &Plastic{
Selector: "/main", Selector: "/main",
Status: &PlasticStatus{ Status: &PlasticStatus{
ScmStatus: ScmStatus{ ScmStatus: ScmStatus{
@ -320,7 +320,7 @@ func TestPlasticTemplateString(t *testing.T) {
Case: "No workspace changes", Case: "No workspace changes",
Expected: "/main", Expected: "/main",
Template: "{{ .Selector }}{{ if .Status.Changed }} \uF044 {{ .Status.String }}{{ end }}", Template: "{{ .Selector }}{{ if .Status.Changed }} \uF044 {{ .Status.String }}{{ end }}",
Plastic: &plastic{ Plastic: &Plastic{
Selector: "/main", Selector: "/main",
Status: &PlasticStatus{}, Status: &PlasticStatus{},
}, },

View file

@ -6,7 +6,7 @@ import (
"strings" "strings"
) )
type poshgit struct { type PoshGit struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -17,17 +17,17 @@ const (
poshGitEnv = "POSH_GIT_STATUS" poshGitEnv = "POSH_GIT_STATUS"
) )
func (p *poshgit) template() string { func (p *PoshGit) template() string {
return "{{ .Status }}" return "{{ .Status }}"
} }
func (p *poshgit) enabled() bool { func (p *PoshGit) enabled() bool {
status := p.env.Getenv(poshGitEnv) status := p.env.Getenv(poshGitEnv)
p.Status = strings.TrimSpace(status) p.Status = strings.TrimSpace(status)
return p.Status != "" return p.Status != ""
} }
func (p *poshgit) init(props properties.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

@ -23,7 +23,7 @@ func TestPoshGitSegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Getenv", poshGitEnv).Return(tc.PoshGitPrompt) env.On("Getenv", poshGitEnv).Return(tc.PoshGitPrompt)
p := &poshgit{ p := &PoshGit{
env: env, env: env,
props: &properties.Map{}, props: &properties.Map{},
} }

View file

@ -5,7 +5,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type python struct { type Python struct {
language language
Venv string Venv string
@ -16,11 +16,11 @@ const (
FetchVirtualEnv properties.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.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,
@ -45,11 +45,11 @@ func (p *python) init(props properties.Properties, env environment.Environment)
} }
} }
func (p *python) enabled() bool { func (p *Python) enabled() bool {
return p.language.enabled() return p.language.enabled()
} }
func (p *python) loadContext() { func (p *Python) loadContext() {
if !p.language.props.GetBool(FetchVirtualEnv, true) { if !p.language.props.GetBool(FetchVirtualEnv, true) {
return return
} }
@ -70,11 +70,11 @@ func (p *python) loadContext() {
} }
} }
func (p *python) inContext() bool { func (p *Python) inContext() bool {
return p.Venv != "" return p.Venv != ""
} }
func (p *python) canUseVenvName(name string) bool { func (p *Python) canUseVenvName(name string) bool {
if name == "" || name == "." { if name == "" || name == "." {
return false return false
} }

View file

@ -62,7 +62,7 @@ func TestPythonTemplate(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),
}) })
python := &python{} python := &Python{}
python.init(props, env) python.init(props, env)
assert.Equal(t, !tc.ExpectedDisabled, python.enabled(), tc.Case) assert.Equal(t, !tc.ExpectedDisabled, python.enabled(), tc.Case)
assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, python), tc.Case) assert.Equal(t, tc.Expected, renderTemplate(env, tc.Template, python), tc.Case)
@ -85,7 +85,7 @@ func TestPythonPythonInContext(t *testing.T) {
env.On("Getenv", "CONDA_ENV_PATH").Return("") env.On("Getenv", "CONDA_ENV_PATH").Return("")
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.Map{}, 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

@ -5,20 +5,20 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type root struct { type Root struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
} }
func (rt *root) template() string { func (rt *Root) template() string {
return "\uF0E7" return "\uF0E7"
} }
func (rt *root) enabled() bool { func (rt *Root) enabled() bool {
return rt.env.Root() return rt.env.Root()
} }
func (rt *root) init(props properties.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

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type ruby struct { type Ruby struct {
language language
} }
func (r *ruby) template() string { func (r *Ruby) template() string {
return languageTemplate return languageTemplate
} }
func (r *ruby) init(props properties.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,
@ -48,7 +48,7 @@ func (r *ruby) init(props properties.Properties, env environment.Environment) {
} }
} }
func (r *ruby) enabled() bool { func (r *Ruby) enabled() bool {
enabled := r.language.enabled() enabled := r.language.enabled()
// this happens when no version is set // this happens when no version is set
if r.Full == "______" { if r.Full == "______" {

View file

@ -103,7 +103,7 @@ func TestRuby(t *testing.T) {
props := properties.Map{ props := properties.Map{
properties.FetchVersion: tc.FetchVersion, properties.FetchVersion: tc.FetchVersion,
} }
ruby := &ruby{} ruby := &Ruby{}
ruby.init(props, env) ruby.init(props, env)
assert.Equal(t, tc.ExpectedEnabled, ruby.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedEnabled, ruby.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, ruby.template(), ruby), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, ruby.template(), ruby), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type rust struct { type Rust struct {
language language
} }
func (r *rust) template() string { func (r *Rust) template() string {
return languageTemplate return languageTemplate
} }
func (r *rust) init(props properties.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,
@ -28,6 +28,6 @@ func (r *rust) init(props properties.Properties, env environment.Environment) {
} }
} }
func (r *rust) enabled() bool { func (r *Rust) enabled() bool {
return r.language.enabled() return r.language.enabled()
} }

View file

@ -23,7 +23,7 @@ func TestRust(t *testing.T) {
extension: "*.rs", extension: "*.rs",
} }
env, props := getMockedLanguageEnv(params) env, props := getMockedLanguageEnv(params)
r := &rust{} r := &Rust{}
r.init(props, env) r.init(props, env)
assert.True(t, r.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.True(t, r.enabled(), fmt.Sprintf("Failed in case: %s", tc.Case))
assert.Equal(t, tc.ExpectedString, renderTemplate(env, r.template(), r), fmt.Sprintf("Failed in case: %s", tc.Case)) assert.Equal(t, tc.ExpectedString, renderTemplate(env, r.template(), r), fmt.Sprintf("Failed in case: %s", tc.Case))

View file

@ -5,7 +5,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type session struct { type Session struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
// text string // text string
@ -16,21 +16,21 @@ type session struct {
DefaultUserName string DefaultUserName string
} }
func (s *session) enabled() bool { func (s *Session) enabled() bool {
s.SSHSession = s.activeSSHSession() s.SSHSession = s.activeSSHSession()
return true return true
} }
func (s *session) template() string { func (s *Session) template() string {
return "{{ .UserName }}@{{ .HostName }}" return "{{ .UserName }}@{{ .HostName }}"
} }
func (s *session) init(props properties.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
} }
func (s *session) activeSSHSession() bool { func (s *Session) activeSSHSession() bool {
keys := []string{ keys := []string{
"SSH_CONNECTION", "SSH_CONNECTION",
"SSH_CLIENT", "SSH_CLIENT",

View file

@ -109,7 +109,7 @@ func TestSessionSegmentTemplate(t *testing.T) {
}, },
Root: tc.Root, Root: tc.Root,
}) })
session := &session{ session := &Session{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }

View file

@ -6,7 +6,7 @@ import (
"strings" "strings"
) )
type shell struct { type Shell struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -18,11 +18,11 @@ const (
MappedShellNames properties.Property = "mapped_shell_names" MappedShellNames properties.Property = "mapped_shell_names"
) )
func (s *shell) template() string { func (s *Shell) template() string {
return "{{ .Name }}" return "{{ .Name }}"
} }
func (s *shell) enabled() bool { func (s *Shell) enabled() bool {
mappedNames := s.props.GetKeyValueMap(MappedShellNames, make(map[string]string)) mappedNames := s.props.GetKeyValueMap(MappedShellNames, make(map[string]string))
s.Name = s.env.Shell() s.Name = s.env.Shell()
for key, val := range mappedNames { for key, val := range mappedNames {
@ -34,7 +34,7 @@ func (s *shell) enabled() bool {
return true return true
} }
func (s *shell) init(props properties.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

@ -12,7 +12,7 @@ func TestWriteCurrentShell(t *testing.T) {
expected := "zsh" expected := "zsh"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Shell").Return(expected, nil) env.On("Shell").Return(expected, nil)
s := &shell{ s := &Shell{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
} }
@ -32,7 +32,7 @@ func TestUseMappedShellNames(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("Shell").Return(tc.Expected, nil) env.On("Shell").Return(tc.Expected, nil)
s := &shell{ s := &Shell{
env: env, env: env,
props: properties.Map{ props: properties.Map{
MappedShellNames: map[string]string{"pwsh": "PS"}, MappedShellNames: map[string]string{"pwsh": "PS"},

View file

@ -5,7 +5,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type spotify struct { type Spotify struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -32,11 +32,11 @@ const (
paused = "paused" paused = "paused"
) )
func (s *spotify) template() string { func (s *Spotify) template() string {
return "{{ .Icon }}{{ if ne .Status \"stopped\" }}{{ .Artist }} - {{ .Track }}{{ end }}" return "{{ .Icon }}{{ if ne .Status \"stopped\" }}{{ .Artist }} - {{ .Track }}{{ end }}"
} }
func (s *spotify) resolveIcon() { func (s *Spotify) resolveIcon() {
switch s.Status { switch s.Status {
case stopped: case stopped:
// in this case, no artist or track info // in this case, no artist or track info
@ -48,7 +48,7 @@ func (s *spotify) resolveIcon() {
} }
} }
func (s *spotify) init(props properties.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

@ -2,7 +2,7 @@
package main package main
func (s *spotify) enabled() bool { func (s *Spotify) enabled() bool {
var err error var err error
// Check if running // Check if running
running := s.runAppleScriptCommand("application \"Spotify\" is running") running := s.runAppleScriptCommand("application \"Spotify\" is running")
@ -24,7 +24,7 @@ func (s *spotify) enabled() bool {
return true return true
} }
func (s *spotify) runAppleScriptCommand(command string) string { func (s *Spotify) runAppleScriptCommand(command string) string {
val, _ := s.env.RunCommand("osascript", "-e", command) val, _ := s.env.RunCommand("osascript", "-e", command)
return val return val
} }

View file

@ -31,7 +31,7 @@ func TestSpotifyDarwinEnabledAndSpotifyPlaying(t *testing.T) {
env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(tc.Status, nil) env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to player state as string"}).Return(tc.Status, nil)
env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(tc.Artist, nil) env.On("RunCommand", "osascript", []string{"-e", "tell application \"Spotify\" to artist of current track as string"}).Return(tc.Artist, nil)
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.Map{}, props: properties.Map{},
} }

View file

@ -11,7 +11,7 @@ import (
func TestSpotifyStringPlayingSong(t *testing.T) { func TestSpotifyStringPlayingSong(t *testing.T) {
expected := "\ue602 Candlemass - Spellbreaker" expected := "\ue602 Candlemass - Spellbreaker"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
s := &spotify{ s := &Spotify{
MusicPlayer: MusicPlayer{ MusicPlayer: MusicPlayer{
Artist: "Candlemass", Artist: "Candlemass",
Track: "Spellbreaker", Track: "Spellbreaker",
@ -27,7 +27,7 @@ func TestSpotifyStringPlayingSong(t *testing.T) {
func TestSpotifyStringStoppedSong(t *testing.T) { func TestSpotifyStringStoppedSong(t *testing.T) {
expected := "\uf04d " expected := "\uf04d "
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
s := &spotify{ s := &Spotify{
MusicPlayer: MusicPlayer{ MusicPlayer: MusicPlayer{
Artist: "Candlemass", Artist: "Candlemass",
Track: "Spellbreaker", Track: "Spellbreaker",

View file

@ -12,7 +12,7 @@ import (
) )
// segment struct, makes templating easier // segment struct, makes templating easier
type strava struct { type Strava struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -70,11 +70,11 @@ func (a *AuthError) Error() string {
return a.message return a.message
} }
func (s *strava) template() string { func (s *Strava) template() string {
return "{{ if .Error }}{{ .Error }}{{ else }}{{ .Ago }}{{ end }}" return "{{ if .Error }}{{ .Error }}{{ else }}{{ .Ago }}{{ end }}"
} }
func (s *strava) enabled() bool { func (s *Strava) enabled() bool {
data, err := s.getResult() data, err := s.getResult()
if err == nil { if err == nil {
s.StravaData = *data s.StravaData = *data
@ -91,12 +91,12 @@ func (s *strava) enabled() bool {
return false return false
} }
func (s *strava) getHours() int { func (s *Strava) getHours() int {
hours := time.Since(s.StartDate).Hours() hours := time.Since(s.StartDate).Hours()
return int(math.Floor(hours)) return int(math.Floor(hours))
} }
func (s *strava) getAgo() string { func (s *Strava) getAgo() string {
if s.Hours > 24 { if s.Hours > 24 {
days := int32(math.Floor(float64(s.Hours) / float64(24))) days := int32(math.Floor(float64(s.Hours) / float64(24)))
return fmt.Sprintf("%d", days) + string('d') return fmt.Sprintf("%d", days) + string('d')
@ -104,7 +104,7 @@ func (s *strava) getAgo() string {
return fmt.Sprintf("%d", s.Hours) + string("h") return fmt.Sprintf("%d", s.Hours) + string("h")
} }
func (s *strava) getActivityIcon() string { func (s *Strava) getActivityIcon() string {
switch s.Type { switch s.Type {
case "VirtualRide": case "VirtualRide":
fallthrough fallthrough
@ -124,7 +124,7 @@ func (s *strava) getActivityIcon() string {
return s.props.GetString(UnknownActivityIcon, "\ue213") return s.props.GetString(UnknownActivityIcon, "\ue213")
} }
func (s *strava) getAccessToken() (string, error) { func (s *Strava) getAccessToken() (string, error) {
// get directly from cache // get directly from cache
if acccessToken, OK := s.env.Cache().Get(StravaAccessToken); OK { if acccessToken, OK := s.env.Cache().Get(StravaAccessToken); OK {
return acccessToken, nil return acccessToken, nil
@ -147,7 +147,7 @@ func (s *strava) getAccessToken() (string, error) {
return acccessToken, err return acccessToken, err
} }
func (s *strava) refreshToken(refreshToken string) (string, error) { func (s *Strava) refreshToken(refreshToken string) (string, error) {
httpTimeout := s.props.GetInt(HTTPTimeout, DefaultHTTPTimeout) httpTimeout := s.props.GetInt(HTTPTimeout, DefaultHTTPTimeout)
url := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=strava&token=%s", refreshToken) url := fmt.Sprintf("https://ohmyposh.dev/api/refresh?segment=strava&token=%s", refreshToken)
body, err := s.env.HTTPRequest(url, httpTimeout) body, err := s.env.HTTPRequest(url, httpTimeout)
@ -170,7 +170,7 @@ func (s *strava) refreshToken(refreshToken string) (string, error) {
return tokens.AccessToken, nil return tokens.AccessToken, nil
} }
func (s *strava) getResult() (*StravaData, error) { func (s *Strava) getResult() (*StravaData, error) {
parseSingleElement := func(data []byte) (*StravaData, error) { parseSingleElement := func(data []byte) (*StravaData, error) {
var result []*StravaData var result []*StravaData
err := json.Unmarshal(data, &result) err := json.Unmarshal(data, &result)
@ -231,7 +231,7 @@ func (s *strava) getResult() (*StravaData, error) {
return data, nil return data, nil
} }
func (s *strava) init(props properties.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

@ -164,7 +164,7 @@ func TestStravaSegment(t *testing.T) {
props[properties.RefreshToken] = tc.InitialRefreshToken props[properties.RefreshToken] = tc.InitialRefreshToken
} }
ns := &strava{ ns := &Strava{
props: props, props: props,
env: env, env: env,
} }

View file

@ -9,7 +9,7 @@ import (
mem "github.com/shirou/gopsutil/v3/mem" mem "github.com/shirou/gopsutil/v3/mem"
) )
type sysinfo struct { type SystemInfo struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -35,18 +35,18 @@ const (
Precision properties.Property = "precision" Precision properties.Property = "precision"
) )
func (s *sysinfo) template() string { func (s *SystemInfo) template() string {
return "{{ round .PhysicalPercentUsed .Precision }}" return "{{ round .PhysicalPercentUsed .Precision }}"
} }
func (s *sysinfo) enabled() bool { func (s *SystemInfo) enabled() bool {
if s.PhysicalPercentUsed == 0 && s.SwapPercentUsed == 0 { if s.PhysicalPercentUsed == 0 && s.SwapPercentUsed == 0 {
return false return false
} }
return true return true
} }
func (s *sysinfo) init(props properties.Properties, env environment.Environment) { func (s *SystemInfo) 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

@ -14,39 +14,39 @@ func TestSysInfo(t *testing.T) {
Case string Case string
ExpectedString string ExpectedString string
ExpectDisabled bool ExpectDisabled bool
SysInfo sysinfo SysInfo SystemInfo
Precision int Precision int
Template string Template string
}{ }{
{ {
Case: "physical mem", Case: "physical mem",
ExpectedString: "50", ExpectedString: "50",
SysInfo: sysinfo{PhysicalPercentUsed: 50}, SysInfo: SystemInfo{PhysicalPercentUsed: 50},
Template: "{{ round .PhysicalPercentUsed .Precision }}", Template: "{{ round .PhysicalPercentUsed .Precision }}",
}, },
{ {
Case: "physical mem 2 digits", Case: "physical mem 2 digits",
ExpectedString: "60.51", ExpectedString: "60.51",
SysInfo: sysinfo{Precision: 2, PhysicalPercentUsed: 60.51}, SysInfo: SystemInfo{Precision: 2, PhysicalPercentUsed: 60.51},
Template: "{{ round .PhysicalPercentUsed .Precision }}", Template: "{{ round .PhysicalPercentUsed .Precision }}",
}, },
{ {
Case: "physical meme rounded", Case: "physical meme rounded",
ExpectedString: "61", ExpectedString: "61",
SysInfo: sysinfo{Precision: 0, PhysicalPercentUsed: 61}, SysInfo: SystemInfo{Precision: 0, PhysicalPercentUsed: 61},
Template: "{{ round .PhysicalPercentUsed .Precision }}", Template: "{{ round .PhysicalPercentUsed .Precision }}",
}, },
{ {
Case: "load", Case: "load",
ExpectedString: "0.22 0.12 0", ExpectedString: "0.22 0.12 0",
Template: "{{ round .Load1 .Precision }} {{round .Load5 .Precision }} {{round .Load15 .Precision }}", Template: "{{ round .Load1 .Precision }} {{round .Load5 .Precision }} {{round .Load15 .Precision }}",
SysInfo: sysinfo{Precision: 2, Load1: 0.22, Load5: 0.12, Load15: 0}}, SysInfo: SystemInfo{Precision: 2, Load1: 0.22, Load5: 0.12, Load15: 0}},
{Case: "not enabled", ExpectDisabled: true, SysInfo: sysinfo{PhysicalPercentUsed: 0, SwapPercentUsed: 0}}, {Case: "not enabled", ExpectDisabled: true, SysInfo: SystemInfo{PhysicalPercentUsed: 0, SwapPercentUsed: 0}},
{ {
Case: "2 physical cpus", Case: "2 physical cpus",
ExpectedString: "1200 1200 ", ExpectedString: "1200 1200 ",
Template: "{{range $cpu := .CPU}}{{round $cpu.Mhz 2 }} {{end}}", Template: "{{range $cpu := .CPU}}{{round $cpu.Mhz 2 }} {{end}}",
SysInfo: sysinfo{CPU: []cpu.InfoStat{{Mhz: 1200}, {Mhz: 1200}}}, SysInfo: SystemInfo{CPU: []cpu.InfoStat{{Mhz: 1200}, {Mhz: 1200}}},
}, },
} }

View file

@ -5,23 +5,23 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type terraform struct { type Terraform struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
WorkspaceName string WorkspaceName string
} }
func (tf *terraform) template() string { func (tf *Terraform) template() string {
return "{{ .WorkspaceName }}" return "{{ .WorkspaceName }}"
} }
func (tf *terraform) init(props properties.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
} }
func (tf *terraform) enabled() bool { func (tf *Terraform) enabled() bool {
cmd := "terraform" cmd := "terraform"
if !tf.env.HasCommand(cmd) || !tf.env.HasFolder(tf.env.Pwd()+"/.terraform") { if !tf.env.HasCommand(cmd) || !tf.env.HasFolder(tf.env.Pwd()+"/.terraform") {
return false return false

View file

@ -14,13 +14,13 @@ type terraformArgs struct {
workspaceName string workspaceName string
} }
func bootStrapTerraformTest(args *terraformArgs) *terraform { func bootStrapTerraformTest(args *terraformArgs) *Terraform {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("HasCommand", "terraform").Return(args.hasTfCommand) env.On("HasCommand", "terraform").Return(args.hasTfCommand)
env.On("HasFolder", "/.terraform").Return(args.hasTfFolder) env.On("HasFolder", "/.terraform").Return(args.hasTfFolder)
env.On("Pwd").Return("") env.On("Pwd").Return("")
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.Map{}, props: properties.Map{},
} }

View file

@ -16,7 +16,7 @@ const (
func TestMapSegmentWriterCanMap(t *testing.T) { func TestMapSegmentWriterCanMap(t *testing.T) {
sc := &Segment{ sc := &Segment{
Type: Session, Type: SESSION,
} }
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
err := sc.mapSegmentWithWriter(env) err := sc.mapSegmentWithWriter(env)
@ -198,7 +198,7 @@ func TestGetColors(t *testing.T) {
Env: make(map[string]string), Env: make(map[string]string),
}) })
segment := &Segment{ segment := &Segment{
writer: &aws{ writer: &Aws{
Profile: tc.Profile, Profile: tc.Profile,
Region: tc.Region, Region: tc.Region,
}, },

View file

@ -5,22 +5,22 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type text struct { type Text struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
Text string Text string
} }
func (t *text) template() string { func (t *Text) template() string {
return "{{ .Text }}" return "{{ .Text }}"
} }
func (t *text) enabled() bool { func (t *Text) enabled() bool {
return true return true
} }
func (t *text) init(props properties.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

@ -39,7 +39,7 @@ func TestTextSegment(t *testing.T) {
Root: true, Root: true,
Folder: "posh", Folder: "posh",
}) })
txt := &text{ txt := &Text{
env: env, env: env,
props: properties.Map{ props: properties.Map{
properties.SegmentTemplate: tc.Template, properties.SegmentTemplate: tc.Template,

View file

@ -6,7 +6,7 @@ import (
"time" "time"
) )
type tempus struct { type Time struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -18,11 +18,11 @@ const (
TimeFormat properties.Property = "time_format" TimeFormat properties.Property = "time_format"
) )
func (t *tempus) template() string { func (t *Time) template() string {
return "{{ .CurrentDate | date \"" + t.props.GetString(TimeFormat, "15:04:05") + "\" }}" return "{{ .CurrentDate | date \"" + t.props.GetString(TimeFormat, "15:04:05") + "\" }}"
} }
func (t *tempus) enabled() bool { func (t *Time) enabled() bool {
// if no date set, use now(unit testing) // if no date set, use now(unit testing)
if t.CurrentDate.IsZero() { if t.CurrentDate.IsZero() {
t.CurrentDate = time.Now() t.CurrentDate = time.Now()
@ -30,7 +30,7 @@ func (t *tempus) enabled() bool {
return true return true
} }
func (t *tempus) init(props properties.Properties, env environment.Environment) { func (t *Time) init(props properties.Properties, env environment.Environment) {
t.props = props t.props = props
t.env = env t.env = env
} }

View file

@ -41,7 +41,7 @@ func TestTimeSegmentTemplate(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
tempus := &tempus{ tempus := &Time{
env: env, env: env,
props: properties.Map{}, props: properties.Map{},
CurrentDate: currentDate, CurrentDate: currentDate,

View file

@ -6,7 +6,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type wakatime struct { type Wakatime struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -24,16 +24,16 @@ type wtData struct {
End string `json:"end"` End string `json:"end"`
} }
func (w *wakatime) template() string { func (w *Wakatime) template() string {
return "{{ secondsRound .CummulativeTotal.Seconds }}" return "{{ secondsRound .CummulativeTotal.Seconds }}"
} }
func (w *wakatime) enabled() bool { func (w *Wakatime) enabled() bool {
err := w.setAPIData() err := w.setAPIData()
return err == nil return err == nil
} }
func (w *wakatime) setAPIData() error { func (w *Wakatime) setAPIData() error {
url := w.props.GetString(URL, "") url := w.props.GetString(URL, "")
cacheTimeout := w.props.GetInt(CacheTimeout, DefaultCacheTimeout) cacheTimeout := w.props.GetInt(CacheTimeout, DefaultCacheTimeout)
if cacheTimeout > 0 { if cacheTimeout > 0 {
@ -64,7 +64,7 @@ func (w *wakatime) setAPIData() error {
return nil return nil
} }
func (w *wakatime) init(props properties.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

@ -80,7 +80,7 @@ func TestWTTrackedTime(t *testing.T) {
cache.On("Set", FAKEAPIURL, response, tc.CacheTimeout).Return() cache.On("Set", FAKEAPIURL, response, tc.CacheTimeout).Return()
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
w := &wakatime{ w := &Wakatime{
props: properties.Map{ props: properties.Map{
APIKey: "key", APIKey: "key",
CacheTimeout: tc.CacheTimeout, CacheTimeout: tc.CacheTimeout,

View file

@ -5,7 +5,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type wifi struct { type Wifi struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -18,11 +18,11 @@ const (
defaultTemplate = "{{ if .Error }}{{ .Error }}{{ else }}\uFAA8 {{ .SSID }} {{ .Signal }}% {{ .ReceiveRate }}Mbps{{ end }}" defaultTemplate = "{{ if .Error }}{{ .Error }}{{ else }}\uFAA8 {{ .SSID }} {{ .Signal }}% {{ .ReceiveRate }}Mbps{{ end }}"
) )
func (w *wifi) template() string { func (w *Wifi) template() string {
return defaultTemplate return defaultTemplate
} }
func (w *wifi) enabled() bool { func (w *Wifi) enabled() bool {
// This segment only supports Windows/WSL for now // This segment only supports Windows/WSL for now
if w.env.Platform() != environment.WindowsPlatform && !w.env.IsWsl() { if w.env.Platform() != environment.WindowsPlatform && !w.env.IsWsl() {
return false return false
@ -40,7 +40,7 @@ func (w *wifi) enabled() bool {
return true return true
} }
func (w *wifi) init(props properties.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

@ -49,7 +49,7 @@ func TestWiFiSegment(t *testing.T) {
env.On("IsWsl").Return(false) env.On("IsWsl").Return(false)
env.On("WifiNetwork").Return(tc.Network, tc.WifiError) env.On("WifiNetwork").Return(tc.Network, tc.WifiError)
w := &wifi{ w := &Wifi{
env: env, env: env,
props: properties.Map{ props: properties.Map{
properties.DisplayError: tc.DisplayError, properties.DisplayError: tc.DisplayError,

View file

@ -7,7 +7,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type winreg struct { type WindowsRegistry struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -21,16 +21,16 @@ const (
Fallback properties.Property = "fallback" Fallback properties.Property = "fallback"
) )
func (wr *winreg) template() string { func (wr *WindowsRegistry) template() string {
return "{{ .Value }}" return "{{ .Value }}"
} }
func (wr *winreg) init(props properties.Properties, env environment.Environment) { func (wr *WindowsRegistry) init(props properties.Properties, env environment.Environment) {
wr.props = props wr.props = props
wr.env = env wr.env = env
} }
func (wr *winreg) enabled() bool { func (wr *WindowsRegistry) enabled() bool {
if wr.env.GOOS() != environment.WindowsPlatform { if wr.env.GOOS() != environment.WindowsPlatform {
return false return false
} }
@ -63,7 +63,7 @@ func (wr *winreg) enabled() bool {
return false return false
} }
func (wr winreg) GetRegistryString(path string) (string, error) { func (wr WindowsRegistry) GetRegistryString(path string) (string, error) {
regValue, err := wr.env.WindowsRegistryKeyValue(path) regValue, err := wr.env.WindowsRegistryKeyValue(path)
if regValue == nil { if regValue == nil {
@ -77,7 +77,7 @@ func (wr winreg) GetRegistryString(path string) (string, error) {
return regValue.Str, nil return regValue.Str, nil
} }
func (wr winreg) GetRegistryDword(path string) (uint32, error) { func (wr WindowsRegistry) GetRegistryDword(path string) (uint32, error) {
regValue, err := wr.env.WindowsRegistryKeyValue(path) regValue, err := wr.env.WindowsRegistryKeyValue(path)
if regValue == nil { if regValue == nil {
@ -91,7 +91,7 @@ func (wr winreg) GetRegistryDword(path string) (uint32, error) {
return regValue.Dword, nil return regValue.Dword, nil
} }
func (wr winreg) GetRegistryQword(path string) (uint64, error) { func (wr WindowsRegistry) GetRegistryQword(path string) (uint64, error) {
regValue, err := wr.env.WindowsRegistryKeyValue(path) regValue, err := wr.env.WindowsRegistryKeyValue(path)
if regValue == nil { if regValue == nil {

View file

@ -76,7 +76,7 @@ func TestWinReg(t *testing.T) {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("GOOS").Return(environment.WindowsPlatform) env.On("GOOS").Return(environment.WindowsPlatform)
env.On("WindowsRegistryKeyValue", tc.Path).Return(tc.getWRKVOutput, tc.Err) env.On("WindowsRegistryKeyValue", tc.Path).Return(tc.getWRKVOutput, tc.Err)
r := &winreg{ r := &WindowsRegistry{
env: env, env: env,
props: properties.Map{ props: properties.Map{
RegistryPath: tc.Path, RegistryPath: tc.Path,

View file

@ -6,7 +6,7 @@ import (
"oh-my-posh/properties" "oh-my-posh/properties"
) )
type ytm struct { type Ytm struct {
props properties.Properties props properties.Properties
env environment.Environment env environment.Environment
@ -18,18 +18,18 @@ const (
APIURL properties.Property = "api_url" APIURL properties.Property = "api_url"
) )
func (y *ytm) template() string { func (y *Ytm) template() string {
return "{{ .Icon }}{{ if ne .Status \"stopped\" }}{{ .Artist }} - {{ .Track }}{{ end }}" return "{{ .Icon }}{{ if ne .Status \"stopped\" }}{{ .Artist }} - {{ .Track }}{{ end }}"
} }
func (y *ytm) enabled() bool { func (y *Ytm) enabled() bool {
err := y.setStatus() err := y.setStatus()
// If we don't get a response back (error), the user isn't running // If we don't get a response back (error), the user isn't running
// YTMDA, or they don't have the RC API enabled. // YTMDA, or they don't have the RC API enabled.
return err == nil return err == nil
} }
func (y *ytm) init(props properties.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
} }
@ -64,7 +64,7 @@ type track struct {
InLibrary bool `json:"inLibrary"` InLibrary bool `json:"inLibrary"`
} }
func (y *ytm) setStatus() error { func (y *Ytm) setStatus() error {
// https://github.com/ytmdesktop/ytmdesktop/wiki/Remote-Control-API // https://github.com/ytmdesktop/ytmdesktop/wiki/Remote-Control-API
url := y.props.GetString(APIURL, "http://127.0.0.1:9863") url := y.props.GetString(APIURL, "http://127.0.0.1:9863")
httpTimeout := y.props.GetInt(APIURL, DefaultHTTPTimeout) httpTimeout := y.props.GetInt(APIURL, DefaultHTTPTimeout)

View file

@ -9,11 +9,11 @@ import (
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func bootstrapYTMDATest(json string, err error) *ytm { func bootstrapYTMDATest(json string, err error) *Ytm {
url := "http://127.0.0.1:9863" url := "http://127.0.0.1:9863"
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
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.Map{ props: properties.Map{
APIURL: url, APIURL: url,