refactor(platform): rename to runtime

This commit is contained in:
Jan De Dobbeleer 2024-07-02 12:02:57 +02:00 committed by Jan De Dobbeleer
parent bab346fcc5
commit 05251e1ac3
207 changed files with 1186 additions and 1185 deletions

View file

@ -7,7 +7,7 @@ import (
"path/filepath"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra"
)
@ -34,8 +34,8 @@ You can do the following:
_ = cmd.Help()
return
}
env := &platform.Shell{
CmdFlags: &platform.Flags{},
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{},
}
env.Init()
defer env.Close()
@ -43,7 +43,7 @@ You can do the following:
case "path":
fmt.Print(env.CachePath())
case "clear":
cacheFilePath := filepath.Join(env.CachePath(), platform.CacheFile)
cacheFilePath := filepath.Join(env.CachePath(), runtime.CacheFile)
err := os.Remove(cacheFilePath)
if err != nil {
fmt.Println(err.Error())
@ -51,7 +51,7 @@ You can do the following:
}
fmt.Printf("removed cache file at %s\n", cacheFilePath)
case "edit":
cacheFilePath := filepath.Join(env.CachePath(), platform.CacheFile)
cacheFilePath := filepath.Join(env.CachePath(), runtime.CacheFile)
editFileWithEditor(cacheFilePath)
}
},

View file

@ -8,7 +8,7 @@ import (
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra"
)
@ -36,8 +36,8 @@ Exports the ~/myconfig.omp.json config file and prints the result to stdout.
Exports the ~/myconfig.omp.json config file to toml and prints the result to stdout.`,
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Config: configFlag,
},
}
@ -83,7 +83,7 @@ Exports the ~/myconfig.omp.json config file to toml and prints the result to std
},
}
func cleanOutputPath(path string, env platform.Environment) string {
func cleanOutputPath(path string, env runtime.Environment) string {
if strings.HasPrefix(path, "~") {
path = strings.TrimPrefix(path, "~")
path = filepath.Join(env.Home(), path)

View file

@ -5,8 +5,8 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/image"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/prompt"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
@ -49,8 +49,8 @@ Exports the config to an image file ~/mytheme.png.
Exports the config to an image file using customized output options.`,
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Config: configFlag,
Shell: shell.GENERIC,
TerminalWidth: 150,

View file

@ -4,7 +4,7 @@ import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra"
)
@ -39,8 +39,8 @@ Migrates the ~/myconfig.omp.json config file to TOML and writes the result to yo
A backup of the current config can be found at ~/myconfig.omp.json.bak.`,
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Config: configFlag,
Migrate: true,
},

View file

@ -4,7 +4,7 @@ import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra"
)
@ -34,8 +34,8 @@ Migrates the ~/myconfig.omp.json config file's glyphs and writes the result to y
A backup of the current config can be found at ~/myconfig.omp.json.bak.`,
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Config: configFlag,
},
}

View file

