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

View file

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

View file

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

View file

@ -7,15 +7,15 @@ import (
"oh-my-posh/properties"
)
type angular struct {
type Angular struct {
language
}
func (a *angular) template() string {
func (a *Angular) template() string {
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{
env: env,
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()
}

View file

@ -36,7 +36,7 @@ func TestAngularCliVersionDisplayed(t *testing.T) {
Env: make(map[string]string),
})
props := properties.Map{}
angular := &angular{}
angular := &Angular{}
angular.init(props, env)
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))

View file

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

View file

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

View file

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

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties"
)
type azfunc struct {
type AzFunc struct {
language
}
func (az *azfunc) template() string {
func (az *AzFunc) template() string {
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{
env: env,
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()
}

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", "AzureRmContext.json")).Return(azureRmContext)
env.On("FileContent", filepath.Join(home, ".azure", "AzureRmContext.json")).Return(azureRMContext)
az := &az{
az := &Az{
env: env,
props: properties.Map{},
}

View file

@ -8,7 +8,7 @@ import (
"github.com/distatus/battery"
)
type batt struct {
type Battery struct {
props properties.Properties
env environment.Environment
@ -27,11 +27,11 @@ const (
ChargedIcon properties.Property = "charged_icon"
)
func (b *batt) template() string {
func (b *Battery) template() string {
return "{{ if not .Error }}{{.Icon}}{{.Percentage}}{{ end }}{{.Error}}"
}
func (b *batt) enabled() bool {
func (b *Battery) enabled() bool {
batteries, err := b.env.BatteryInfo()
if !b.enabledWhileError(err) {
@ -64,7 +64,7 @@ func (b *batt) enabled() bool {
return true
}
func (b *batt) enabledWhileError(err error) bool {
func (b *Battery) enabledWhileError(err error) bool {
if err == nil {
return true
}
@ -86,7 +86,7 @@ func (b *batt) enabledWhileError(err error) bool {
return true
}
func (b *batt) mapMostLogicalState(currentState, newState battery.State) battery.State {
func (b *Battery) mapMostLogicalState(currentState, newState battery.State) battery.State {
switch currentState {
case battery.Discharging, battery.NotCharging:
return battery.Discharging
@ -105,7 +105,7 @@ func (b *batt) mapMostLogicalState(currentState, newState battery.State) battery
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.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},
}
for _, tc := range cases {
batt := &batt{}
batt := &Battery{}
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
type brewfather struct {
type Brewfather struct {
props properties.Properties
env environment.Environment
@ -100,11 +100,11 @@ type Batch struct {
TemperatureTrend float64 // diff between this and last, short term trend
}
func (bf *brewfather) template() string {
func (bf *Brewfather) template() string {
return DefaultTemplate
}
func (bf *brewfather) enabled() bool {
func (bf *Brewfather) enabled() bool {
data, err := bf.getResult()
if err != nil {
return false
@ -151,7 +151,7 @@ func (bf *brewfather) enabled() bool {
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...
if trend >= 0 {
if trend > 4 {
@ -184,7 +184,7 @@ func (bf *brewfather) getTrendIcon(trend float64) string {
return bf.props.GetString(BFFlatIcon, "→")
}
func (bf *brewfather) getBatchStatusIcon(batchStatus string) string {
func (bf *Brewfather) getBatchStatusIcon(batchStatus string) string {
switch batchStatus {
case BFStatusPlanning:
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) {
val, found := bf.env.Cache().Get(key)
// we got something from the cache
@ -308,25 +308,25 @@ func (bf *brewfather) getResult() (*Batch, error) {
}
// 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
}
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
}
func (bf *brewfather) SGToBrix(sg float64) float64 {
func (bf *Brewfather) SGToBrix(sg float64) float64 {
// 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
}
func (bf *brewfather) SGToPlato(sg float64) float64 {
func (bf *Brewfather) SGToPlato(sg float64) float64 {
// 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
}
func (bf *brewfather) init(props properties.Properties, env environment.Environment) {
func (bf *Brewfather) init(props properties.Properties, env environment.Environment) {
bf.props = props
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("Cache").Return(cache)
ns := &brewfather{
ns := &Brewfather{
props: props,
env: env,
}

View file

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

View file

@ -15,7 +15,7 @@ func TestExecuteCommand(t *testing.T) {
props := properties.Map{
Command: "echo hello",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -33,7 +33,7 @@ func TestExecuteMultipleCommandsOrFirst(t *testing.T) {
props := properties.Map{
Command: "exit 1 || echo hello",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -50,7 +50,7 @@ func TestExecuteMultipleCommandsOrSecond(t *testing.T) {
props := properties.Map{
Command: "echo hello || echo world",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -67,7 +67,7 @@ func TestExecuteMultipleCommandsAnd(t *testing.T) {
props := properties.Map{
Command: "echo hello && echo world",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -83,7 +83,7 @@ func TestExecuteSingleCommandEmpty(t *testing.T) {
props := properties.Map{
Command: "",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -96,7 +96,7 @@ func TestExecuteSingleCommandNoCommandProperty(t *testing.T) {
env.On("HasCommand", "bash").Return(true)
env.On("RunShellCommand", "bash", "echo no command specified").Return("no command specified")
var props properties.Map
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -112,7 +112,7 @@ func TestExecuteMultipleCommandsAndDisabled(t *testing.T) {
props := properties.Map{
Command: "echo && echo",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}
@ -128,7 +128,7 @@ func TestExecuteMultipleCommandsOrDisabled(t *testing.T) {
props := properties.Map{
Command: "echo|| echo",
}
c := &command{
c := &Cmd{
props: props,
env: env,
}

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties"
)
type crystal struct {
type Crystal struct {
language
}
func (c *crystal) template() string {
func (c *Crystal) template() string {
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{
env: env,
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()
}

View file

@ -23,7 +23,7 @@ func TestCrystal(t *testing.T) {
extension: "*.cr",
}
env, props := getMockedLanguageEnv(params)
c := &crystal{}
c := &Crystal{}
c.init(props, env)
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))

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties"
)
type dart struct {
type Dart struct {
language
}
func (d *dart) template() string {
func (d *Dart) template() string {
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{
env: env,
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()
}

View file

@ -23,7 +23,7 @@ func TestDart(t *testing.T) {
extension: "*.dart",
}
env, props := getMockedLanguageEnv(params)
d := &dart{}
d := &Dart{}
d.init(props, env)
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))

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -31,7 +31,7 @@ func (s *GitStatus) add(code string) {
}
}
type git struct {
type Git struct {
scm
Working *GitStatus
@ -107,11 +107,11 @@ const (
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
}
func (g *git) enabled() bool {
func (g *Git) enabled() bool {
if !g.shouldDisplay() {
return false
}
@ -137,7 +137,7 @@ func (g *git) enabled() bool {
return true
}
func (g *git) shouldDisplay() bool {
func (g *Git) shouldDisplay() bool {
// when in wsl/wsl2 and in a windows shared folder
// we must use git.exe and convert paths accordingly
// for worktrees, stashes, and path to work
@ -194,7 +194,7 @@ func (g *git) shouldDisplay() bool {
return false
}
func (g *git) setBranchStatus() {
func (g *Git) setBranchStatus() {
getBranchStatus := func() string {
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)
@ -216,7 +216,7 @@ func (g *git) setBranchStatus() {
g.BranchStatus = getBranchStatus()
}
func (g *git) getUpstreamIcon() string {
func (g *Git) getUpstreamIcon() string {
upstream := regex.ReplaceAllString("/.*", g.Upstream, "")
g.UpstreamURL = g.getOriginURL(upstream)
if strings.Contains(g.UpstreamURL, "github") {
@ -234,7 +234,7 @@ func (g *git) getUpstreamIcon() string {
return g.props.GetString(GitIcon, "\uE5FB ")
}
func (g *git) setGitStatus() {
func (g *Git) setGitStatus() {
addToStatus := func(status string) {
const 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 {
return g.gitCommand
}
@ -296,7 +296,7 @@ func (g *git) getGitCommand() string {
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...)
val, err := g.env.RunCommand(g.getGitCommand(), args...)
if err != nil {
@ -305,7 +305,7 @@ func (g *git) getGitCommandOutput(args ...string) string {
return val
}
func (g *git) setGitHEADContext() {
func (g *Git) setGitHEADContext() {
branchIcon := g.props.GetString(BranchIcon, "\uE0A0")
if g.Ref == DETACHED {
g.setPrettyHEADName()
@ -413,7 +413,7 @@ func (g *git) setGitHEADContext() {
g.HEAD = formatDetached()
}
func (g *git) formatHEAD(head string) string {
func (g *Git) formatHEAD(head string) string {
maxLength := g.props.GetInt(BranchMaxLength, 0)
if maxLength == 0 || len(head) < maxLength {
return head
@ -422,23 +422,23 @@ func (g *git) formatHEAD(head string) string {
return head[0:maxLength] + symbol
}
func (g *git) formatSHA(sha string) string {
func (g *Git) formatSHA(sha string) string {
if len(sha) <= 7 {
return sha
}
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)
}
func (g *git) getGitRefFileSymbolicName(refFile string) string {
func (g *Git) getGitRefFileSymbolicName(refFile string) string {
ref := g.FileContents(g.gitWorkingFolder, refFile)
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
if len(g.Hash) == 0 {
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)
}
func (g *git) getStashContext() int {
func (g *Git) getStashContext() int {
stashContent := g.FileContents(g.gitRootFolder, "logs/refs/stash")
if stashContent == "" {
return 0
@ -475,7 +475,7 @@ func (g *git) getStashContext() int {
return len(lines)
}
func (g *git) getWorktreeContext() int {
func (g *Git) getWorktreeContext() int {
if !g.env.HasFolder(g.gitRootFolder + "/worktrees") {
return 0
}
@ -483,7 +483,7 @@ func (g *git) getWorktreeContext() int {
return len(worktreeFolders)
}
func (g *git) getOriginURL(upstream string) string {
func (g *Git) getOriginURL(upstream string) string {
cleanSSHURL := func(url string) string {
if strings.HasPrefix(url, "http") {
return url
@ -507,14 +507,14 @@ func (g *git) getOriginURL(upstream string) string {
return cleanSSHURL(url)
}
func (g *git) convertToWindowsPath(path string) string {
func (g *Git) convertToWindowsPath(path string) string {
if !g.IsWslSharedPath {
return path
}
return g.env.ConvertToWindowsPath(path)
}
func (g *git) convertToLinuxPath(path string) string {
func (g *Git) convertToLinuxPath(path string) string {
if !g.IsWslSharedPath {
return path
}

View file

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

View file

@ -7,7 +7,7 @@ import (
"golang.org/x/mod/modfile"
)
type golang struct {
type Golang struct {
language
}
@ -15,11 +15,11 @@ const (
ParseModFile properties.Property = "parse_mod_file"
)
func (g *golang) template() string {
func (g *Golang) template() string {
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{
env: env,
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) {
return "", nil
}
@ -55,6 +55,6 @@ func (g *golang) getVersion() (string, error) {
return file.Go.Version, nil
}
func (g *golang) enabled() bool {
func (g *Golang) enabled() bool {
return g.language.enabled()
}

View file

@ -86,7 +86,7 @@ func TestGolang(t *testing.T) {
}
env.On("FileContent", fileInfo.Path).Return(content)
}
g := &golang{}
g := &Golang{}
g.init(props, env)
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))

View file

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

View file

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

View file

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

View file

@ -71,7 +71,7 @@ func TestJava(t *testing.T) {
props := properties.Map{
properties.FetchVersion: true,
}
j := &java{}
j := &Java{}
j.init(props, env)
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))

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties"
)
type julia struct {
type Julia struct {
language
}
func (j *julia) template() string {
func (j *Julia) template() string {
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{
env: env,
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()
}

View file

@ -24,7 +24,7 @@ func TestJulia(t *testing.T) {
extension: "*.jl",
}
env, props := getMockedLanguageEnv(params)
j := &julia{}
j := &Julia{}
j.init(props, env)
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))

View file

@ -11,7 +11,7 @@ import (
// Whether to use kubectl or read kubeconfig ourselves
const ParseKubeConfig properties.Property = "parse_kubeconfig"
type kubectl struct {
type Kubectl struct {
props properties.Properties
env environment.Environment
@ -34,16 +34,16 @@ type KubeContext struct {
Namespace string `yaml:"namespace"`
}
func (k *kubectl) template() string {
func (k *Kubectl) template() string {
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.env = env
}
func (k *kubectl) enabled() bool {
func (k *Kubectl) enabled() bool {
parseKubeConfig := k.props.GetBool(ParseKubeConfig, false)
if parseKubeConfig {
return k.doParseKubeConfig()
@ -51,7 +51,7 @@ func (k *kubectl) enabled() bool {
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)
// 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"))
@ -101,7 +101,7 @@ func (k *kubectl) doParseKubeConfig() bool {
return true
}
func (k *kubectl) doCallKubectl() bool {
func (k *Kubectl) doCallKubectl() bool {
cmd := "kubectl"
if !k.env.HasCommand(cmd) {
return false
@ -128,7 +128,7 @@ func (k *kubectl) doCallKubectl() bool {
return true
}
func (k *kubectl) setError(message string) {
func (k *Kubectl) setError(message string) {
if len(k.Context) == 0 {
k.Context = message
}

View file

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

View file

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

View file

@ -62,7 +62,7 @@ func TestNbgv(t *testing.T) {
env := new(mock.MockedEnvironment)
env.On("HasCommand", "nbgv").Return(tc.HasNbgv)
env.On("RunCommand", "nbgv", []string{"get-version", "--format=json"}).Return(tc.Response, tc.Error)
nbgv := &nbgv{
nbgv := &Nbgv{
env: env,
props: properties.Map{},
}

View file

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

View file

@ -7,7 +7,7 @@ import (
"oh-my-posh/regex"
)
type node struct {
type Node struct {
language
PackageManagerIcon string
@ -22,11 +22,11 @@ const (
FetchPackageManager properties.Property = "fetch_package_manager"
)
func (n *node) template() string {
func (n *Node) template() string {
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{
env: env,
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()
}
func (n *node) loadContext() {
func (n *Node) loadContext() {
if !n.language.props.GetBool(FetchPackageManager, false) {
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")
if len(fileVersion) == 0 {
return true

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties"
)
type php struct {
type Php struct {
language
}
func (p *php) template() string {
func (p *Php) template() string {
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{
env: env,
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()
}

View file

@ -24,7 +24,7 @@ func TestPhp(t *testing.T) {
extension: "*.php",
}
env, props := getMockedLanguageEnv(params)
j := &php{}
j := &Php{}
j.init(props, env)
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))

View file

@ -26,7 +26,7 @@ func (s *PlasticStatus) add(code string) {
}
}
type plastic struct {
type Plastic struct {
scm
Status *PlasticStatus
@ -37,16 +37,16 @@ type plastic struct {
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.env = env
}
func (p *plastic) template() string {
func (p *Plastic) template() string {
return "{{ .Selector }}"
}
func (p *plastic) enabled() bool {
func (p *Plastic) enabled() bool {
if !p.env.HasCommand("cm") {
return false
}
@ -69,7 +69,7 @@ func (p *plastic) enabled() bool {
return true
}
func (p *plastic) setPlasticStatus() {
func (p *Plastic) setPlasticStatus() {
output := p.getCmCommandOutput("status", "--all", "--machinereadable")
splittedOutput := strings.Split(output, "\n")
// compare to head
@ -83,7 +83,7 @@ func (p *plastic) setPlasticStatus() {
p.parseFilesStatus(splittedOutput)
}
func (p *plastic) parseFilesStatus(output []string) {
func (p *Plastic) parseFilesStatus(output []string) {
if len(output) <= 1 {
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)
if sValue, ok := match[name]; ok {
return sValue
@ -112,7 +112,7 @@ func (p *plastic) parseStringPattern(output, pattern, name string) string {
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)
if len(sValue) > 0 {
iValue, _ := strconv.Atoi(sValue)
@ -121,16 +121,16 @@ func (p *plastic) parseIntPattern(output, pattern, name string, defValue int) in
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)
}
func (p *plastic) getHeadChangeset() int {
func (p *Plastic) getHeadChangeset() int {
output := p.getCmCommandOutput("status", "--head", "--machinereadable")
return p.parseIntPattern(output, `\bcs:(?P<cs>[0-9]+?)\s`, "cs", 0)
}
func (p *plastic) setSelector() {
func (p *Plastic) setSelector() {
var ref string
selector := p.FileContents(p.plasticWorkspaceFolder+"/.plastic/", "plastic.selector")
// changeset
@ -153,19 +153,19 @@ func (p *plastic) setSelector() {
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")
}
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")
}
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")
}
func (p *plastic) getCmCommandOutput(args ...string) string {
func (p *Plastic) getCmCommandOutput(args ...string) string {
val, _ := p.env.RunCommand("cm", args...)
return val
}

View file

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

View file

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

View file

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

View file

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

View file

@ -62,7 +62,7 @@ func TestPythonTemplate(t *testing.T) {
env.On("TemplateCache").Return(&environment.TemplateCache{
Env: make(map[string]string),
})
python := &python{}
python := &Python{}
python.init(props, env)
assert.Equal(t, !tc.ExpectedDisabled, python.enabled(), 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_DEFAULT_ENV").Return("")
env.On("Getenv", "PYENV_VERSION").Return("")
python := &python{}
python := &Python{}
python.init(properties.Map{}, env)
python.loadContext()
assert.Equal(t, tc.Expected, python.inContext())

View file

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

View file

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

View file

@ -103,7 +103,7 @@ func TestRuby(t *testing.T) {
props := properties.Map{
properties.FetchVersion: tc.FetchVersion,
}
ruby := &ruby{}
ruby := &Ruby{}
ruby.init(props, env)
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))

View file

@ -5,15 +5,15 @@ import (
"oh-my-posh/properties"
)
type rust struct {
type Rust struct {
language
}
func (r *rust) template() string {
func (r *Rust) template() string {
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{
env: env,
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()
}

View file

@ -23,7 +23,7 @@ func TestRust(t *testing.T) {
extension: "*.rs",
}
env, props := getMockedLanguageEnv(params)
r := &rust{}
r := &Rust{}
r.init(props, env)
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))

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -14,39 +14,39 @@ func TestSysInfo(t *testing.T) {
Case string
ExpectedString string
ExpectDisabled bool
SysInfo sysinfo
SysInfo SystemInfo
Precision int
Template string
}{
{
Case: "physical mem",
ExpectedString: "50",
SysInfo: sysinfo{PhysicalPercentUsed: 50},
SysInfo: SystemInfo{PhysicalPercentUsed: 50},
Template: "{{ round .PhysicalPercentUsed .Precision }}",
},
{
Case: "physical mem 2 digits",
ExpectedString: "60.51",
SysInfo: sysinfo{Precision: 2, PhysicalPercentUsed: 60.51},
SysInfo: SystemInfo{Precision: 2, PhysicalPercentUsed: 60.51},
Template: "{{ round .PhysicalPercentUsed .Precision }}",
},
{
Case: "physical meme rounded",
ExpectedString: "61",
SysInfo: sysinfo{Precision: 0, PhysicalPercentUsed: 61},
SysInfo: SystemInfo{Precision: 0, PhysicalPercentUsed: 61},
Template: "{{ round .PhysicalPercentUsed .Precision }}",
},
{
Case: "load",
ExpectedString: "0.22 0.12 0",
Template: "{{ round .Load1 .Precision }} {{round .Load5 .Precision }} {{round .Load15 .Precision }}",
SysInfo: sysinfo{Precision: 2, Load1: 0.22, Load5: 0.12, Load15: 0}},
{Case: "not enabled", ExpectDisabled: true, SysInfo: sysinfo{PhysicalPercentUsed: 0, SwapPercentUsed: 0}},
SysInfo: SystemInfo{Precision: 2, Load1: 0.22, Load5: 0.12, Load15: 0}},
{Case: "not enabled", ExpectDisabled: true, SysInfo: SystemInfo{PhysicalPercentUsed: 0, SwapPercentUsed: 0}},
{
Case: "2 physical cpus",
ExpectedString: "1200 1200 ",
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"
)
type terraform struct {
type Terraform struct {
props properties.Properties
env environment.Environment
WorkspaceName string
}
func (tf *terraform) template() string {
func (tf *Terraform) template() string {
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.env = env
}
func (tf *terraform) enabled() bool {
func (tf *Terraform) enabled() bool {
cmd := "terraform"
if !tf.env.HasCommand(cmd) || !tf.env.HasFolder(tf.env.Pwd()+"/.terraform") {
return false

View file

@ -14,13 +14,13 @@ type terraformArgs struct {
workspaceName string
}
func bootStrapTerraformTest(args *terraformArgs) *terraform {
func bootStrapTerraformTest(args *terraformArgs) *Terraform {
env := new(mock.MockedEnvironment)
env.On("HasCommand", "terraform").Return(args.hasTfCommand)
env.On("HasFolder", "/.terraform").Return(args.hasTfFolder)
env.On("Pwd").Return("")
env.On("RunCommand", "terraform", []string{"workspace", "show"}).Return(args.workspaceName, nil)
k := &terraform{
k := &Terraform{
env: env,
props: properties.Map{},
}

View file

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

View file

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

View file

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

View file

@ -6,7 +6,7 @@ import (
"time"
)
type tempus struct {
type Time struct {
props properties.Properties
env environment.Environment
@ -18,11 +18,11 @@ const (
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") + "\" }}"
}
func (t *tempus) enabled() bool {
func (t *Time) enabled() bool {
// if no date set, use now(unit testing)
if t.CurrentDate.IsZero() {
t.CurrentDate = time.Now()
@ -30,7 +30,7 @@ func (t *tempus) enabled() bool {
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.env = env
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -9,11 +9,11 @@ import (
"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"
env := new(mock.MockedEnvironment)
env.On("HTTPRequest", url+"/query").Return([]byte(json), err)
ytm := &ytm{
ytm := &Ytm{
env: env,
props: properties.Map{
APIURL: url,