@ -6,8 +6,8 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/build"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/prompt"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
@ -23,8 +23,8 @@ var debugCmd = &cobra.Command{
Run: func(_ *cobra.Command, _ []string) {
startTime := time.Now()
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Config: configFlag,
Debug: true,
PWD: pwd,

View file

@ -3,7 +3,7 @@ package cli
import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/upgrade"
"github.com/spf13/cobra"
@ -42,8 +42,8 @@ func init() {
}
func toggleFeature(cmd *cobra.Command, feature string, enable bool) {
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Shell: shellName,
},
}

View file

@ -4,7 +4,7 @@ import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/font"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
"github.com/spf13/cobra"
@ -35,7 +35,7 @@ This command is used to install fonts and configure the font in your terminal.
if len(args) > 1 {
fontName = args[1]
}
env := &platform.Shell{}
env := &runtime.Terminal{}
env.Init()
defer env.Close()

View file

@ -6,7 +6,7 @@ import (
"time"
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
color2 "github.com/gookit/color"
"github.com/spf13/cobra"
@ -44,8 +44,8 @@ This command is used to get the value of the following variables:
return
}
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Shell: shellName,
},
}
@ -65,7 +65,7 @@ This command is used to get the value of the following variables:
fmt.Println("#" + accent.Hex())
case "toggles":
cache := env.Cache()
togglesCache, _ := cache.Get(platform.TOGGLECACHE)
togglesCache, _ := cache.Get(runtime.TOGGLECACHE)
var toggles []string
if len(togglesCache) != 0 {
toggles = strings.Split(togglesCache, ",")

View file

@ -4,7 +4,7 @@ import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
"github.com/jandedobbeleer/oh-my-posh/src/upgrade"
@ -55,8 +55,8 @@ func init() {
}
func runInit(shellName string) {
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Shell: shellName,
Config: configFlag,
Strict: strict,

View file

@ -3,7 +3,7 @@ package cli
import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/upgrade"
"github.com/spf13/cobra"
)
@ -15,8 +15,8 @@ var noticeCmd = &cobra.Command{
Long: "Print the upgrade notice when a new version is available.",
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
env := &platform.Shell{
CmdFlags: &platform.Flags{},
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{},
}
env.Init()
defer env.Close()

View file

@ -3,8 +3,8 @@ package cli
import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/prompt"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra"
)
@ -49,7 +49,7 @@ var printCmd = &cobra.Command{
return
}
flags := &platform.Flags{
flags := &runtime.Flags{
Config: configFlag,
PWD: pwd,
PSWD: pswd,

View file

@ -3,8 +3,7 @@ package cli
import (
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/cobra"
)
@ -19,12 +18,12 @@ var toggleCmd = &cobra.Command{
_ = cmd.Help()
return
}
env := &platform.Shell{}
env := &runtime.Terminal{}
env.Init()
defer env.Close()
cache := env.Cache()
togglesCache, _ := cache.Get(platform.TOGGLECACHE)
togglesCache, _ := cache.Get(runtime.TOGGLECACHE)
var toggles []string
if len(togglesCache) != 0 {
toggles = strings.Split(togglesCache, ",")
@ -45,7 +44,7 @@ var toggleCmd = &cobra.Command{
newToggles = append(newToggles, segment)
}
cache.Set(platform.TOGGLECACHE, strings.Join(newToggles, ","), 1440)
cache.Set(runtime.TOGGLECACHE, strings.Join(newToggles, ","), 1440)
},
}

View file

@ -2,11 +2,11 @@ package cli
import (
"fmt"
"runtime"
stdruntime "runtime"
"slices"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
"github.com/jandedobbeleer/oh-my-posh/src/upgrade"
"github.com/spf13/cobra"
@ -22,18 +22,18 @@ var upgradeCmd = &cobra.Command{
Args: cobra.NoArgs,
Run: func(_ *cobra.Command, _ []string) {
supportedPlatforms := []string{
platform.WINDOWS,
platform.DARWIN,
platform.LINUX,
runtime.WINDOWS,
runtime.DARWIN,
runtime.LINUX,
}
if !slices.Contains(supportedPlatforms, runtime.GOOS) {
if !slices.Contains(supportedPlatforms, stdruntime.GOOS) {
fmt.Print("\n⚠ upgrade is not supported on this platform\n\n")
return
}
env := &platform.Shell{
CmdFlags: &platform.Flags{},
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{},
}
env.Init()
defer env.Close()

View file

@ -6,7 +6,7 @@ import (
"strings"
"github.com/gookit/color"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
var TrueColor = true
@ -107,7 +107,7 @@ func (c Ansi) String() string {
return string(c)
}
func MakeColors(palette Palette, cacheEnabled bool, accentColor Ansi, env platform.Environment) (colors String) {
func MakeColors(palette Palette, cacheEnabled bool, accentColor Ansi, env runtime.Environment) (colors String) {
defaultColors := &Defaults{}
defaultColors.SetAccentColor(env, accentColor)
colors = defaultColors

View file

@ -6,7 +6,7 @@ import (
"github.com/alecthomas/assert"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
func TestGetAnsiFromColorString(t *testing.T) {
@ -40,7 +40,7 @@ func TestGetAnsiFromColorString(t *testing.T) {
func TestMakeColors(t *testing.T) {
env := &mock.MockedEnvironment{}
env.On("WindowsRegistryKeyValue", `HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM\ColorizationColor`).Return(&platform.WindowsRegistryValue{}, errors.New("err"))
env.On("WindowsRegistryKeyValue", `HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM\ColorizationColor`).Return(&runtime.WindowsRegistryValue{}, errors.New("err"))
colors := MakeColors(nil, false, "", env)
assert.IsType(t, &Defaults{}, colors)

View file

@ -2,13 +2,13 @@
package color
import "github.com/jandedobbeleer/oh-my-posh/src/platform"
import "github.com/jandedobbeleer/oh-my-posh/src/runtime"
func GetAccentColor(_ platform.Environment) (*RGB, error) {
return nil, &platform.NotImplemented{}
func GetAccentColor(_ runtime.Environment) (*RGB, error) {
return nil, &runtime.NotImplemented{}
}
func (d *Defaults) SetAccentColor(_ platform.Environment, defaultColor Ansi) {
func (d *Defaults) SetAccentColor(_ runtime.Environment, defaultColor Ansi) {
if len(defaultColor) == 0 {
return
}

View file

@ -3,19 +3,18 @@ package color
import (
"errors"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/gookit/color"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
func GetAccentColor(env platform.Environment) (*RGB, error) {
func GetAccentColor(env runtime.Environment) (*RGB, error) {
if env == nil {
return nil, errors.New("unable to get color without environment")
}
// see https://stackoverflow.com/questions/3560890/vista-7-how-to-get-glass-color
value, err := env.WindowsRegistryKeyValue(`HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM\ColorizationColor`)
if err != nil || value.ValueType != platform.DWORD {
if err != nil || value.ValueType != runtime.DWORD {
return nil, err
}
@ -26,7 +25,7 @@ func GetAccentColor(env platform.Environment) (*RGB, error) {
}, nil
}
func (d *Defaults) SetAccentColor(env platform.Environment, defaultColor Ansi) {
func (d *Defaults) SetAccentColor(env runtime.Environment, defaultColor Ansi) {
rgb, err := GetAccentColor(env)
if err != nil {
d.accent = &Set{

View file

@ -3,7 +3,7 @@ package config
import (
"sync"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
)
@ -53,15 +53,15 @@ type Block struct {
MaxWidth int `json:"max_width,omitempty" toml:"max_width,omitempty"`
MinWidth int `json:"min_width,omitempty" toml:"min_width,omitempty"`
env platform.Environment
env runtime.Environment
}
func (b *Block) Init(env platform.Environment) {
func (b *Block) Init(env runtime.Environment) {
b.env = env
b.executeSegmentLogic()
}
func (b *Block) InitPlain(env platform.Environment, config *Config) {
func (b *Block) InitPlain(env runtime.Environment, config *Config) {
terminal.Init(shell.GENERIC)
terminal.BackgroundColor = shell.ConsoleBackgroundColor(env, config.TerminalBackground)
terminal.Colors = config.MakeColors()

View file

@ -2,7 +2,7 @@ package config
import (
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/template"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
)
@ -51,7 +51,7 @@ type Config struct {
origin string
// eval bool
updated bool
env platform.Environment
env runtime.Environment
}
func (cfg *Config) MakeColors() color.String {

View file

@ -5,7 +5,7 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock"
@ -71,7 +71,7 @@ func TestGetPalette(t *testing.T) {
}
for _, tc := range cases {
env := &mock.MockedEnvironment{}
env.On("TemplateCache").Return(&platform.TemplateCache{
env.On("TemplateCache").Return(&runtime.TemplateCache{
Env: map[string]string{},
Shell: "bash",
})

View file

@ -2,12 +2,12 @@ package config
import (
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/segments"
)
func Default(env platform.Environment, warning bool) *Config {
func Default(env runtime.Environment, warning bool) *Config {
exitBackgroundTemplate := "{{ if gt .Code 0 }}p:red{{ end }}"
exitTemplate := " {{ if gt .Code 0 }}\uf00d{{ else }}\uf00c{{ end }} "
if warning {

View file

@ -3,13 +3,13 @@ package config
import (
"bytes"
"fmt"
"os"
stdOS "os"
"path/filepath"
"strings"
"time"
"github.com/gookit/goutil/jsonutil"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
json "github.com/goccy/go-json"
@ -18,7 +18,7 @@ import (
)
// LoadConfig returns the default configuration including possible user overrides
func Load(env platform.Environment) *Config {
func Load(env runtime.Environment) *Config {
cfg := loadConfig(env)
// only migrate automatically when the switch isn't set
@ -47,7 +47,7 @@ func Load(env platform.Environment) *Config {
return cfg
}
func loadConfig(env platform.Environment) *Config {
func loadConfig(env runtime.Environment) *Config {
defer env.Trace(time.Now())
configFile := env.Flags().Config
@ -61,7 +61,7 @@ func loadConfig(env platform.Environment) *Config {
cfg.Format = strings.TrimPrefix(filepath.Ext(configFile), ".")
cfg.env = env
data, err := os.ReadFile(configFile)
data, err := stdOS.ReadFile(configFile)
if err != nil {
env.DebugF("error reading config file: %s", err)
return Default(env, true)

View file

@ -4,8 +4,8 @@ import (
"fmt"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/segments"
)
@ -33,7 +33,7 @@ func (cfg *Config) Migrate() {
cfg.Version = Version
}
func (segment *Segment) migrate(env platform.Environment, version int) {
func (segment *Segment) migrate(env runtime.Environment, version int) {
if version < 1 {
segment.migrationOne(env)
}
@ -42,7 +42,7 @@ func (segment *Segment) migrate(env platform.Environment, version int) {
}
}
func (segment *Segment) migrationOne(env platform.Environment) {
func (segment *Segment) migrationOne(env runtime.Environment) {
if err := segment.MapSegmentWithWriter(env); err != nil {
return
}
@ -162,7 +162,7 @@ func (segment *Segment) migrationOne(env platform.Environment) {
delete(segment.Properties, colorBackground)
}
func (segment *Segment) migrationTwo(env platform.Environment) {
func (segment *Segment) migrationTwo(env runtime.Environment) {
if err := segment.MapSegmentWithWriter(env); err != nil {
return
}

View file

@ -9,7 +9,7 @@ import (
"strings"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/platform/net"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net"
)
type ConnectionError struct {

View file

@ -4,8 +4,8 @@ import (
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/segments"
"github.com/stretchr/testify/assert"
@ -91,7 +91,7 @@ func (m *MockedWriter) Template() string {
return m.template
}
func (m *MockedWriter) Init(_ properties.Properties, _ platform.Environment) {}
func (m *MockedWriter) Init(_ properties.Properties, _ runtime.Environment) {}
func TestIconOverride(t *testing.T) {
cases := []struct {

View file

@ -1,8 +1,8 @@
package config
import "github.com/jandedobbeleer/oh-my-posh/src/platform"
import "github.com/jandedobbeleer/oh-my-posh/src/runtime"
func shouldHideForWidth(env platform.Environment, minWidth, maxWidth int) bool {
func shouldHideForWidth(env runtime.Environment, minWidth, maxWidth int) bool {
if maxWidth == 0 && minWidth == 0 {
return false
}

View file

@ -7,8 +7,8 @@ import (
"time"
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/template"
c "golang.org/x/text/cases"
@ -18,7 +18,7 @@ import (
// SegmentStyle the style of segment, for more information, see the constants
type SegmentStyle string
func (s *SegmentStyle) resolve(env platform.Environment, context any) SegmentStyle {
func (s *SegmentStyle) resolve(env runtime.Environment, context any) SegmentStyle {
txtTemplate := &template.Text{
Context: context,
Env: env,
@ -58,7 +58,7 @@ type Segment struct {
Text string
env platform.Environment
env runtime.Environment
writer SegmentWriter
styleCache SegmentStyle
name string
@ -82,7 +82,7 @@ func (segment *Segment) Name() string {
return name
}
func (segment *Segment) SetEnabled(env platform.Environment) {
func (segment *Segment) SetEnabled(env runtime.Environment) {
defer func() {
err := recover()
if err == nil {
@ -112,7 +112,7 @@ func (segment *Segment) SetEnabled(env platform.Environment) {
segment.env.DebugF("Segment: %s", segment.Name())
// validate toggles
if toggles, OK := segment.env.Cache().Get(platform.TOGGLECACHE); OK && len(toggles) > 0 {
if toggles, OK := segment.env.Cache().Get(runtime.TOGGLECACHE); OK && len(toggles) > 0 {
list := strings.Split(toggles, ",")
for _, toggle := range list {
if SegmentType(toggle) == segment.Type || toggle == segment.Alias {

View file

@ -6,8 +6,8 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/segments"
"github.com/stretchr/testify/assert"
@ -73,7 +73,7 @@ func TestShouldIncludeFolder(t *testing.T) {
}
for _, tc := range cases {
env := new(mock.MockedEnvironment)
env.On("GOOS").Return(platform.LINUX)
env.On("GOOS").Return(runtime.LINUX)
env.On("Home").Return("")
env.On("Pwd").Return(cwd)
env.On("DirMatchesOneOf", cwd, []string{"Projects/oh-my-posh"}).Return(tc.Included)
@ -145,7 +145,7 @@ func TestGetColors(t *testing.T) {
for _, tc := range cases {
env := new(mock.MockedEnvironment)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil)
env.On("TemplateCache").Return(&platform.TemplateCache{
env.On("TemplateCache").Return(&runtime.TemplateCache{
Env: make(map[string]string),
})

View file

@ -3,8 +3,8 @@ package config
import (
"errors"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/segments"
)
@ -15,7 +15,7 @@ type SegmentType string
type SegmentWriter interface {
Enabled() bool
Template() string
Init(props properties.Properties, env platform.Environment)
Init(props properties.Properties, env runtime.Environment)
}
const (
@ -308,7 +308,7 @@ var Segments = map[SegmentType]func() SegmentWriter{
YTM: func() SegmentWriter { return &segments.Ytm{} },
}
func (segment *Segment) MapSegmentWithWriter(env platform.Environment) error {
func (segment *Segment) MapSegmentWithWriter(env runtime.Environment) error {
segment.env = env
if segment.Properties == nil {

View file

@ -11,7 +11,7 @@ import (
"net/http"
"net/url"
"github.com/jandedobbeleer/oh-my-posh/src/platform/net"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net"
)
func Download(fontPath string) ([]byte, error) {

View file

@ -10,7 +10,7 @@ import (
"strings"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/platform/net"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net"
)
type release struct {

View file

@ -7,11 +7,11 @@ import (
"bytes"
"io"
"path"
"runtime"
stdruntime "runtime"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/platform/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd"
)
func contains[S ~[]E, E comparable](s S, e E) bool {
@ -74,7 +74,7 @@ func InstallZIP(data []byte, user bool) ([]string, error) {
}
// Update the font cache when installing fonts on Linux
if runtime.GOOS == platform.LINUX || runtime.GOOS == platform.DARWIN {
if stdruntime.GOOS == runtime.LINUX || stdruntime.GOOS == runtime.DARWIN {
_, _ = cmd.Run("fc-cache", "-f")
}

View file

@ -6,8 +6,8 @@ import (
"io"
"net/http"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
const (
@ -86,7 +86,7 @@ func (o *OAuthRequest) refreshToken(refreshToken string) (string, error) {
return tokens.AccessToken, nil
}
func OauthResult[a any](o *OAuthRequest, url string, body io.Reader, requestModifiers ...platform.HTTPRequestModifier) (a, error) {
func OauthResult[a any](o *OAuthRequest, url string, body io.Reader, requestModifiers ...runtime.HTTPRequestModifier) (a, error) {
if data, err := getCacheValue[a](&o.Request, url); err == nil {
return data, nil
}
@ -103,7 +103,7 @@ func OauthResult[a any](o *OAuthRequest, url string, body io.Reader, requestModi
}
if requestModifiers == nil {
requestModifiers = []platform.HTTPRequestModifier{}
requestModifiers = []runtime.HTTPRequestModifier{}
}
requestModifiers = append(requestModifiers, addAuthHeader)

View file

@ -5,21 +5,21 @@ import (
"errors"
"io"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Request struct {
props properties.Properties
env platform.Environment
env runtime.Environment
}
func (r *Request) Init(env platform.Environment, props properties.Properties) {
func (r *Request) Init(env runtime.Environment, props properties.Properties) {
r.env = env
r.props = props
}
func Do[a any](r *Request, url string, requestModifiers ...platform.HTTPRequestModifier) (a, error) {
func Do[a any](r *Request, url string, requestModifiers ...runtime.HTTPRequestModifier) (a, error) {
if data, err := getCacheValue[a](r, url); err == nil {
return data, nil
}
@ -45,7 +45,7 @@ func getCacheValue[a any](r *Request, key string) (a, error) {
return data, err
}
func do[a any](r *Request, url string, body io.Reader, requestModifiers ...platform.HTTPRequestModifier) (a, error) {
func do[a any](r *Request, url string, body io.Reader, requestModifiers ...runtime.HTTPRequestModifier) (a, error) {
var data a
httpTimeout := r.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)

View file

@ -28,7 +28,7 @@ import (
"fmt"
"io"
"math"
"os"
stdOS "os"
"path/filepath"
"slices"
"strconv"
@ -36,8 +36,8 @@ import (
"unicode/utf8"
fontCLI "github.com/jandedobbeleer/oh-my-posh/src/font"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
"github.com/esimov/stackblur-go"
@ -115,7 +115,7 @@ type Renderer struct {
RPromptOffset int
BgColor string
env platform.Environment
env runtime.Environment
Path string
@ -147,7 +147,7 @@ type Renderer struct {
ansiSequenceRegexMap map[string]string
}
func (ir *Renderer) Init(env platform.Environment) error {
func (ir *Renderer) Init(env runtime.Environment) error {
ir.env = env
if ir.Path == "" {
@ -210,8 +210,8 @@ func (ir *Renderer) loadFonts() error {
var data []byte
fontCachePath := filepath.Join(ir.env.CachePath(), "Hack.zip")
if _, err := os.Stat(fontCachePath); err == nil {
data, _ = os.ReadFile(fontCachePath)
if _, err := stdOS.Stat(fontCachePath); err == nil {
data, _ = stdOS.ReadFile(fontCachePath)
}
// Download font if not cached
@ -224,7 +224,7 @@ func (ir *Renderer) loadFonts() error {
return err
}
err = os.WriteFile(fontCachePath, data, 0644)
err = stdOS.WriteFile(fontCachePath, data, 0644)
if err != nil {
return err
}

View file

@ -1,11 +1,11 @@
package image
import (
"os"
stdOS "os"
"path/filepath"
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
@ -28,11 +28,14 @@ var cases = []struct {
func runImageTest(config, content string) (string, error) {
poshImagePath := "jandedobbeleer.png"
file, err := os.CreateTemp("", poshImagePath)
file, err := stdOS.CreateTemp("", poshImagePath)
if err != nil {
return "", err
}
defer os.Remove(file.Name())
defer func() {
_ = stdOS.Remove(file.Name())
}()
terminal.Init(shell.GENERIC)
@ -40,8 +43,8 @@ func runImageTest(config, content string) (string, error) {
AnsiString: content,
}
env := &platform.Shell{
CmdFlags: &platform.Flags{
env := &runtime.Terminal{
CmdFlags: &runtime.Flags{
Config: config,
},
}
@ -53,7 +56,7 @@ func runImageTest(config, content string) (string, error) {
err = image.SavePNG()
if err == nil {
os.Remove(image.Path)
_ = stdOS.Remove(image.Path)
}
return filepath.Base(image.Path), err

View file

@ -5,8 +5,8 @@ import (
"io/fs"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/platform/battery"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
mock "github.com/stretchr/testify/mock"
)
@ -120,9 +120,9 @@ func (env *MockedEnvironment) Root() bool {
return args.Bool(0)
}
func (env *MockedEnvironment) Flags() *platform.Flags {
func (env *MockedEnvironment) Flags() *runtime.Flags {
arguments := env.Called()
return arguments.Get(0).(*platform.Flags)
return arguments.Get(0).(*runtime.Flags)
}
func (env *MockedEnvironment) BatteryState() (*battery.Info, error) {
@ -140,19 +140,19 @@ func (env *MockedEnvironment) QueryWindowTitles(processName, windowTitleRegex st
return args.String(0), args.Error(1)
}
func (env *MockedEnvironment) WindowsRegistryKeyValue(path string) (*platform.WindowsRegistryValue, error) {
func (env *MockedEnvironment) WindowsRegistryKeyValue(path string) (*runtime.WindowsRegistryValue, error) {
args := env.Called(path)
return args.Get(0).(*platform.WindowsRegistryValue), args.Error(1)
return args.Get(0).(*runtime.WindowsRegistryValue), args.Error(1)
}
func (env *MockedEnvironment) HTTPRequest(url string, _ io.Reader, _ int, _ ...platform.HTTPRequestModifier) ([]byte, error) {
func (env *MockedEnvironment) HTTPRequest(url string, _ io.Reader, _ int, _ ...runtime.HTTPRequestModifier) ([]byte, error) {
args := env.Called(url)
return args.Get(0).([]byte), args.Error(1)
}
func (env *MockedEnvironment) HasParentFilePath(path string) (*platform.FileInfo, error) {
func (env *MockedEnvironment) HasParentFilePath(path string) (*runtime.FileInfo, error) {
args := env.Called(path)
return args.Get(0).(*platform.FileInfo), args.Error(1)
return args.Get(0).(*runtime.FileInfo), args.Error(1)
}
func (env *MockedEnvironment) StackCount() int {
@ -180,9 +180,9 @@ func (env *MockedEnvironment) CachePath() string {
return args.String(0)
}
func (env *MockedEnvironment) Cache() platform.Cache {
func (env *MockedEnvironment) Cache() runtime.Cache {
args := env.Called()
return args.Get(0).(platform.Cache)
return args.Get(0).(runtime.Cache)
}
func (env *MockedEnvironment) Close() {
@ -209,14 +209,14 @@ func (env *MockedEnvironment) ConvertToLinuxPath(_ string) string {
return args.String(0)
}
func (env *MockedEnvironment) Connection(connectionType platform.ConnectionType) (*platform.Connection, error) {
func (env *MockedEnvironment) Connection(connectionType runtime.ConnectionType) (*runtime.Connection, error) {
args := env.Called(connectionType)
return args.Get(0).(*platform.Connection), args.Error(1)
return args.Get(0).(*runtime.Connection), args.Error(1)
}
func (env *MockedEnvironment) TemplateCache() *platform.TemplateCache {
func (env *MockedEnvironment) TemplateCache() *runtime.TemplateCache {
args := env.Called()
return args.Get(0).(*platform.TemplateCache)
return args.Get(0).(*runtime.TemplateCache)
}
func (env *MockedEnvironment) LoadTemplateCache() {
@ -278,9 +278,9 @@ func (env *MockedEnvironment) CursorPosition() (int, int) {
return args.Int(0), args.Int(1)
}
func (env *MockedEnvironment) SystemInfo() (*platform.SystemInfo, error) {
func (env *MockedEnvironment) SystemInfo() (*runtime.SystemInfo, error) {
args := env.Called()
return args.Get(0).(*platform.SystemInfo), args.Error(1)
return args.Get(0).(*runtime.SystemInfo), args.Error(1)
}
func (env *MockedEnvironment) Unset(name string) {

View file

@ -1,195 +0,0 @@
//go:build !windows
package platform
import (
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/shirou/gopsutil/v3/host"
mem "github.com/shirou/gopsutil/v3/mem"
terminal "github.com/wayneashleyberry/terminal-dimensions"
"golang.org/x/sys/unix"
)
func (env *Shell) Root() bool {
defer env.Trace(time.Now())
return os.Geteuid() == 0
}
func (env *Shell) Home() string {
return os.Getenv("HOME")
}
func (env *Shell) QueryWindowTitles(_, _ string) (string, error) {
return "", &NotImplemented{}
}
func (env *Shell) IsWsl() bool {
defer env.Trace(time.Now())
const key = "is_wsl"
if val, found := env.Cache().Get(key); found {
env.Debug(val)
return val == "true"
}
var val bool
defer func() {
env.Cache().Set(key, strconv.FormatBool(val), -1)
}()
val = env.HasCommand("wslpath")
env.Debug(strconv.FormatBool(val))
return val
}
func (env *Shell) IsWsl2() bool {
defer env.Trace(time.Now())
if !env.IsWsl() {
return false
}
uname := env.FileContent("/proc/sys/kernel/osrelease")
return strings.Contains(uname, "WSL2")
}
func (env *Shell) TerminalWidth() (int, error) {
defer env.Trace(time.Now())
if env.CmdFlags.TerminalWidth > 0 {
env.DebugF("terminal width: %d", env.CmdFlags.TerminalWidth)
return env.CmdFlags.TerminalWidth, nil
}
width, err := terminal.Width()
if err != nil {
env.Error(err)
}
// fetch width from the environment variable
// in case the terminal width is not available
if width == 0 {
i, err := strconv.Atoi(env.Getenv("COLUMNS"))
if err != nil {
env.Error(err)
}
width = uint(i)
}
env.CmdFlags.TerminalWidth = int(width)
env.DebugF("terminal width: %d", env.CmdFlags.TerminalWidth)
return env.CmdFlags.TerminalWidth, err
}
func (env *Shell) Platform() string {
const key = "environment_platform"
if val, found := env.Cache().Get(key); found {
env.Debug(val)
return val
}
var platform string
defer func() {
env.Cache().Set(key, platform, -1)
}()
if wsl := env.Getenv("WSL_DISTRO_NAME"); len(wsl) != 0 {
platform = strings.Split(strings.ToLower(wsl), "-")[0]
env.Debug(platform)
return platform
}
platform, _, _, _ = host.PlatformInformation()
if platform == "arch" {
// validate for Manjaro
lsbInfo := env.FileContent("/etc/lsb-release")
if strings.Contains(strings.ToLower(lsbInfo), "manjaro") {
platform = "manjaro"
}
}
env.Debug(platform)
return platform
}
func (env *Shell) CachePath() string {
defer env.Trace(time.Now())
// allow the user to set the cache path using OMP_CACHE_DIR
if cachePath := returnOrBuildCachePath(env.Getenv("OMP_CACHE_DIR")); len(cachePath) != 0 {
return cachePath
}
// get XDG_CACHE_HOME if present
if cachePath := returnOrBuildCachePath(env.Getenv("XDG_CACHE_HOME")); len(cachePath) != 0 {
return cachePath
}
// HOME cache folder
if cachePath := returnOrBuildCachePath(env.Home() + "/.cache"); len(cachePath) != 0 {
return cachePath
}
return env.Home()
}
func (env *Shell) WindowsRegistryKeyValue(_ string) (*WindowsRegistryValue, error) {
return nil, &NotImplemented{}
}
func (env *Shell) InWSLSharedDrive() bool {
if !env.IsWsl2() {
return false
}
windowsPath := env.ConvertToWindowsPath(env.Pwd())
return !strings.HasPrefix(windowsPath, `//wsl.localhost/`) && !strings.HasPrefix(windowsPath, `//wsl$/`)
}
func (env *Shell) ConvertToWindowsPath(path string) string {
windowsPath, err := env.RunCommand("wslpath", "-m", path)
if err == nil {
return windowsPath
}
return path
}
func (env *Shell) ConvertToLinuxPath(path string) string {
if linuxPath, err := env.RunCommand("wslpath", "-u", path); err == nil {
return linuxPath
}
return path
}
func (env *Shell) LookPath(command string) (string, error) {
return exec.LookPath(command)
}
func (env *Shell) DirIsWritable(path string) bool {
defer env.Trace(time.Now(), path)
return unix.Access(path, unix.W_OK) == nil
}
func (env *Shell) Connection(_ ConnectionType) (*Connection, error) {
// added to disable the linting error, we can implement this later
if len(env.networks) == 0 {
return nil, &NotImplemented{}
}
return nil, &NotImplemented{}
}
func (env *Shell) Memory() (*Memory, error) {
m := &Memory{}
memStat, err := mem.VirtualMemory()
if err != nil {
env.Error(err)
return nil, err
}
m.PhysicalTotalMemory = memStat.Total
m.PhysicalAvailableMemory = memStat.Available
m.PhysicalFreeMemory = memStat.Free
m.PhysicalPercentUsed = memStat.UsedPercent
swapStat, err := mem.SwapMemory()
if err != nil {
env.Error(err)
}
m.SwapTotalMemory = swapStat.Total
m.SwapFreeMemory = swapStat.Free
m.SwapPercentUsed = swapStat.UsedPercent
return m, nil
}

View file

@ -1,19 +0,0 @@
//go:build !darwin
package platform
import (
"time"
"github.com/jandedobbeleer/oh-my-posh/src/platform/battery"
)
func (env *Shell) BatteryState() (*battery.Info, error) {
defer env.Trace(time.Now())
info, err := battery.Get()
if err != nil {
env.Error(err)
return nil, err
}
return info, nil
}

View file

@ -5,8 +5,8 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/template"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
@ -18,7 +18,7 @@ var (
type Engine struct {
Config *config.Config
Env platform.Environment
Env runtime.Environment
Plain bool
console strings.Builder

View file

@ -6,7 +6,7 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
@ -81,7 +81,7 @@ func TestPrintPWD(t *testing.T) {
env.On("User").Return("user")
env.On("Host").Return("host", nil)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil)
env.On("TemplateCache").Return(&platform.TemplateCache{
env.On("TemplateCache").Return(&runtime.TemplateCache{
Env: make(map[string]string),
Shell: "shell",
})
@ -110,7 +110,7 @@ func BenchmarkEngineRender(b *testing.B) {
}
func engineRender() {
env := &platform.Shell{}
env := &runtime.Terminal{}
env.Init()
defer env.Close()
@ -175,7 +175,7 @@ func TestGetTitle(t *testing.T) {
env.On("Home").Return("/usr/home")
env.On("PathSeparator").Return(tc.PathSeparator)
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil)
env.On("TemplateCache").Return(&platform.TemplateCache{
env.On("TemplateCache").Return(&runtime.TemplateCache{
Env: map[string]string{
"USERDOMAIN": "MyCompany",
},
@ -238,7 +238,7 @@ func TestGetConsoleTitleIfGethostnameReturnsError(t *testing.T) {
env.On("Pwd").Return(tc.Cwd)
env.On("Home").Return("/usr/home")
env.On("DebugF", mock2.Anything, mock2.Anything).Return(nil)
env.On("TemplateCache").Return(&platform.TemplateCache{
env.On("TemplateCache").Return(&runtime.TemplateCache{
Env: map[string]string{
"USERDOMAIN": "MyCompany",
},

View file

@ -2,7 +2,7 @@ package prompt
import (
"github.com/jandedobbeleer/oh-my-posh/src/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/shell"
"github.com/jandedobbeleer/oh-my-posh/src/terminal"
)
@ -10,8 +10,8 @@ import (
// New returns a prompt engine initialized with the
// given configuration options, and is ready to print any
// of the prompt components.
func New(flags *platform.Flags) *Engine {
env := &platform.Shell{
func New(flags *runtime.Flags) *Engine {
env := &runtime.Terminal{
CmdFlags: flags,
}
@ -39,7 +39,7 @@ func New(flags *platform.Flags) *Engine {
return eng
}
func patchPowerShellBleed(sh string, flags *platform.Flags) {
func patchPowerShellBleed(sh string, flags *runtime.Flags) {
// when in PowerShell, and force patching the bleed bug
// we need to reduce the terminal width by 1 so the last
// character isn't cut off by the ANSI escape sequences

View file

@ -4,12 +4,12 @@ import (
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Wrapper struct {
Properties Map
Env platform.Environment
Env runtime.Environment
}
func (w *Wrapper) GetColor(property Property, defaultColor color.Ansi) color.Ansi {

View file

@ -5,8 +5,8 @@ import (
"strconv"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd"
)
func mapMostLogicalState(state string) State {

View file

@ -5,7 +5,7 @@ import (
"strconv"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd"
)
func Get() (*Info, error) {

View file

@ -7,7 +7,7 @@ import (
"strconv"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd"
)
// See https://man.openbsd.org/man8/apm.8

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"encoding/json"

View file

@ -11,7 +11,7 @@ import (
"time"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/platform/net"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net"
)
func Download(cachePath, url string) (string, error) {

View file

@ -1,4 +1,4 @@
package platform
package runtime
import "sync"

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"errors"
@ -144,7 +144,7 @@ type DOT11_SSID struct {
ucSSID [DOT11_SSID_MAX_LENGTH]uint8
}
func (env *Shell) getConnections() []*Connection {
func (env *Terminal) getConnections() []*Connection {
var pIFTable2 *MIN_IF_TABLE2
_, _, _ = hGetIfTable2.Call(uintptr(unsafe.Pointer(&pIFTable2)))
@ -199,7 +199,7 @@ func (env *Shell) getConnections() []*Connection {
return networks
}
func (env *Shell) wifiNetwork() (*Connection, error) {
func (env *Terminal) wifiNetwork() (*Connection, error) {
env.Trace(time.Now())
// Open handle
var pdwNegotiatedVersion uint32
@ -234,7 +234,7 @@ func (env *Shell) wifiNetwork() (*Connection, error) {
return nil, errors.New("Not connected")
}
func (env *Shell) parseNetworkInterface(network *WLAN_INTERFACE_INFO, clientHandle uint32) (*Connection, error) {
func (env *Terminal) parseNetworkInterface(network *WLAN_INTERFACE_INFO, clientHandle uint32) (*Connection, error) {
info := Connection{
Type: WIFI,
}

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"context"
@ -18,11 +18,11 @@ import (
"time"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/platform/battery"
"github.com/jandedobbeleer/oh-my-posh/src/platform/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/platform/config"
"github.com/jandedobbeleer/oh-my-posh/src/platform/net"
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/cmd"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/config"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/net"
disk "github.com/shirou/gopsutil/v3/disk"
load "github.com/shirou/gopsutil/v3/load"
@ -194,7 +194,7 @@ type Environment interface {
Trace(start time.Time, args ...string)
}
type Shell struct {
type Terminal struct {
CmdFlags *Flags
Var SimpleMap
@ -210,144 +210,144 @@ type Shell struct {
lsDirMap ConcurrentMap
}
func (env *Shell) Init() {
defer env.Trace(time.Now())
if env.CmdFlags == nil {
env.CmdFlags = &Flags{}
func (term *Terminal) Init() {
defer term.Trace(time.Now())
if term.CmdFlags == nil {
term.CmdFlags = &Flags{}
}
if env.CmdFlags.Debug {
if term.CmdFlags.Debug {
log.Enable()
}
if env.CmdFlags.Plain {
if term.CmdFlags.Plain {
log.Plain()
}
env.fileCache = &fileCache{}
env.fileCache.Init(env.CachePath())
env.resolveConfigPath()
env.cmdCache = &commandCache{
term.fileCache = &fileCache{}
term.fileCache.Init(term.CachePath())
term.resolveConfigPath()
term.cmdCache = &commandCache{
commands: NewConcurrentMap(),
}
env.tmplCache = &TemplateCache{}
term.tmplCache = &TemplateCache{}
env.SetPromptCount()
term.SetPromptCount()
}
func (env *Shell) resolveConfigPath() {
defer env.Trace(time.Now())
func (term *Terminal) resolveConfigPath() {
defer term.Trace(time.Now())
if len(env.CmdFlags.Config) == 0 {
env.CmdFlags.Config = env.Getenv("POSH_THEME")
if len(term.CmdFlags.Config) == 0 {
term.CmdFlags.Config = term.Getenv("POSH_THEME")
}
if len(env.CmdFlags.Config) == 0 {
env.Debug("No config set, fallback to default config")
if len(term.CmdFlags.Config) == 0 {
term.Debug("No config set, fallback to default config")
return
}
if strings.HasPrefix(env.CmdFlags.Config, "https://") {
filePath, err := config.Download(env.CachePath(), env.CmdFlags.Config)
if strings.HasPrefix(term.CmdFlags.Config, "https://") {
filePath, err := config.Download(term.CachePath(), term.CmdFlags.Config)
if err != nil {
env.Error(err)
env.CmdFlags.Config = ""
term.Error(err)
term.CmdFlags.Config = ""
return
}
env.CmdFlags.Config = filePath
term.CmdFlags.Config = filePath
return
}
// Cygwin path always needs the full path as we're on Windows but not really.
// Doing filepath actions will convert it to a Windows path and break the init script.
if env.Platform() == WINDOWS && env.Shell() == "bash" {
env.Debug("Cygwin detected, using full path for config")
if term.Platform() == WINDOWS && term.Shell() == "bash" {
term.Debug("Cygwin detected, using full path for config")
return
}
configFile := env.CmdFlags.Config
configFile := term.CmdFlags.Config
if strings.HasPrefix(configFile, "~") {
configFile = strings.TrimPrefix(configFile, "~")
configFile = filepath.Join(env.Home(), configFile)
configFile = filepath.Join(term.Home(), configFile)
}
if !filepath.IsAbs(configFile) {
configFile = filepath.Join(env.Pwd(), configFile)
configFile = filepath.Join(term.Pwd(), configFile)
}
env.CmdFlags.Config = filepath.Clean(configFile)
term.CmdFlags.Config = filepath.Clean(configFile)
}
func (env *Shell) Trace(start time.Time, args ...string) {
func (term *Terminal) Trace(start time.Time, args ...string) {
log.Trace(start, args...)
}
func (env *Shell) Debug(message string) {
func (term *Terminal) Debug(message string) {
log.Debug(message)
}
func (env *Shell) DebugF(format string, a ...any) {
if !env.CmdFlags.Debug {
func (term *Terminal) DebugF(format string, a ...any) {
if !term.CmdFlags.Debug {
return
}
message := fmt.Sprintf(format, a...)
log.Debug(message)
}
func (env *Shell) Error(err error) {
func (term *Terminal) Error(err error) {
log.Error(err)
}
func (env *Shell) Getenv(key string) string {
defer env.Trace(time.Now(), key)
func (term *Terminal) Getenv(key string) string {
defer term.Trace(time.Now(), key)
val := os.Getenv(key)
env.Debug(val)
term.Debug(val)
return val
}
func (env *Shell) Pwd() string {
env.Lock()
defer env.Trace(time.Now())
defer env.Unlock()
if env.cwd != "" {
return env.cwd
func (term *Terminal) Pwd() string {
term.Lock()
defer term.Trace(time.Now())
defer term.Unlock()
if term.cwd != "" {
return term.cwd
}
correctPath := func(pwd string) string {
if env.GOOS() != WINDOWS {
if term.GOOS() != WINDOWS {
return pwd
}
// on Windows, and being case sensitive and not consistent and all, this gives silly issues
driveLetter := regex.GetCompiledRegex(`^[a-z]:`)
return driveLetter.ReplaceAllStringFunc(pwd, strings.ToUpper)
}
if env.CmdFlags != nil && env.CmdFlags.PWD != "" {
env.cwd = correctPath(env.CmdFlags.PWD)
env.Debug(env.cwd)
return env.cwd
if term.CmdFlags != nil && term.CmdFlags.PWD != "" {
term.cwd = correctPath(term.CmdFlags.PWD)
term.Debug(term.cwd)
return term.cwd
}
dir, err := os.Getwd()
if err != nil {
env.Error(err)
term.Error(err)
return ""
}
env.cwd = correctPath(dir)
env.Debug(env.cwd)
return env.cwd
term.cwd = correctPath(dir)
term.Debug(term.cwd)
return term.cwd
}
func (env *Shell) HasFiles(pattern string) bool {
return env.HasFilesInDir(env.Pwd(), pattern)
func (term *Terminal) HasFiles(pattern string) bool {
return term.HasFilesInDir(term.Pwd(), pattern)
}
func (env *Shell) HasFilesInDir(dir, pattern string) bool {
defer env.Trace(time.Now(), pattern)
func (term *Terminal) HasFilesInDir(dir, pattern string) bool {
defer term.Trace(time.Now(), pattern)
fileSystem := os.DirFS(dir)
var dirEntries []fs.DirEntry
if files, OK := env.lsDirMap.Get(dir); OK {
if files, OK := term.lsDirMap.Get(dir); OK {
dirEntries, _ = files.([]fs.DirEntry)
}
@ -355,18 +355,18 @@ func (env *Shell) HasFilesInDir(dir, pattern string) bool {
var err error
dirEntries, err = fs.ReadDir(fileSystem, ".")
if err != nil {
env.Error(err)
env.Debug("false")
term.Error(err)
term.Debug("false")
return false
}
env.lsDirMap.Set(dir, dirEntries)
term.lsDirMap.Set(dir, dirEntries)
}
pattern = strings.ToLower(pattern)
env.RWMutex.RLock()
defer env.RWMutex.RUnlock()
term.RWMutex.RLock()
defer term.RWMutex.RUnlock()
for _, match := range dirEntries {
if match.IsDir() {
@ -375,236 +375,236 @@ func (env *Shell) HasFilesInDir(dir, pattern string) bool {
matchFileName, err := filepath.Match(pattern, strings.ToLower(match.Name()))
if err != nil {
env.Error(err)
env.Debug("false")
term.Error(err)
term.Debug("false")
return false
}
if matchFileName {
env.Debug("true")
term.Debug("true")
return true
}
}
env.Debug("false")
term.Debug("false")
return false
}
func (env *Shell) HasFileInParentDirs(pattern string, depth uint) bool {
defer env.Trace(time.Now(), pattern, fmt.Sprint(depth))
currentFolder := env.Pwd()
func (term *Terminal) HasFileInParentDirs(pattern string, depth uint) bool {
defer term.Trace(time.Now(), pattern, fmt.Sprint(depth))
currentFolder := term.Pwd()
for c := 0; c < int(depth); c++ {
if env.HasFilesInDir(currentFolder, pattern) {
env.Debug("true")
if term.HasFilesInDir(currentFolder, pattern) {
term.Debug("true")
return true
}
if dir := filepath.Dir(currentFolder); dir != currentFolder {
currentFolder = dir
} else {
env.Debug("false")
term.Debug("false")
return false
}
}
env.Debug("false")
term.Debug("false")
return false
}
func (env *Shell) HasFolder(folder string) bool {
defer env.Trace(time.Now(), folder)
func (term *Terminal) HasFolder(folder string) bool {
defer term.Trace(time.Now(), folder)
f, err := os.Stat(folder)
if err != nil {
env.Debug("false")
term.Debug("false")
return false
}
isDir := f.IsDir()
env.DebugF("%t", isDir)
term.DebugF("%t", isDir)
return isDir
}
func (env *Shell) ResolveSymlink(path string) (string, error) {
defer env.Trace(time.Now(), path)
func (term *Terminal) ResolveSymlink(path string) (string, error) {
defer term.Trace(time.Now(), path)
link, err := filepath.EvalSymlinks(path)
if err != nil {
env.Error(err)
term.Error(err)
return "", err
}
env.Debug(link)
term.Debug(link)
return link, nil
}
func (env *Shell) FileContent(file string) string {
defer env.Trace(time.Now(), file)
func (term *Terminal) FileContent(file string) string {
defer term.Trace(time.Now(), file)
if !filepath.IsAbs(file) {
file = filepath.Join(env.Pwd(), file)
file = filepath.Join(term.Pwd(), file)
}
content, err := os.ReadFile(file)
if err != nil {
env.Error(err)
term.Error(err)
return ""
}
fileContent := string(content)
env.Debug(fileContent)
term.Debug(fileContent)
return fileContent
}
func (env *Shell) LsDir(path string) []fs.DirEntry {
defer env.Trace(time.Now(), path)
func (term *Terminal) LsDir(path string) []fs.DirEntry {
defer term.Trace(time.Now(), path)
entries, err := os.ReadDir(path)
if err != nil {
env.Error(err)
term.Error(err)
return nil
}
env.DebugF("%v", entries)
term.DebugF("%v", entries)
return entries
}
func (env *Shell) PathSeparator() string {
defer env.Trace(time.Now())
func (term *Terminal) PathSeparator() string {
defer term.Trace(time.Now())
return string(os.PathSeparator)
}
func (env *Shell) User() string {
defer env.Trace(time.Now())
func (term *Terminal) User() string {
defer term.Trace(time.Now())
user := os.Getenv("USER")
if user == "" {
user = os.Getenv("USERNAME")
}
env.Debug(user)
term.Debug(user)
return user
}
func (env *Shell) Host() (string, error) {
defer env.Trace(time.Now())
if len(env.host) != 0 {
return env.host, nil
func (term *Terminal) Host() (string, error) {
defer term.Trace(time.Now())
if len(term.host) != 0 {
return term.host, nil
}
hostName, err := os.Hostname()
if err != nil {
env.Error(err)
term.Error(err)
return "", err
}
hostName = cleanHostName(hostName)
env.Debug(hostName)
env.host = hostName
term.Debug(hostName)
term.host = hostName
return hostName, nil
}
func (env *Shell) GOOS() string {
defer env.Trace(time.Now())
func (term *Terminal) GOOS() string {
defer term.Trace(time.Now())
return runtime.GOOS
}
func (env *Shell) RunCommand(command string, args ...string) (string, error) {
defer env.Trace(time.Now(), append([]string{command}, args...)...)
if cacheCommand, ok := env.cmdCache.get(command); ok {
func (term *Terminal) RunCommand(command string, args ...string) (string, error) {
defer term.Trace(time.Now(), append([]string{command}, args...)...)
if cacheCommand, ok := term.cmdCache.get(command); ok {
command = cacheCommand
}
output, err := cmd.Run(command, args...)
if err != nil {
env.Error(err)
term.Error(err)
}
env.Debug(output)
term.Debug(output)
return output, err
}
func (env *Shell) RunShellCommand(shell, command string) string {
defer env.Trace(time.Now())
if out, err := env.RunCommand(shell, "-c", command); err == nil {
func (term *Terminal) RunShellCommand(shell, command string) string {
defer term.Trace(time.Now())
if out, err := term.RunCommand(shell, "-c", command); err == nil {
return out
}
return ""
}
func (env *Shell) CommandPath(command string) string {
defer env.Trace(time.Now(), command)
if path, ok := env.cmdCache.get(command); ok {
env.Debug(path)
func (term *Terminal) CommandPath(command string) string {
defer term.Trace(time.Now(), command)
if path, ok := term.cmdCache.get(command); ok {
term.Debug(path)
return path
}
path, err := env.LookPath(command)
path, err := term.LookPath(command)
if err == nil {
env.cmdCache.set(command, path)
env.Debug(path)
term.cmdCache.set(command, path)
term.Debug(path)
return path
}
env.Error(err)
term.Error(err)
return ""
}
func (env *Shell) HasCommand(command string) bool {
defer env.Trace(time.Now(), command)
if path := env.CommandPath(command); path != "" {
func (term *Terminal) HasCommand(command string) bool {
defer term.Trace(time.Now(), command)
if path := term.CommandPath(command); path != "" {
return true
}
return false
}
func (env *Shell) StatusCodes() (int, string) {
defer env.Trace(time.Now())
func (term *Terminal) StatusCodes() (int, string) {
defer term.Trace(time.Now())
if env.CmdFlags.Shell != CMD || !env.CmdFlags.NoExitCode {
return env.CmdFlags.ErrorCode, env.CmdFlags.PipeStatus
if term.CmdFlags.Shell != CMD || !term.CmdFlags.NoExitCode {
return term.CmdFlags.ErrorCode, term.CmdFlags.PipeStatus
}
errorCode := env.Getenv("=ExitCode")
env.Debug(errorCode)
env.CmdFlags.ErrorCode, _ = strconv.Atoi(errorCode)
errorCode := term.Getenv("=ExitCode")
term.Debug(errorCode)
term.CmdFlags.ErrorCode, _ = strconv.Atoi(errorCode)
return env.CmdFlags.ErrorCode, env.CmdFlags.PipeStatus
return term.CmdFlags.ErrorCode, term.CmdFlags.PipeStatus
}
func (env *Shell) ExecutionTime() float64 {
defer env.Trace(time.Now())
if env.CmdFlags.ExecutionTime < 0 {
func (term *Terminal) ExecutionTime() float64 {
defer term.Trace(time.Now())
if term.CmdFlags.ExecutionTime < 0 {
return 0
}
return env.CmdFlags.ExecutionTime
return term.CmdFlags.ExecutionTime
}
func (env *Shell) Flags() *Flags {
defer env.Trace(time.Now())
return env.CmdFlags
func (term *Terminal) Flags() *Flags {
defer term.Trace(time.Now())
return term.CmdFlags
}
func (env *Shell) Shell() string {
defer env.Trace(time.Now())
if len(env.CmdFlags.Shell) != 0 {
return env.CmdFlags.Shell
func (term *Terminal) Shell() string {
defer term.Trace(time.Now())
if len(term.CmdFlags.Shell) != 0 {
return term.CmdFlags.Shell
}
env.Debug("no shell name provided in flags, trying to detect it")
term.Debug("no shell name provided in flags, trying to detect it")
pid := os.Getppid()
p, _ := process.NewProcess(int32(pid))
name, err := p.Name()
if err != nil {
env.Error(err)
term.Error(err)
return UNKNOWN
}
env.Debug("process name: " + name)
term.Debug("process name: " + name)
// this is used for when scoop creates a shim, see
// https://github.com/jandedobbeleer/oh-my-posh/issues/2806
executable, _ := os.Executable()
if name == executable {
p, _ = p.Parent()
name, err = p.Name()
env.Debug("parent process name: " + name)
term.Debug("parent process name: " + name)
}
if err != nil {
env.Error(err)
term.Error(err)
return UNKNOWN
}
// Cache the shell value to speed things up.
env.CmdFlags.Shell = strings.Trim(strings.TrimSuffix(name, ".exe"), " ")
return env.CmdFlags.Shell
term.CmdFlags.Shell = strings.Trim(strings.TrimSuffix(name, ".exe"), " ")
return term.CmdFlags.Shell
}
func (env *Shell) unWrapError(err error) error {
func (term *Terminal) unWrapError(err error) error {
cause := err
for {
type nested interface{ Unwrap() error }
@ -617,8 +617,8 @@ func (env *Shell) unWrapError(err error) error {
return cause
}
func (env *Shell) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) {
defer env.Trace(time.Now(), targetURL)
func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) {
defer term.Trace(time.Now(), targetURL)
ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cncl()
@ -632,22 +632,22 @@ func (env *Shell) HTTPRequest(targetURL string, body io.Reader, timeout int, req
modifier(request)
}
if env.CmdFlags.Debug {
if term.CmdFlags.Debug {
dump, _ := httputil.DumpRequestOut(request, true)
env.Debug(string(dump))
term.Debug(string(dump))
}
response, err := net.HTTPClient.Do(request)
if err != nil {
env.Error(err)
return nil, env.unWrapError(err)
term.Error(err)
return nil, term.unWrapError(err)
}
// anything inside the range [200, 299] is considered a success
if response.StatusCode < 200 || response.StatusCode >= 300 {
message := "HTTP status code " + strconv.Itoa(response.StatusCode)
err := errors.New(message)
env.Error(err)
term.Error(err)
return nil, err
}
@ -655,18 +655,18 @@ func (env *Shell) HTTPRequest(targetURL string, body io.Reader, timeout int, req
responseBody, err := io.ReadAll(response.Body)
if err != nil {
env.Error(err)
term.Error(err)
return nil, err
}
env.Debug(string(responseBody))
term.Debug(string(responseBody))
return responseBody, nil
}
func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
defer env.Trace(time.Now(), path)
currentFolder := env.Pwd()
func (term *Terminal) HasParentFilePath(path string) (*FileInfo, error) {
defer term.Trace(time.Now(), path)
currentFolder := term.Pwd()
for {
fileSystem := os.DirFS(currentFolder)
info, err := fs.Stat(fileSystem, path)
@ -684,68 +684,68 @@ func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
currentFolder = dir
continue
}
env.Error(err)
term.Error(err)
return nil, errors.New("no match at root level")
}
}
func (env *Shell) StackCount() int {
defer env.Trace(time.Now())
if env.CmdFlags.StackCount < 0 {
func (term *Terminal) StackCount() int {
defer term.Trace(time.Now())
if term.CmdFlags.StackCount < 0 {
return 0
}
return env.CmdFlags.StackCount
return term.CmdFlags.StackCount
}
func (env *Shell) Cache() Cache {
return env.fileCache
func (term *Terminal) Cache() Cache {
return term.fileCache
}
func (env *Shell) saveTemplateCache() {
func (term *Terminal) saveTemplateCache() {
// only store this when in a primary prompt
// and when we have a transient prompt in the config
canSave := env.CmdFlags.Primary && env.CmdFlags.HasTransient
canSave := term.CmdFlags.Primary && term.CmdFlags.HasTransient
if !canSave {
return
}
cache := env.TemplateCache()
cache := term.TemplateCache()
cache.SegmentsCache = cache.Segments.SimpleMap()
templateCache, err := json.Marshal(cache)
if err == nil {
env.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440)
term.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440)
}
}
func (env *Shell) Close() {
defer env.Trace(time.Now())
env.saveTemplateCache()
env.fileCache.Close()
func (term *Terminal) Close() {
defer term.Trace(time.Now())
term.saveTemplateCache()
term.fileCache.Close()
}
func (env *Shell) LoadTemplateCache() {
defer env.Trace(time.Now())
val, OK := env.fileCache.Get(TEMPLATECACHE)
func (term *Terminal) LoadTemplateCache() {
defer term.Trace(time.Now())
val, OK := term.fileCache.Get(TEMPLATECACHE)
if !OK {
return
}
var tmplCache TemplateCache
err := json.Unmarshal([]byte(val), &tmplCache)
if err != nil {
env.Error(err)
term.Error(err)
return
}
tmplCache.Segments = tmplCache.SegmentsCache.ConcurrentMap()
tmplCache.initialized = true
env.tmplCache = &tmplCache
term.tmplCache = &tmplCache
}
func (env *Shell) Logs() string {
func (term *Terminal) Logs() string {
return log.String()
}
func (env *Shell) TemplateCache() *TemplateCache {
defer env.Trace(time.Now())
tmplCache := env.tmplCache
func (term *Terminal) TemplateCache() *TemplateCache {
defer term.Trace(time.Now())
tmplCache := term.tmplCache
tmplCache.Lock()
defer tmplCache.Unlock()
@ -753,23 +753,23 @@ func (env *Shell) TemplateCache() *TemplateCache {
return tmplCache
}
tmplCache.Root = env.Root()
tmplCache.Shell = env.Shell()
tmplCache.ShellVersion = env.CmdFlags.ShellVersion
tmplCache.Code, _ = env.StatusCodes()
tmplCache.WSL = env.IsWsl()
tmplCache.Root = term.Root()
tmplCache.Shell = term.Shell()
tmplCache.ShellVersion = term.CmdFlags.ShellVersion
tmplCache.Code, _ = term.StatusCodes()
tmplCache.WSL = term.IsWsl()
tmplCache.Segments = NewConcurrentMap()
tmplCache.PromptCount = env.CmdFlags.PromptCount
tmplCache.PromptCount = term.CmdFlags.PromptCount
tmplCache.Env = make(map[string]string)
tmplCache.Var = make(map[string]any)
if env.Var != nil {
tmplCache.Var = env.Var
if term.Var != nil {
tmplCache.Var = term.Var
}
const separator = "="
values := os.Environ()
env.DebugF("environment: %v", values)
term.DebugF("environment: %v", values)
for value := range values {
key, val, valid := strings.Cut(values[value], separator)
if !valid {
@ -778,31 +778,31 @@ func (env *Shell) TemplateCache() *TemplateCache {
tmplCache.Env[key] = val
}
pwd := env.Pwd()
tmplCache.PWD = ReplaceHomeDirPrefixWithTilde(env, pwd)
pwd := term.Pwd()
tmplCache.PWD = ReplaceHomeDirPrefixWithTilde(term, pwd)
tmplCache.AbsolutePWD = pwd
if env.IsWsl() {
tmplCache.AbsolutePWD, _ = env.RunCommand("wslpath", "-m", pwd)
if term.IsWsl() {
tmplCache.AbsolutePWD, _ = term.RunCommand("wslpath", "-m", pwd)
}
tmplCache.Folder = Base(env, pwd)
if env.GOOS() == WINDOWS && strings.HasSuffix(tmplCache.Folder, ":") {
tmplCache.Folder = Base(term, pwd)
if term.GOOS() == WINDOWS && strings.HasSuffix(tmplCache.Folder, ":") {
tmplCache.Folder += `\`
}
tmplCache.UserName = env.User()
if host, err := env.Host(); err == nil {
tmplCache.UserName = term.User()
if host, err := term.Host(); err == nil {
tmplCache.HostName = host
}
goos := env.GOOS()
goos := term.GOOS()
tmplCache.OS = goos
if goos == LINUX {
tmplCache.OS = env.Platform()
tmplCache.OS = term.Platform()
}
val := env.Getenv("SHLVL")
val := term.Getenv("SHLVL")
if shlvl, err := strconv.Atoi(val); err == nil {
tmplCache.SHLVL = shlvl
}
@ -811,17 +811,17 @@ func (env *Shell) TemplateCache() *TemplateCache {
return tmplCache
}
func (env *Shell) DirMatchesOneOf(dir string, regexes []string) (match bool) {
func (term *Terminal) DirMatchesOneOf(dir string, regexes []string) (match bool) {
// sometimes the function panics inside golang, we want to silence that error
// and assume that there's no match. Not perfect, but better than crashing
// for the time being until we figure out what the actual root cause is
defer func() {
if err := recover(); err != nil {
env.Error(errors.New("panic"))
term.Error(errors.New("panic"))
match = false
}
}()
match = dirMatchesOneOf(dir, env.Home(), env.GOOS(), regexes)
match = dirMatchesOneOf(dir, term.Home(), term.GOOS(), regexes)
return
}
@ -852,42 +852,42 @@ func dirMatchesOneOf(dir, home, goos string, regexes []string) bool {
return false
}
func (env *Shell) SetPromptCount() {
func (term *Terminal) SetPromptCount() {
countStr := os.Getenv("POSH_PROMPT_COUNT")
if len(countStr) > 0 {
// this counter is incremented by the shell
count, err := strconv.Atoi(countStr)
if err == nil {
env.CmdFlags.PromptCount = count
term.CmdFlags.PromptCount = count
return
}
}
var count int
if val, found := env.Cache().Get(PROMPTCOUNTCACHE); found {
if val, found := term.Cache().Get(PROMPTCOUNTCACHE); found {
count, _ = strconv.Atoi(val)
}
// only write to cache if we're the primary prompt
if env.CmdFlags.Primary {
if term.CmdFlags.Primary {
count++
env.Cache().Set(PROMPTCOUNTCACHE, strconv.Itoa(count), 1440)
term.Cache().Set(PROMPTCOUNTCACHE, strconv.Itoa(count), 1440)
}
env.CmdFlags.PromptCount = count
term.CmdFlags.PromptCount = count
}
func (env *Shell) CursorPosition() (row, col int) {
if number, err := strconv.Atoi(env.Getenv("POSH_CURSOR_LINE")); err == nil {
func (term *Terminal) CursorPosition() (row, col int) {
if number, err := strconv.Atoi(term.Getenv("POSH_CURSOR_LINE")); err == nil {
row = number
}
if number, err := strconv.Atoi(env.Getenv("POSH_CURSOR_COLUMN")); err != nil {
if number, err := strconv.Atoi(term.Getenv("POSH_CURSOR_COLUMN")); err != nil {
col = number
}
return
}
func (env *Shell) SystemInfo() (*SystemInfo, error) {
func (term *Terminal) SystemInfo() (*SystemInfo, error) {
s := &SystemInfo{}
mem, err := env.Memory()
mem, err := term.Memory()
if err != nil {
return nil, err
}

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"errors"
@ -8,7 +8,7 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/platform/battery"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
)
func mapMostLogicalState(state string) battery.State {
@ -30,17 +30,17 @@ func mapMostLogicalState(state string) battery.State {
}
}
func (env *Shell) parseBatteryOutput(output string) (*battery.Info, error) {
func (term *Terminal) parseBatteryOutput(output string) (*battery.Info, error) {
matches := regex.FindNamedRegexMatch(`(?P<PERCENTAGE>[0-9]{1,3})%; (?P<STATE>[a-zA-Z\s]+);`, output)
if len(matches) != 2 {
err := errors.New("Unable to find battery state based on output")
env.Error(err)
term.Error(err)
return nil, err
}
var percentage int
var err error
if percentage, err = strconv.Atoi(matches["PERCENTAGE"]); err != nil {
env.Error(err)
term.Error(err)
return nil, errors.New("Unable to parse battery percentage")
}
return &battery.Info{
@ -49,15 +49,15 @@ func (env *Shell) parseBatteryOutput(output string) (*battery.Info, error) {
}, nil
}
func (env *Shell) BatteryState() (*battery.Info, error) {
defer env.Trace(time.Now())
output, err := env.RunCommand("pmset", "-g", "batt")
func (term *Terminal) BatteryState() (*battery.Info, error) {
defer term.Trace(time.Now())
output, err := term.RunCommand("pmset", "-g", "batt")
if err != nil {
env.Error(err)
term.Error(err)
return nil, err
}
if !strings.Contains(output, "Battery") {
return nil, errors.New("No battery found")
}
return env.parseBatteryOutput(output)
return term.parseBatteryOutput(output)
}

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"testing"

195
src/runtime/os_unix.go Normal file
View file

@ -0,0 +1,195 @@
//go:build !windows
package runtime
import (
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/shirou/gopsutil/v3/host"
mem "github.com/shirou/gopsutil/v3/mem"
terminal "github.com/wayneashleyberry/terminal-dimensions"
"golang.org/x/sys/unix"
)
func (term *Terminal) Root() bool {
defer term.Trace(time.Now())
return os.Geteuid() == 0
}
func (term *Terminal) Home() string {
return os.Getenv("HOME")
}
func (term *Terminal) QueryWindowTitles(_, _ string) (string, error) {
return "", &NotImplemented{}
}
func (term *Terminal) IsWsl() bool {
defer term.Trace(time.Now())
const key = "is_wsl"
if val, found := term.Cache().Get(key); found {
term.Debug(val)
return val == "true"
}
var val bool
defer func() {
term.Cache().Set(key, strconv.FormatBool(val), -1)
}()
val = term.HasCommand("wslpath")
term.Debug(strconv.FormatBool(val))
return val
}
func (term *Terminal) IsWsl2() bool {
defer term.Trace(time.Now())
if !term.IsWsl() {
return false
}
uname := term.FileContent("/proc/sys/kernel/osrelease")
return strings.Contains(uname, "WSL2")
}
func (term *Terminal) TerminalWidth() (int, error) {
defer term.Trace(time.Now())
if term.CmdFlags.TerminalWidth > 0 {
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, nil
}
width, err := terminal.Width()
if err != nil {
term.Error(err)
}
// fetch width from the environment variable
// in case the terminal width is not available
if width == 0 {
i, err := strconv.Atoi(term.Getenv("COLUMNS"))
if err != nil {
term.Error(err)
}
width = uint(i)
}
term.CmdFlags.TerminalWidth = int(width)
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, err
}
func (term *Terminal) Platform() string {
const key = "environment_platform"
if val, found := term.Cache().Get(key); found {
term.Debug(val)
return val
}
var platform string
defer func() {
term.Cache().Set(key, platform, -1)
}()
if wsl := term.Getenv("WSL_DISTRO_NAME"); len(wsl) != 0 {
platform = strings.Split(strings.ToLower(wsl), "-")[0]
term.Debug(platform)
return platform
}
platform, _, _, _ = host.PlatformInformation()
if platform == "arch" {
// validate for Manjaro
lsbInfo := term.FileContent("/etc/lsb-release")
if strings.Contains(strings.ToLower(lsbInfo), "manjaro") {
platform = "manjaro"
}
}
term.Debug(platform)
return platform
}
func (term *Terminal) CachePath() string {
defer term.Trace(time.Now())
// allow the user to set the cache path using OMP_CACHE_DIR
if cachePath := returnOrBuildCachePath(term.Getenv("OMP_CACHE_DIR")); len(cachePath) != 0 {
return cachePath
}
// get XDG_CACHE_HOME if present
if cachePath := returnOrBuildCachePath(term.Getenv("XDG_CACHE_HOME")); len(cachePath) != 0 {
return cachePath
}
// HOME cache folder
if cachePath := returnOrBuildCachePath(term.Home() + "/.cache"); len(cachePath) != 0 {
return cachePath
}
return term.Home()
}
func (term *Terminal) WindowsRegistryKeyValue(_ string) (*WindowsRegistryValue, error) {
return nil, &NotImplemented{}
}
func (term *Terminal) InWSLSharedDrive() bool {
if !term.IsWsl2() {
return false
}
windowsPath := term.ConvertToWindowsPath(term.Pwd())
return !strings.HasPrefix(windowsPath, `//wsl.localhost/`) && !strings.HasPrefix(windowsPath, `//wsl$/`)
}
func (term *Terminal) ConvertToWindowsPath(path string) string {
windowsPath, err := term.RunCommand("wslpath", "-m", path)
if err == nil {
return windowsPath
}
return path
}
func (term *Terminal) ConvertToLinuxPath(path string) string {
if linuxPath, err := term.RunCommand("wslpath", "-u", path); err == nil {
return linuxPath
}
return path
}
func (term *Terminal) LookPath(command string) (string, error) {
return exec.LookPath(command)
}
func (term *Terminal) DirIsWritable(path string) bool {
defer term.Trace(time.Now(), path)
return unix.Access(path, unix.W_OK) == nil
}
func (term *Terminal) Connection(_ ConnectionType) (*Connection, error) {
// added to disable the linting error, we can implement this later
if len(term.networks) == 0 {
return nil, &NotImplemented{}
}
return nil, &NotImplemented{}
}
func (term *Terminal) Memory() (*Memory, error) {
m := &Memory{}
memStat, err := mem.VirtualMemory()
if err != nil {
term.Error(err)
return nil, err
}
m.PhysicalTotalMemory = memStat.Total
m.PhysicalAvailableMemory = memStat.Available
m.PhysicalFreeMemory = memStat.Free
m.PhysicalPercentUsed = memStat.UsedPercent
swapStat, err := mem.SwapMemory()
if err != nil {
term.Error(err)
}
m.SwapTotalMemory = swapStat.Total
m.SwapFreeMemory = swapStat.Free
m.SwapPercentUsed = swapStat.UsedPercent
return m, nil
}

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"errors"
@ -15,8 +15,8 @@ import (
"golang.org/x/sys/windows/registry"
)
func (env *Shell) Root() bool {
defer env.Trace(time.Now())
func (term *Terminal) Root() bool {
defer term.Trace(time.Now())
var sid *windows.SID
// Although this looks scary, it is directly copied from the
@ -31,7 +31,7 @@ func (env *Shell) Root() bool {
0, 0, 0, 0, 0, 0,
&sid)
if err != nil {
env.Error(err)
term.Error(err)
return false
}
defer func() {
@ -45,17 +45,17 @@ func (env *Shell) Root() bool {
member, err := token.IsMember(sid)
if err != nil {
env.Error(err)
term.Error(err)
return false
}
return member
}
func (env *Shell) Home() string {
func (term *Terminal) Home() string {
home := os.Getenv("HOME")
defer func() {
env.Debug(home)
term.Debug(home)
}()
if len(home) > 0 {
return home
@ -68,61 +68,61 @@ func (env *Shell) Home() string {
return home
}
func (env *Shell) QueryWindowTitles(processName, windowTitleRegex string) (string, error) {
defer env.Trace(time.Now(), windowTitleRegex)
func (term *Terminal) QueryWindowTitles(processName, windowTitleRegex string) (string, error) {
defer term.Trace(time.Now(), windowTitleRegex)
title, err := queryWindowTitles(processName, windowTitleRegex)
if err != nil {
env.Error(err)
term.Error(err)
}
return title, err
}
func (env *Shell) IsWsl() bool {
defer env.Trace(time.Now())
func (term *Terminal) IsWsl() bool {
defer term.Trace(time.Now())
return false
}
func (env *Shell) IsWsl2() bool {
defer env.Trace(time.Now())
func (term *Terminal) IsWsl2() bool {
defer term.Trace(time.Now())
return false
}
func (env *Shell) TerminalWidth() (int, error) {
defer env.Trace(time.Now())
func (term *Terminal) TerminalWidth() (int, error) {
defer term.Trace(time.Now())
if env.CmdFlags.TerminalWidth > 0 {
env.DebugF("terminal width: %d", env.CmdFlags.TerminalWidth)
return env.CmdFlags.TerminalWidth, nil
if term.CmdFlags.TerminalWidth > 0 {
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, nil
}
handle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0)
if err != nil {
env.Error(err)
term.Error(err)
return 0, err
}
info, err := winterm.GetConsoleScreenBufferInfo(uintptr(handle))
if err != nil {
env.Error(err)
term.Error(err)
return 0, err
}
env.CmdFlags.TerminalWidth = int(info.Size.X)
env.DebugF("terminal width: %d", env.CmdFlags.TerminalWidth)
return env.CmdFlags.TerminalWidth, nil
term.CmdFlags.TerminalWidth = int(info.Size.X)
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, nil
}
func (env *Shell) Platform() string {
func (term *Terminal) Platform() string {
return WINDOWS
}
func (env *Shell) CachePath() string {
defer env.Trace(time.Now())
func (term *Terminal) CachePath() string {
defer term.Trace(time.Now())
// get LOCALAPPDATA if present
if cachePath := returnOrBuildCachePath(env.Getenv("LOCALAPPDATA")); len(cachePath) != 0 {
if cachePath := returnOrBuildCachePath(term.Getenv("LOCALAPPDATA")); len(cachePath) != 0 {
return cachePath
}
return env.Home()
return term.Home()
}
// Takes a registry path to a key like
@ -134,8 +134,8 @@ func (env *Shell) CachePath() string {
// If the path ends in "\", the "(Default)" key in that path is retrieved.
//
// Returns a variant type if successful; nil and an error if not.
func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error) {
env.Trace(time.Now(), path)
func (term *Terminal) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error) {
term.Trace(time.Now(), path)
// Format:sudo -u postgres psql
// "HKLM\Software\Microsoft\Windows NT\CurrentVersion\EditionID"
@ -152,13 +152,13 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
rootKey, regPath, found := strings.Cut(path, `\`)
if !found {
err := fmt.Errorf("Error, malformed registry path: '%s'", path)
env.Error(err)
term.Error(err)
return nil, err
}
var regKey string
if !strings.HasSuffix(regPath, `\`) {
regKey = Base(env, regPath)
regKey = Base(term, regPath)
if len(regKey) != 0 {
regPath = strings.TrimSuffix(regPath, `\`+regKey)
}
@ -178,18 +178,18 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
key = windows.HKEY_USERS
default:
err := fmt.Errorf("Error, unknown registry key: '%s", rootKey)
env.Error(err)
term.Error(err)
return nil, err
}
k, err := registry.OpenKey(key, regPath, registry.READ)
if err != nil {
env.Error(err)
term.Error(err)
return nil, err
}
_, valType, err := k.GetValue(regKey, nil)
if err != nil {
env.Error(err)
term.Error(err)
return nil, err
}
@ -214,46 +214,46 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
errorLogMsg := fmt.Sprintf("Error, no formatter for type: %d", valType)
return nil, errors.New(errorLogMsg)
}
env.Debug(fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String))
term.Debug(fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String))
return regValue, nil
}
func (env *Shell) InWSLSharedDrive() bool {
func (term *Terminal) InWSLSharedDrive() bool {
return false
}
func (env *Shell) ConvertToWindowsPath(path string) string {
func (term *Terminal) ConvertToWindowsPath(path string) string {
return strings.ReplaceAll(path, `\`, "/")
}
func (env *Shell) ConvertToLinuxPath(path string) string {
func (term *Terminal) ConvertToLinuxPath(path string) string {
return path
}
func (env *Shell) DirIsWritable(path string) bool {
defer env.Trace(time.Now())
return env.isWriteable(path)
func (term *Terminal) DirIsWritable(path string) bool {
defer term.Trace(time.Now())
return term.isWriteable(path)
}
func (env *Shell) Connection(connectionType ConnectionType) (*Connection, error) {
if env.networks == nil {
networks := env.getConnections()
func (term *Terminal) Connection(connectionType ConnectionType) (*Connection, error) {
if term.networks == nil {
networks := term.getConnections()
if len(networks) == 0 {
return nil, errors.New("No connections found")
}
env.networks = networks
term.networks = networks
}
for _, network := range env.networks {
for _, network := range term.networks {
if network.Type == connectionType {
return network, nil
}
}
env.Error(fmt.Errorf("Network type '%s' not found", connectionType))
term.Error(fmt.Errorf("Network type '%s' not found", connectionType))
return nil, &NotImplemented{}
}
func (env *Shell) LookPath(command string) (string, error) {
winAppPath := filepath.Join(env.Getenv("LOCALAPPDATA"), `\Microsoft\WindowsApps\`, command)
func (term *Terminal) LookPath(command string) (string, error) {
winAppPath := filepath.Join(term.Getenv("LOCALAPPDATA"), `\Microsoft\WindowsApps\`, command)
if !strings.HasSuffix(winAppPath, ".exe") {
winAppPath += ".exe"
}

View file

@ -0,0 +1,19 @@
//go:build !darwin
package runtime
import (
"time"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
)
func (term *Terminal) BatteryState() (*battery.Info, error) {
defer term.Trace(time.Now())
info, err := battery.Get()
if err != nil {
term.Error(err)
return nil, err
}
return info, nil
}

View file

@ -1,4 +1,4 @@
package platform
package runtime
import (
"errors"
@ -259,7 +259,7 @@ func (u *tokenUser) isMemberOf(sid *windows.SID) bool {
return false
}
func (env *Shell) isWriteable(folder string) bool {
func (env *Terminal) isWriteable(folder string) bool {
cu, err := getCurrentUser()
if err != nil {
@ -335,7 +335,7 @@ type memoryStatusEx struct {
AvailExtendedVirtual uint64
}
func (env *Shell) Memory() (*Memory, error) {
func (env *Terminal) Memory() (*Memory, error) {
var memStat memoryStatusEx
memStat.Length = uint32(unsafe.Sizeof(memStat))
r0, _, err := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memStat)))

View file

@ -3,8 +3,8 @@ package segments
import (
"path/filepath"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Angular struct {
@ -15,7 +15,7 @@ func (a *Angular) Template() string {
return languageTemplate
}
func (a *Angular) Init(props properties.Properties, env platform.Environment) {
func (a *Angular) Init(props properties.Properties, env runtime.Environment) {
a.language = language{
env: env,
props: props,

View file

@ -6,8 +6,8 @@ import (
"path"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/spf13/pflag"
"gopkg.in/yaml.v3"
)
@ -34,7 +34,7 @@ type ArgocdConfig struct {
type Argocd struct {
props properties.Properties
env platform.Environment
env runtime.Environment
ArgocdContext
}
@ -43,7 +43,7 @@ func (a *Argocd) Template() string {
return NameTemplate
}
func (a *Argocd) Init(props properties.Properties, env platform.Environment) {
func (a *Argocd) Init(props properties.Properties, env runtime.Environment) {
a.props = props
a.env = env
}

View file

@ -4,13 +4,13 @@ import (
"fmt"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Aws struct {
props properties.Properties
env platform.Environment
env runtime.Environment
Profile string
Region string
@ -24,7 +24,7 @@ func (a *Aws) Template() string {
return " {{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }} "
}
func (a *Aws) Init(props properties.Properties, env platform.Environment) {
func (a *Aws) Init(props properties.Properties, env runtime.Environment) {
a.props = props
a.env = env
}

View file

@ -6,13 +6,13 @@ import (
"path/filepath"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Az struct {
props properties.Properties
env platform.Environment
env runtime.Environment
AzureSubscription
Origin string
@ -74,7 +74,7 @@ func (a *Az) Template() string {
return NameTemplate
}
func (a *Az) Init(props properties.Properties, env platform.Environment) {
func (a *Az) Init(props properties.Properties, env runtime.Environment) {
a.props = props
a.env = env
}

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type AzFunc struct {
@ -13,7 +13,7 @@ func (az *AzFunc) Template() string {
return languageTemplate
}
func (az *AzFunc) Init(props properties.Properties, env platform.Environment) {
func (az *AzFunc) Init(props properties.Properties, env runtime.Environment) {
az.language = language{
env: env,
props: props,

View file

@ -6,8 +6,8 @@ import (
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
)
@ -121,7 +121,7 @@ func TestAzSegment(t *testing.T) {
azureRmContext = string(content)
}
env.On("GOOS").Return(platform.LINUX)
env.On("GOOS").Return(runtime.LINUX)
env.On("FileContent", filepath.Join(poshHome, ".azure", "azureProfile.json")).Return(azureProfile)
env.On("Getenv", "POSH_AZURE_SUBSCRIPTION").Return(azureRmContext)
env.On("Getenv", "AZURE_CONFIG_DIR").Return("")

View file

@ -5,13 +5,13 @@ import (
"path/filepath"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Azd struct {
props properties.Properties
env platform.Environment
env runtime.Environment
azdConfig
}
@ -25,7 +25,7 @@ func (t *Azd) Template() string {
return " \uebd8 {{ .DefaultEnvironment }} "
}
func (t *Azd) Init(props properties.Properties, env platform.Environment) {
func (t *Azd) Init(props properties.Properties, env runtime.Environment) {
t.props = props
t.env = env
}

View file

@ -7,8 +7,8 @@ import (
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
mock2 "github.com/stretchr/testify/mock"
)
@ -39,7 +39,7 @@ func TestAzdSegment(t *testing.T) {
env.On("Debug", mock2.Anything)
if tc.IsInited {
fileInfo := &platform.FileInfo{
fileInfo := &runtime.FileInfo{
Path: "test/.azure",
ParentFolder: "test",
IsDir: true,
@ -58,7 +58,7 @@ func TestAzdSegment(t *testing.T) {
env.On("FileContent", filepath.Join("test", ".azure", "config.json")).Return(`{"version": 1, "defaultEnvironment": "TestEnvironment"}`, nil)
} else {
env.On("HasParentFilePath", ".azure").Return(&platform.FileInfo{}, errors.New("no such file or directory"))
env.On("HasParentFilePath", ".azure").Return(&runtime.FileInfo{}, errors.New("no such file or directory"))
}
azd := Azd{

View file

@ -1,14 +1,14 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/platform/battery"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
)
type Battery struct {
props properties.Properties
env platform.Environment
env runtime.Environment
*battery.Info
Error string
@ -84,7 +84,7 @@ func (b *Battery) enabledWhileError(err error) bool {
return true
}
func (b *Battery) Init(props properties.Properties, env platform.Environment) {
func (b *Battery) Init(props properties.Properties, env runtime.Environment) {
b.props = props
b.env = env
}

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Bazel struct {
@ -20,7 +20,7 @@ func (c *Bazel) Template() string {
return " {{ if .Error }}{{ .Icon }} {{ .Error }}{{ else }}{{ url .Icon .URL }} {{ .Full }}{{ end }} "
}
func (c *Bazel) Init(props properties.Properties, env platform.Environment) {
func (c *Bazel) Init(props properties.Properties, env runtime.Environment) {
c.language = language{
env: env,
props: props,

View file

@ -10,14 +10,14 @@ import (
"sort"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
// segment struct, makes templating easier
type Brewfather struct {
props properties.Properties
env platform.Environment
env runtime.Environment
Batch
TemperatureTrendIcon string
@ -320,7 +320,7 @@ func (bf *Brewfather) SGToPlato(sg float64) float64 {
return math.Round(100*((135.997*sg*sg*sg)-(630.272*sg*sg)+(1111.14*sg)-616.868)) / 100 // 2 decimal places
}
func (bf *Brewfather) Init(props properties.Properties, env platform.Environment) {
func (bf *Brewfather) Init(props properties.Properties, env runtime.Environment) {
bf.props = props
bf.env = env
}

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Buf struct {
@ -13,7 +13,7 @@ func (b *Buf) Template() string {
return languageTemplate
}
func (b *Buf) Init(props properties.Properties, env platform.Environment) {
func (b *Buf) Init(props properties.Properties, env runtime.Environment) {
b.language = language{
env: env,
props: props,

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Bun struct {
@ -13,7 +13,7 @@ func (b *Bun) Template() string {
return languageTemplate
}
func (b *Bun) Init(props properties.Properties, env platform.Environment) {
func (b *Bun) Init(props properties.Properties, env runtime.Environment) {
b.language = language{
env: env,
props: props,

View file

@ -4,13 +4,13 @@ import (
"encoding/json"
"fmt"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type CarbonIntensity struct {
props properties.Properties
env platform.Environment
env runtime.Environment
TrendIcon string
@ -149,7 +149,7 @@ func (d *CarbonIntensity) setStatus() error {
return nil
}
func (d *CarbonIntensity) Init(props properties.Properties, env platform.Environment) {
func (d *CarbonIntensity) Init(props properties.Properties, env runtime.Environment) {
d.props = props
d.env = env
}

View file

@ -3,8 +3,8 @@ package segments
import (
"encoding/json"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Cds struct {
@ -16,7 +16,7 @@ func (c *Cds) Template() string {
return languageTemplate
}
func (c *Cds) Init(props properties.Properties, env platform.Environment) {
func (c *Cds) Init(props properties.Properties, env runtime.Environment) {
c.language = language{
env: env,
props: props,

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Cf struct {
@ -13,7 +13,7 @@ func (c *Cf) Template() string {
return languageTemplate
}
func (c *Cf) Init(props properties.Properties, env platform.Environment) {
func (c *Cf) Init(props properties.Properties, env runtime.Environment) {
c.language = language{
env: env,
props: props,

View file

@ -4,13 +4,13 @@ import (
"errors"
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type CfTarget struct {
props properties.Properties
env platform.Environment
env runtime.Environment
CfTargetDetails
}
@ -26,7 +26,7 @@ func (c *CfTarget) Template() string {
return "{{if .Org }}{{ .Org }}{{ end }}{{if .Space }}/{{ .Space }}{{ end }}"
}
func (c *CfTarget) Init(props properties.Properties, env platform.Environment) {
func (c *CfTarget) Init(props properties.Properties, env runtime.Environment) {
c.props = props
c.env = env
}

View file

@ -7,8 +7,8 @@ import (
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
)
@ -19,7 +19,7 @@ func TestCFTargetSegment(t *testing.T) {
Template string
ExpectedString string
DisplayMode string
FileInfo *platform.FileInfo
FileInfo *runtime.FileInfo
TargetOutput string
CommandError error
}{
@ -51,13 +51,13 @@ func TestCFTargetSegment(t *testing.T) {
Case: "files and a manifest file",
ExpectedString: "12345678trial/dev",
DisplayMode: DisplayModeFiles,
FileInfo: &platform.FileInfo{},
FileInfo: &runtime.FileInfo{},
TargetOutput: "API endpoint: https://api.cf.eu10.hana.ondemand.com\nAPI version: 3.109.0\nuser: user@some.com\norg: 12345678trial\nspace: dev",
},
{
Case: "files and a manifest directory",
DisplayMode: DisplayModeFiles,
FileInfo: &platform.FileInfo{
FileInfo: &runtime.FileInfo{
IsDir: true,
},
},

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Cmake struct {
@ -13,7 +13,7 @@ func (c *Cmake) Template() string {
return languageTemplate
}
func (c *Cmake) Init(props properties.Properties, env platform.Environment) {
func (c *Cmake) Init(props properties.Properties, env runtime.Environment) {
c.language = language{
env: env,
props: props,

View file

@ -3,13 +3,13 @@ package segments
import (
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Cmd struct {
props properties.Properties
env platform.Environment
env runtime.Environment
Output string
}
@ -86,7 +86,7 @@ func (c *Cmd) runScript(shell, script string) bool {
return len(c.Output) != 0
}
func (c *Cmd) Init(props properties.Properties, env platform.Environment) {
func (c *Cmd) Init(props properties.Properties, env runtime.Environment) {
c.props = props
c.env = env
}

View file

@ -3,15 +3,15 @@ package segments
import (
"strings"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Connection struct {
props properties.Properties
env platform.Environment
env runtime.Environment
platform.Connection
runtime.Connection
}
const (
@ -26,7 +26,7 @@ func (c *Connection) Enabled() bool {
types := c.props.GetString(Type, "wifi|ethernet")
connectionTypes := strings.Split(types, "|")
for _, connectionType := range connectionTypes {
network, err := c.env.Connection(platform.ConnectionType(connectionType))
network, err := c.env.Connection(runtime.ConnectionType(connectionType))
if err != nil {
continue
}
@ -36,7 +36,7 @@ func (c *Connection) Enabled() bool {
return false
}
func (c *Connection) Init(props properties.Properties, env platform.Environment) {
func (c *Connection) Init(props properties.Properties, env runtime.Environment) {
c.props = props
c.env = env
}

View file

@ -5,15 +5,15 @@ import (
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/mock"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
)
func TestConnection(t *testing.T) {
type connectionResponse struct {
Connection *platform.Connection
Connection *runtime.Connection
Error error
}
cases := []struct {
@ -30,7 +30,7 @@ func TestConnection(t *testing.T) {
ConnectionType: "wifi",
Connections: []*connectionResponse{
{
Connection: &platform.Connection{
Connection: &runtime.Connection{
Name: "WiFi",
Type: "wifi",
},
@ -42,8 +42,8 @@ func TestConnection(t *testing.T) {
ConnectionType: "wifi",
Connections: []*connectionResponse{
{
Connection: &platform.Connection{
Type: platform.WIFI,
Connection: &runtime.Connection{
Type: runtime.WIFI,
},
Error: fmt.Errorf("no connection"),
},
@ -56,14 +56,14 @@ func TestConnection(t *testing.T) {
ExpectedEnabled: true,
Connections: []*connectionResponse{
{
Connection: &platform.Connection{
Type: platform.WIFI,
Connection: &runtime.Connection{
Type: runtime.WIFI,
},
Error: fmt.Errorf("no connection"),
},
{
Connection: &platform.Connection{
Type: platform.ETHERNET,
Connection: &runtime.Connection{
Type: runtime.ETHERNET,
},
},
},
@ -73,14 +73,14 @@ func TestConnection(t *testing.T) {
ConnectionType: "wifi|ethernet",
Connections: []*connectionResponse{
{
Connection: &platform.Connection{
Type: platform.WIFI,
Connection: &runtime.Connection{
Type: runtime.WIFI,
},
Error: fmt.Errorf("no connection"),
},
{
Connection: &platform.Connection{
Type: platform.ETHERNET,
Connection: &runtime.Connection{
Type: runtime.ETHERNET,
},
Error: fmt.Errorf("no connection"),
},

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Crystal struct {
@ -13,7 +13,7 @@ func (c *Crystal) Template() string {
return languageTemplate
}
func (c *Crystal) Init(props properties.Properties, env platform.Environment) {
func (c *Crystal) Init(props properties.Properties, env runtime.Environment) {
c.language = language{
env: env,
props: props,

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
var (
@ -18,7 +18,7 @@ func (d *Dart) Template() string {
return languageTemplate
}
func (d *Dart) Init(props properties.Properties, env platform.Environment) {
func (d *Dart) Init(props properties.Properties, env runtime.Environment) {
d.language = language{
env: env,
props: props,

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Deno struct {
@ -13,7 +13,7 @@ func (d *Deno) Template() string {
return languageTemplate
}
func (d *Deno) Init(props properties.Properties, env platform.Environment) {
func (d *Deno) Init(props properties.Properties, env runtime.Environment) {
d.language = language{
env: env,
props: props,

View file

@ -4,8 +4,8 @@ import (
"encoding/json"
"path/filepath"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type DockerConfig struct {
@ -14,7 +14,7 @@ type DockerConfig struct {
type Docker struct {
props properties.Properties
env platform.Environment
env runtime.Environment
Context string
}
@ -23,7 +23,7 @@ func (d *Docker) Template() string {
return " \uf308 {{ .Context }} "
}
func (d *Docker) Init(props properties.Properties, env platform.Environment) {
func (d *Docker) Init(props properties.Properties, env runtime.Environment) {
d.props = props
d.env = env
}

View file

@ -2,8 +2,8 @@ package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/constants"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Dotnet struct {
@ -16,7 +16,7 @@ func (d *Dotnet) Template() string {
return " {{ if .Unsupported }}\uf071{{ else }}{{ .Full }}{{ end }} "
}
func (d *Dotnet) Init(props properties.Properties, env platform.Environment) {
func (d *Dotnet) Init(props properties.Properties, env runtime.Environment) {
d.language = language{
env: env,
props: props,

View file

@ -4,7 +4,7 @@ import (
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/constants"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
)
@ -31,7 +31,7 @@ func TestDotnetSegment(t *testing.T) {
if tc.ExitCode != 0 {
env.Unset("RunCommand")
err := &platform.CommandError{ExitCode: tc.ExitCode}
err := &runtime.CommandError{ExitCode: tc.ExitCode}
env.On("RunCommand", "dotnet", []string{"--version"}).Return("", err)
}

View file

@ -1,8 +1,8 @@
package segments
import (
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
)
type Elixir struct {
@ -13,7 +13,7 @@ func (e *Elixir) Template() string {
return languageTemplate
}
func (e *Elixir) Init(props properties.Properties, env platform.Environment) {
func (e *Elixir) Init(props properties.Properties, env runtime.Environment) {
e.language = language{
env: env,
props: props,

View file

@ -4,7 +4,7 @@ import (
"fmt"
"testing"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/stretchr/testify/assert"
)
@ -50,7 +50,7 @@ func TestElixir(t *testing.T) {
env.On("HasCommand", "asdf").Return(tc.HasAsdf)
var asdfErr error
if tc.AsdfExitCode != 0 {
asdfErr = &platform.CommandError{ExitCode: tc.AsdfExitCode}
asdfErr = &runtime.CommandError{ExitCode: tc.AsdfExitCode}
}
env.On("RunCommand", "asdf", []string{"current", "elixir"}).Return(tc.AsdfVersionOutput, asdfErr)

View file

@ -4,8 +4,8 @@ import (
"fmt"
"strconv"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime"
lang "golang.org/x/text/language"
"golang.org/x/text/message"
@ -13,7 +13,7 @@ import (
type Executiontime struct {
props properties.Properties
env platform.Environment
env runtime.Environment
FormattedMs string
Ms int64
@ -70,7 +70,7 @@ func (t *Executiontime) Template() string {
return " {{ .FormattedMs }} "
}
func (t *Executiontime) Init(props properties.Properties, env platform.Environment) {
func (t *Executiontime) Init(props properties.Properties, env runtime.Environment) {
t.props = props
t.env = env
}

Some files were not shown because too many files have changed in this diff Show more