refactor(environment): remove logging via interface

This commit is contained in:
Jan De Dobbeleer 2024-11-13 17:12:32 +01:00 committed by Jan De Dobbeleer
parent 077135e6cc
commit 9349de4998
49 changed files with 224 additions and 258 deletions

View file

@ -8,6 +8,7 @@ import (
"github.com/gookit/color" "github.com/gookit/color"
"github.com/jandedobbeleer/oh-my-posh/src/cache" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/template" "github.com/jandedobbeleer/oh-my-posh/src/template"
) )
@ -164,7 +165,7 @@ func MakeColors(palette Palette, cacheEnabled bool, accentColor Ansi, env runtim
} }
func (d *Defaults) SetAccentColor(env runtime.Environment, defaultColor Ansi) { func (d *Defaults) SetAccentColor(env runtime.Environment, defaultColor Ansi) {
defer env.Trace(time.Now()) defer log.Trace(time.Now())
// get accent color from session cache first // get accent color from session cache first
if accent, OK := env.Session().Get("accent_color"); OK { if accent, OK := env.Session().Get("accent_color"); OK {

View file

@ -4,19 +4,20 @@ import (
"errors" "errors"
"strconv" "strconv"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
) )
func GetAccentColor(env runtime.Environment) (*RGB, error) { func GetAccentColor(env runtime.Environment) (*RGB, error) {
output, err := env.RunCommand("defaults", "read", "-g", "AppleAccentColor") output, err := env.RunCommand("defaults", "read", "-g", "AppleAccentColor")
if err != nil { if err != nil {
env.Error(err) log.Error(err)
return nil, errors.New("unable to read accent color") return nil, errors.New("unable to read accent color")
} }
index, err := strconv.Atoi(output) index, err := strconv.Atoi(output)
if err != nil { if err != nil {
env.Error(err) log.Error(err)
return nil, errors.New("unable to parse accent color index") return nil, errors.New("unable to parse accent color index")
} }

View file

@ -10,8 +10,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/template" "github.com/jandedobbeleer/oh-my-posh/src/template"
testify_ "github.com/stretchr/testify/mock"
) )
func TestGetAnsiFromColorString(t *testing.T) { func TestGetAnsiFromColorString(t *testing.T) {
@ -45,8 +43,6 @@ func TestGetAnsiFromColorString(t *testing.T) {
func TestMakeColors(t *testing.T) { func TestMakeColors(t *testing.T) {
env := &mock.Environment{} env := &mock.Environment{}
env.On("Trace", testify_.Anything, testify_.Anything).Return(nil)
c := &cache_.Cache{} c := &cache_.Cache{}
c.On("Get", "accent_color").Return("", true) c.On("Get", "accent_color").Return("", true)
env.On("Session").Return(c) env.On("Session").Return(c)

View file

@ -4,11 +4,12 @@ import (
"errors" "errors"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
) )
func GetAccentColor(env runtime.Environment) (*RGB, error) { func GetAccentColor(env runtime.Environment) (*RGB, error) {
defer env.Trace(time.Now()) defer log.Trace(time.Now())
if env == nil { if env == nil {
return nil, errors.New("unable to get color without environment") return nil, errors.New("unable to get color without environment")

View file

@ -9,6 +9,7 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/cache" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/color" "github.com/jandedobbeleer/oh-my-posh/src/color"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
@ -105,7 +106,7 @@ func (segment *Segment) Execute(env runtime.Environment) {
return return
} }
segment.env.DebugF("segment: %s", segment.Name()) log.Debugf("segment: %s", segment.Name())
if segment.isToggled() { if segment.isToggled() {
return return
@ -207,7 +208,7 @@ func (segment *Segment) isToggled() bool {
list := strings.Split(toggles, ",") list := strings.Split(toggles, ",")
for _, toggle := range list { for _, toggle := range list {
if SegmentType(toggle) == segment.Type || toggle == segment.Alias { if SegmentType(toggle) == segment.Type || toggle == segment.Alias {
segment.env.DebugF("segment toggled off: %s", segment.Name()) log.Debugf("segment toggled off: %s", segment.Name())
return true return true
} }
} }
@ -227,7 +228,7 @@ func (segment *Segment) restoreCache() bool {
err := json.Unmarshal([]byte(data), &segment.writer) err := json.Unmarshal([]byte(data), &segment.writer)
if err != nil { if err != nil {
segment.env.Error(err) log.Error(err)
} }
segment.Enabled = true segment.Enabled = true
@ -243,7 +244,7 @@ func (segment *Segment) setCache() {
data, err := json.Marshal(segment.writer) data, err := json.Marshal(segment.writer)
if err != nil { if err != nil {
segment.env.Error(err) log.Error(err)
return return
} }

View file

@ -45,6 +45,15 @@ func Debug(message ...string) {
printLn(debug, header, strings.Join(message, " ")) printLn(debug, header, strings.Join(message, " "))
} }
func Debugf(format string, args ...interface{}) {
if !enabled {
return
}
message := fmt.Sprintf(format, args...)
Debug(message)
}
func Error(err error) { func Error(err error) {
if !enabled { if !enabled {
return return

View file

@ -21,7 +21,7 @@ func (e *Engine) PrintDebug(startTime time.Time, version string) string {
// console title timing // console title timing
titleStartTime := time.Now() titleStartTime := time.Now()
e.Env.Debug("segment: Title") log.Debug("segment: Title")
consoleTitle := &config.Segment{ consoleTitle := &config.Segment{
Alias: "ConsoleTitle", Alias: "ConsoleTitle",
NameLength: 12, NameLength: 12,

View file

@ -3,7 +3,6 @@ package runtime
import ( import (
"io" "io"
"io/fs" "io/fs"
"time"
"github.com/jandedobbeleer/oh-my-posh/src/cache" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/battery" "github.com/jandedobbeleer/oh-my-posh/src/runtime/battery"
@ -68,10 +67,6 @@ type Environment interface {
Connection(connectionType ConnectionType) (*Connection, error) Connection(connectionType ConnectionType) (*Connection, error)
CursorPosition() (row, col int) CursorPosition() (row, col int)
SystemInfo() (*SystemInfo, error) SystemInfo() (*SystemInfo, error)
Debug(message string)
DebugF(format string, a ...any)
Error(err error)
Trace(start time.Time, args ...string)
} }
type Flags struct { type Flags struct {

View file

@ -135,7 +135,6 @@ func TestOauthResult(t *testing.T) {
env.On("Cache").Return(cache) env.On("Cache").Return(cache)
env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), tc.Error)
env.On("HTTPRequest", tokenURL).Return([]byte(tc.TokenResponse), tc.Error) env.On("HTTPRequest", tokenURL).Return([]byte(tc.TokenResponse), tc.Error)
env.On("Error", testify_.Anything)
oauth := &OAuthRequest{ oauth := &OAuthRequest{
AccessTokenKey: accessTokenKey, AccessTokenKey: accessTokenKey,

View file

@ -7,6 +7,7 @@ import (
"time" "time"
"unsafe" "unsafe"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
) )
@ -180,7 +181,7 @@ func (term *Terminal) getConnections() []*Connection {
continue continue
} }
term.DebugF("Found network interface: %s", alias) log.Debugf("Found network interface: %s", alias)
network := &Connection{ network := &Connection{
Type: connectionType, Type: connectionType,
@ -201,7 +202,7 @@ func (term *Terminal) getConnections() []*Connection {
} }
func (term *Terminal) wifiNetwork() (*Connection, error) { func (term *Terminal) wifiNetwork() (*Connection, error) {
term.Trace(time.Now()) log.Trace(time.Now())
// Open handle // Open handle
var pdwNegotiatedVersion uint32 var pdwNegotiatedVersion uint32
var phClientHandle uint32 var phClientHandle uint32
@ -252,7 +253,7 @@ func (term *Terminal) parseNetworkInterface(network *WLAN_INTERFACE_INFO, client
uintptr(unsafe.Pointer(&wlanAttr)), uintptr(unsafe.Pointer(&wlanAttr)),
uintptr(unsafe.Pointer(nil))) uintptr(unsafe.Pointer(nil)))
if e != 0 { if e != 0 {
term.Error(err) log.Error(err)
return &info, err return &info, err
} }
@ -261,7 +262,7 @@ func (term *Terminal) parseNetworkInterface(network *WLAN_INTERFACE_INFO, client
if ssid.uSSIDLength > 0 { if ssid.uSSIDLength > 0 {
info.SSID = string(ssid.ucSSID[0:ssid.uSSIDLength]) info.SSID = string(ssid.ucSSID[0:ssid.uSSIDLength])
info.Name = info.SSID info.Name = info.SSID
term.DebugF("Found wifi interface: %s", info.SSID) log.Debugf("Found wifi interface: %s", info.SSID)
} }
info.TransmitRate = uint64(wlanAttr.wlanAssociationAttributes.ulTxRate / 1024) info.TransmitRate = uint64(wlanAttr.wlanAssociationAttributes.ulTxRate / 1024)

View file

@ -41,7 +41,7 @@ type Terminal struct {
} }
func (term *Terminal) Init(flags *Flags) { func (term *Terminal) Init(flags *Flags) {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
term.CmdFlags = flags term.CmdFlags = flags
@ -76,30 +76,10 @@ func (term *Terminal) Init(flags *Flags) {
} }
} }
func (term *Terminal) Trace(start time.Time, args ...string) {
log.Trace(start, args...)
}
func (term *Terminal) Debug(message string) {
log.Debug(message)
}
func (term *Terminal) DebugF(format string, a ...any) {
if !term.CmdFlags.Debug {
return
}
message := fmt.Sprintf(format, a...)
log.Debug(message)
}
func (term *Terminal) Error(err error) {
log.Error(err)
}
func (term *Terminal) Getenv(key string) string { func (term *Terminal) Getenv(key string) string {
defer term.Trace(time.Now(), key) defer log.Trace(time.Now(), key)
val := os.Getenv(key) val := os.Getenv(key)
term.Debug(val) log.Debug(val)
return val return val
} }
@ -108,7 +88,7 @@ func (term *Terminal) Pwd() string {
} }
func (term *Terminal) setPwd() { func (term *Terminal) setPwd() {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
correctPath := func(pwd string) string { correctPath := func(pwd string) string {
if term.GOOS() != WINDOWS { if term.GOOS() != WINDOWS {
@ -121,18 +101,18 @@ func (term *Terminal) setPwd() {
if term.CmdFlags != nil && term.CmdFlags.PWD != "" { if term.CmdFlags != nil && term.CmdFlags.PWD != "" {
term.cwd = path.Clean(term.CmdFlags.PWD) term.cwd = path.Clean(term.CmdFlags.PWD)
term.Debug(term.cwd) log.Debug(term.cwd)
return return
} }
dir, err := os.Getwd() dir, err := os.Getwd()
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return return
} }
term.cwd = correctPath(dir) term.cwd = correctPath(dir)
term.Debug(term.cwd) log.Debug(term.cwd)
} }
func (term *Terminal) HasFiles(pattern string) bool { func (term *Terminal) HasFiles(pattern string) bool {
@ -140,7 +120,7 @@ func (term *Terminal) HasFiles(pattern string) bool {
} }
func (term *Terminal) HasFilesInDir(dir, pattern string) bool { func (term *Terminal) HasFilesInDir(dir, pattern string) bool {
defer term.Trace(time.Now(), pattern) defer log.Trace(time.Now(), pattern)
fileSystem := os.DirFS(dir) fileSystem := os.DirFS(dir)
var dirEntries []fs.DirEntry var dirEntries []fs.DirEntry
@ -153,8 +133,8 @@ func (term *Terminal) HasFilesInDir(dir, pattern string) bool {
var err error var err error
dirEntries, err = fs.ReadDir(fileSystem, ".") dirEntries, err = fs.ReadDir(fileSystem, ".")
if err != nil { if err != nil {
term.Error(err) log.Error(err)
term.Debug("false") log.Debug("false")
return false return false
} }
@ -170,127 +150,127 @@ func (term *Terminal) HasFilesInDir(dir, pattern string) bool {
matchFileName, err := filepath.Match(pattern, strings.ToLower(match.Name())) matchFileName, err := filepath.Match(pattern, strings.ToLower(match.Name()))
if err != nil { if err != nil {
term.Error(err) log.Error(err)
term.Debug("false") log.Debug("false")
return false return false
} }
if matchFileName { if matchFileName {
term.Debug("true") log.Debug("true")
return true return true
} }
} }
term.Debug("false") log.Debug("false")
return false return false
} }
func (term *Terminal) HasFileInParentDirs(pattern string, depth uint) bool { func (term *Terminal) HasFileInParentDirs(pattern string, depth uint) bool {
defer term.Trace(time.Now(), pattern, fmt.Sprint(depth)) defer log.Trace(time.Now(), pattern, fmt.Sprint(depth))
currentFolder := term.Pwd() currentFolder := term.Pwd()
for c := 0; c < int(depth); c++ { for c := 0; c < int(depth); c++ {
if term.HasFilesInDir(currentFolder, pattern) { if term.HasFilesInDir(currentFolder, pattern) {
term.Debug("true") log.Debug("true")
return true return true
} }
if dir := filepath.Dir(currentFolder); dir != currentFolder { if dir := filepath.Dir(currentFolder); dir != currentFolder {
currentFolder = dir currentFolder = dir
} else { } else {
term.Debug("false") log.Debug("false")
return false return false
} }
} }
term.Debug("false") log.Debug("false")
return false return false
} }
func (term *Terminal) HasFolder(folder string) bool { func (term *Terminal) HasFolder(folder string) bool {
defer term.Trace(time.Now(), folder) defer log.Trace(time.Now(), folder)
f, err := os.Stat(folder) f, err := os.Stat(folder)
if err != nil { if err != nil {
term.Debug("false") log.Debug("false")
return false return false
} }
isDir := f.IsDir() isDir := f.IsDir()
term.DebugF("%t", isDir) log.Debugf("%t", isDir)
return isDir return isDir
} }
func (term *Terminal) ResolveSymlink(input string) (string, error) { func (term *Terminal) ResolveSymlink(input string) (string, error) {
defer term.Trace(time.Now(), input) defer log.Trace(time.Now(), input)
link, err := filepath.EvalSymlinks(input) link, err := filepath.EvalSymlinks(input)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return "", err return "", err
} }
term.Debug(link) log.Debug(link)
return link, nil return link, nil
} }
func (term *Terminal) FileContent(file string) string { func (term *Terminal) FileContent(file string) string {
defer term.Trace(time.Now(), file) defer log.Trace(time.Now(), file)
if !filepath.IsAbs(file) { if !filepath.IsAbs(file) {
file = filepath.Join(term.Pwd(), file) file = filepath.Join(term.Pwd(), file)
} }
content, err := os.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return "" return ""
} }
fileContent := string(content) fileContent := string(content)
term.Debug(fileContent) log.Debug(fileContent)
return fileContent return fileContent
} }
func (term *Terminal) LsDir(input string) []fs.DirEntry { func (term *Terminal) LsDir(input string) []fs.DirEntry {
defer term.Trace(time.Now(), input) defer log.Trace(time.Now(), input)
entries, err := os.ReadDir(input) entries, err := os.ReadDir(input)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil return nil
} }
term.DebugF("%v", entries) log.Debugf("%v", entries)
return entries return entries
} }
func (term *Terminal) User() string { func (term *Terminal) User() string {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
user := os.Getenv("USER") user := os.Getenv("USER")
if user == "" { if user == "" {
user = os.Getenv("USERNAME") user = os.Getenv("USERNAME")
} }
term.Debug(user) log.Debug(user)
return user return user
} }
func (term *Terminal) Host() (string, error) { func (term *Terminal) Host() (string, error) {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if len(term.host) != 0 { if len(term.host) != 0 {
return term.host, nil return term.host, nil
} }
hostName, err := os.Hostname() hostName, err := os.Hostname()
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return "", err return "", err
} }
hostName = cleanHostName(hostName) hostName = cleanHostName(hostName)
term.Debug(hostName) log.Debug(hostName)
term.host = hostName term.host = hostName
return hostName, nil return hostName, nil
} }
func (term *Terminal) GOOS() string { func (term *Terminal) GOOS() string {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return runtime.GOOS return runtime.GOOS
} }
@ -299,7 +279,7 @@ func (term *Terminal) Home() string {
} }
func (term *Terminal) RunCommand(command string, args ...string) (string, error) { func (term *Terminal) RunCommand(command string, args ...string) (string, error) {
defer term.Trace(time.Now(), append([]string{command}, args...)...) defer log.Trace(time.Now(), append([]string{command}, args...)...)
if cacheCommand, ok := term.cmdCache.Get(command); ok { if cacheCommand, ok := term.cmdCache.Get(command); ok {
command = cacheCommand command = cacheCommand
@ -307,15 +287,15 @@ func (term *Terminal) RunCommand(command string, args ...string) (string, error)
output, err := cmd.Run(command, args...) output, err := cmd.Run(command, args...)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
} }
term.Debug(output) log.Debug(output)
return output, err return output, err
} }
func (term *Terminal) RunShellCommand(shell, command string) string { func (term *Terminal) RunShellCommand(shell, command string) string {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if out, err := term.RunCommand(shell, "-c", command); err == nil { if out, err := term.RunCommand(shell, "-c", command); err == nil {
return out return out
@ -325,25 +305,25 @@ func (term *Terminal) RunShellCommand(shell, command string) string {
} }
func (term *Terminal) CommandPath(command string) string { func (term *Terminal) CommandPath(command string) string {
defer term.Trace(time.Now(), command) defer log.Trace(time.Now(), command)
if cmdPath, ok := term.cmdCache.Get(command); ok { if cmdPath, ok := term.cmdCache.Get(command); ok {
term.Debug(cmdPath) log.Debug(cmdPath)
return cmdPath return cmdPath
} }
cmdPath, err := exec.LookPath(command) cmdPath, err := exec.LookPath(command)
if err == nil { if err == nil {
term.cmdCache.Set(command, cmdPath) term.cmdCache.Set(command, cmdPath)
term.Debug(cmdPath) log.Debug(cmdPath)
return cmdPath return cmdPath
} }
term.Error(err) log.Error(err)
return "" return ""
} }
func (term *Terminal) HasCommand(command string) bool { func (term *Terminal) HasCommand(command string) bool {
defer term.Trace(time.Now(), command) defer log.Trace(time.Now(), command)
if cmdPath := term.CommandPath(command); cmdPath != "" { if cmdPath := term.CommandPath(command); cmdPath != "" {
return true return true
@ -353,21 +333,21 @@ func (term *Terminal) HasCommand(command string) bool {
} }
func (term *Terminal) StatusCodes() (int, string) { func (term *Terminal) StatusCodes() (int, string) {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if term.CmdFlags.Shell != CMD || !term.CmdFlags.NoExitCode { if term.CmdFlags.Shell != CMD || !term.CmdFlags.NoExitCode {
return term.CmdFlags.ErrorCode, term.CmdFlags.PipeStatus return term.CmdFlags.ErrorCode, term.CmdFlags.PipeStatus
} }
errorCode := term.Getenv("=ExitCode") errorCode := term.Getenv("=ExitCode")
term.Debug(errorCode) log.Debug(errorCode)
term.CmdFlags.ErrorCode, _ = strconv.Atoi(errorCode) term.CmdFlags.ErrorCode, _ = strconv.Atoi(errorCode)
return term.CmdFlags.ErrorCode, term.CmdFlags.PipeStatus return term.CmdFlags.ErrorCode, term.CmdFlags.PipeStatus
} }
func (term *Terminal) ExecutionTime() float64 { func (term *Terminal) ExecutionTime() float64 {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if term.CmdFlags.ExecutionTime < 0 { if term.CmdFlags.ExecutionTime < 0 {
return 0 return 0
} }
@ -375,34 +355,34 @@ func (term *Terminal) ExecutionTime() float64 {
} }
func (term *Terminal) Flags() *Flags { func (term *Terminal) Flags() *Flags {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return term.CmdFlags return term.CmdFlags
} }
func (term *Terminal) Shell() string { func (term *Terminal) Shell() string {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if len(term.CmdFlags.Shell) != 0 { if len(term.CmdFlags.Shell) != 0 {
return term.CmdFlags.Shell return term.CmdFlags.Shell
} }
term.Debug("no shell name provided in flags, trying to detect it") log.Debug("no shell name provided in flags, trying to detect it")
pid := os.Getppid() pid := os.Getppid()
p, _ := process.NewProcess(int32(pid)) p, _ := process.NewProcess(int32(pid))
name, err := p.Name() name, err := p.Name()
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return UNKNOWN return UNKNOWN
} }
term.Debug("process name: " + name) log.Debug("process name: " + name)
// this is used for when scoop creates a shim, see // this is used for when scoop creates a shim, see
// https://github.com/jandedobbeleer/oh-my-posh/issues/2806 // https://github.com/jandedobbeleer/oh-my-posh/issues/2806
executable, _ := os.Executable() executable, _ := os.Executable()
if name == executable { if name == executable {
p, _ = p.Parent() p, _ = p.Parent()
name, err = p.Name() name, err = p.Name()
term.Debug("parent process name: " + name) log.Debug("parent process name: " + name)
} }
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return UNKNOWN return UNKNOWN
} }
// Cache the shell value to speed things up. // Cache the shell value to speed things up.
@ -424,7 +404,7 @@ func (term *Terminal) unWrapError(err error) error {
} }
func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...http.RequestModifier) ([]byte, error) { func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...http.RequestModifier) ([]byte, error) {
defer term.Trace(time.Now(), targetURL) defer log.Trace(time.Now(), targetURL)
ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout)) ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cncl() defer cncl()
@ -440,12 +420,12 @@ func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int,
if term.CmdFlags.Debug { if term.CmdFlags.Debug {
dump, _ := httputil.DumpRequestOut(request, true) dump, _ := httputil.DumpRequestOut(request, true)
term.Debug(string(dump)) log.Debug(string(dump))
} }
response, err := http.HTTPClient.Do(request) response, err := http.HTTPClient.Do(request)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil, term.unWrapError(err) return nil, term.unWrapError(err)
} }
@ -453,7 +433,7 @@ func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int,
if response.StatusCode < 200 || response.StatusCode >= 300 { if response.StatusCode < 200 || response.StatusCode >= 300 {
message := "HTTP status code " + strconv.Itoa(response.StatusCode) message := "HTTP status code " + strconv.Itoa(response.StatusCode)
err := errors.New(message) err := errors.New(message)
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
@ -461,17 +441,17 @@ func (term *Terminal) HTTPRequest(targetURL string, body io.Reader, timeout int,
responseBody, err := io.ReadAll(response.Body) responseBody, err := io.ReadAll(response.Body)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
term.Debug(string(responseBody)) log.Debug(string(responseBody))
return responseBody, nil return responseBody, nil
} }
func (term *Terminal) HasParentFilePath(parent string, followSymlinks bool) (*FileInfo, error) { func (term *Terminal) HasParentFilePath(parent string, followSymlinks bool) (*FileInfo, error) {
defer term.Trace(time.Now(), parent) defer log.Trace(time.Now(), parent)
pwd := term.Pwd() pwd := term.Pwd()
if followSymlinks { if followSymlinks {
@ -500,13 +480,13 @@ func (term *Terminal) HasParentFilePath(parent string, followSymlinks bool) (*Fi
continue continue
} }
term.Error(err) log.Error(err)
return nil, errors.New("no match at root level") return nil, errors.New("no match at root level")
} }
} }
func (term *Terminal) StackCount() int { func (term *Terminal) StackCount() int {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if term.CmdFlags.StackCount < 0 { if term.CmdFlags.StackCount < 0 {
return 0 return 0
@ -524,7 +504,7 @@ func (term *Terminal) Session() cache.Cache {
} }
func (term *Terminal) Close() { func (term *Terminal) Close() {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
term.clearCacheFiles() term.clearCacheFiles()
term.deviceCache.Close() term.deviceCache.Close()
term.sessionCache.Close() term.sessionCache.Close()
@ -537,12 +517,12 @@ func (term *Terminal) clearCacheFiles() {
deletedFiles, err := cache.Clear(cache.Path(), false) deletedFiles, err := cache.Clear(cache.Path(), false)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return return
} }
for _, file := range deletedFiles { for _, file := range deletedFiles {
term.DebugF("removed cache file: %s", file) log.Debugf("removed cache file: %s", file)
} }
} }
@ -556,7 +536,7 @@ func (term *Terminal) DirMatchesOneOf(dir string, regexes []string) (match bool)
// for the time being until we figure out what the actual root cause is // for the time being until we figure out what the actual root cause is
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
term.Error(errors.New("panic")) log.Error(errors.New("panic"))
match = false match = false
} }
}() }()
@ -595,7 +575,7 @@ func dirMatchesOneOf(dir, home, goos string, regexes []string) bool {
} }
func (term *Terminal) setPromptCount() { func (term *Terminal) setPromptCount() {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
var count int var count int
if val, found := term.Session().Get(cache.PROMPTCOUNTCACHE); found { if val, found := term.Session().Get(cache.PROMPTCOUNTCACHE); found {

View file

@ -6,6 +6,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "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/battery"
@ -34,13 +35,13 @@ 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) matches := regex.FindNamedRegexMatch(`(?P<PERCENTAGE>[0-9]{1,3})%; (?P<STATE>[a-zA-Z\s]+);`, output)
if len(matches) != 2 { if len(matches) != 2 {
err := errors.New("Unable to find battery state based on output") err := errors.New("Unable to find battery state based on output")
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
var percentage int var percentage int
var err error var err error
if percentage, err = strconv.Atoi(matches["PERCENTAGE"]); err != nil { if percentage, err = strconv.Atoi(matches["PERCENTAGE"]); err != nil {
term.Error(err) log.Error(err)
return nil, errors.New("Unable to parse battery percentage") return nil, errors.New("Unable to parse battery percentage")
} }
return &battery.Info{ return &battery.Info{
@ -50,10 +51,10 @@ func (term *Terminal) parseBatteryOutput(output string) (*battery.Info, error) {
} }
func (term *Terminal) BatteryState() (*battery.Info, error) { func (term *Terminal) BatteryState() (*battery.Info, error) {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
output, err := term.RunCommand("pmset", "-g", "batt") output, err := term.RunCommand("pmset", "-g", "batt")
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
if !strings.Contains(output, "Battery") { if !strings.Contains(output, "Battery") {

View file

@ -9,6 +9,7 @@ import (
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/cache" "github.com/jandedobbeleer/oh-my-posh/src/cache"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/shirou/gopsutil/v3/host" "github.com/shirou/gopsutil/v3/host"
mem "github.com/shirou/gopsutil/v3/mem" mem "github.com/shirou/gopsutil/v3/mem"
terminal "github.com/wayneashleyberry/terminal-dimensions" terminal "github.com/wayneashleyberry/terminal-dimensions"
@ -16,7 +17,7 @@ import (
) )
func (term *Terminal) Root() bool { func (term *Terminal) Root() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return os.Geteuid() == 0 return os.Geteuid() == 0
} }
@ -25,10 +26,10 @@ func (term *Terminal) QueryWindowTitles(_, _ string) (string, error) {
} }
func (term *Terminal) IsWsl() bool { func (term *Terminal) IsWsl() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
const key = "is_wsl" const key = "is_wsl"
if val, found := term.Cache().Get(key); found { if val, found := term.Cache().Get(key); found {
term.Debug(val) log.Debug(val)
return val == "true" return val == "true"
} }
@ -38,13 +39,13 @@ func (term *Terminal) IsWsl() bool {
}() }()
val = term.HasCommand("wslpath") val = term.HasCommand("wslpath")
term.Debug(strconv.FormatBool(val)) log.Debug(strconv.FormatBool(val))
return val return val
} }
func (term *Terminal) IsWsl2() bool { func (term *Terminal) IsWsl2() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if !term.IsWsl() { if !term.IsWsl() {
return false return false
} }
@ -53,21 +54,21 @@ func (term *Terminal) IsWsl2() bool {
} }
func (term *Terminal) IsCygwin() bool { func (term *Terminal) IsCygwin() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return false return false
} }
func (term *Terminal) TerminalWidth() (int, error) { func (term *Terminal) TerminalWidth() (int, error) {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if term.CmdFlags.TerminalWidth > 0 { if term.CmdFlags.TerminalWidth > 0 {
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth) log.Debugf("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, nil return term.CmdFlags.TerminalWidth, nil
} }
width, err := terminal.Width() width, err := terminal.Width()
if err != nil { if err != nil {
term.Error(err) log.Error(err)
} }
// fetch width from the environment variable // fetch width from the environment variable
@ -75,20 +76,20 @@ func (term *Terminal) TerminalWidth() (int, error) {
if width == 0 { if width == 0 {
i, err := strconv.Atoi(term.Getenv("COLUMNS")) i, err := strconv.Atoi(term.Getenv("COLUMNS"))
if err != nil { if err != nil {
term.Error(err) log.Error(err)
} }
width = uint(i) width = uint(i)
} }
term.CmdFlags.TerminalWidth = int(width) term.CmdFlags.TerminalWidth = int(width)
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth) log.Debugf("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, err return term.CmdFlags.TerminalWidth, err
} }
func (term *Terminal) Platform() string { func (term *Terminal) Platform() string {
const key = "environment_platform" const key = "environment_platform"
if val, found := term.Cache().Get(key); found { if val, found := term.Cache().Get(key); found {
term.Debug(val) log.Debug(val)
return val return val
} }
@ -99,7 +100,7 @@ func (term *Terminal) Platform() string {
if wsl := term.Getenv("WSL_DISTRO_NAME"); len(wsl) != 0 { if wsl := term.Getenv("WSL_DISTRO_NAME"); len(wsl) != 0 {
platform = strings.Split(strings.ToLower(wsl), "-")[0] platform = strings.Split(strings.ToLower(wsl), "-")[0]
term.Debug(platform) log.Debug(platform)
return platform return platform
} }
@ -112,7 +113,7 @@ func (term *Terminal) Platform() string {
} }
} }
term.Debug(platform) log.Debug(platform)
return platform return platform
} }
@ -144,7 +145,7 @@ func (term *Terminal) ConvertToLinuxPath(input string) string {
} }
func (term *Terminal) DirIsWritable(input string) bool { func (term *Terminal) DirIsWritable(input string) bool {
defer term.Trace(time.Now(), input) defer log.Trace(time.Now(), input)
return unix.Access(input, unix.W_OK) == nil return unix.Access(input, unix.W_OK) == nil
} }
@ -161,7 +162,7 @@ func (term *Terminal) Memory() (*Memory, error) {
m := &Memory{} m := &Memory{}
memStat, err := mem.VirtualMemory() memStat, err := mem.VirtualMemory()
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
m.PhysicalTotalMemory = memStat.Total m.PhysicalTotalMemory = memStat.Total
@ -170,7 +171,7 @@ func (term *Terminal) Memory() (*Memory, error) {
m.PhysicalPercentUsed = memStat.UsedPercent m.PhysicalPercentUsed = memStat.UsedPercent
swapStat, err := mem.SwapMemory() swapStat, err := mem.SwapMemory()
if err != nil { if err != nil {
term.Error(err) log.Error(err)
} }
m.SwapTotalMemory = swapStat.Total m.SwapTotalMemory = swapStat.Total
m.SwapFreeMemory = swapStat.Free m.SwapFreeMemory = swapStat.Free

View file

@ -8,13 +8,14 @@ import (
"time" "time"
"github.com/Azure/go-ansiterm/winterm" "github.com/Azure/go-ansiterm/winterm"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/path" "github.com/jandedobbeleer/oh-my-posh/src/runtime/path"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
"golang.org/x/sys/windows/registry" "golang.org/x/sys/windows/registry"
) )
func (term *Terminal) Root() bool { func (term *Terminal) Root() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
var sid *windows.SID var sid *windows.SID
// Although this looks scary, it is directly copied from the // Although this looks scary, it is directly copied from the
@ -29,7 +30,7 @@ func (term *Terminal) Root() bool {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&sid) &sid)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return false return false
} }
defer func() { defer func() {
@ -43,7 +44,7 @@ func (term *Terminal) Root() bool {
member, err := token.IsMember(sid) member, err := token.IsMember(sid)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return false return false
} }
@ -51,51 +52,51 @@ func (term *Terminal) Root() bool {
} }
func (term *Terminal) QueryWindowTitles(processName, windowTitleRegex string) (string, error) { func (term *Terminal) QueryWindowTitles(processName, windowTitleRegex string) (string, error) {
defer term.Trace(time.Now(), windowTitleRegex) defer log.Trace(time.Now(), windowTitleRegex)
title, err := queryWindowTitles(processName, windowTitleRegex) title, err := queryWindowTitles(processName, windowTitleRegex)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
} }
return title, err return title, err
} }
func (term *Terminal) IsWsl() bool { func (term *Terminal) IsWsl() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return false return false
} }
func (term *Terminal) IsWsl2() bool { func (term *Terminal) IsWsl2() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return false return false
} }
func (term *Terminal) IsCygwin() bool { func (term *Terminal) IsCygwin() bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return len(term.Getenv("OSTYPE")) > 0 return len(term.Getenv("OSTYPE")) > 0
} }
func (term *Terminal) TerminalWidth() (int, error) { func (term *Terminal) TerminalWidth() (int, error) {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
if term.CmdFlags.TerminalWidth > 0 { if term.CmdFlags.TerminalWidth > 0 {
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth) log.Debugf("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, nil return term.CmdFlags.TerminalWidth, nil
} }
handle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0) handle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return 0, err return 0, err
} }
info, err := winterm.GetConsoleScreenBufferInfo(uintptr(handle)) info, err := winterm.GetConsoleScreenBufferInfo(uintptr(handle))
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return 0, err return 0, err
} }
term.CmdFlags.TerminalWidth = int(info.Size.X) term.CmdFlags.TerminalWidth = int(info.Size.X)
term.DebugF("terminal width: %d", term.CmdFlags.TerminalWidth) log.Debugf("terminal width: %d", term.CmdFlags.TerminalWidth)
return term.CmdFlags.TerminalWidth, nil return term.CmdFlags.TerminalWidth, nil
} }
@ -113,7 +114,7 @@ func (term *Terminal) Platform() string {
// //
// Returns a variant type if successful; nil and an error if not. // Returns a variant type if successful; nil and an error if not.
func (term *Terminal) WindowsRegistryKeyValue(input string) (*WindowsRegistryValue, error) { func (term *Terminal) WindowsRegistryKeyValue(input string) (*WindowsRegistryValue, error) {
term.Trace(time.Now(), input) log.Trace(time.Now(), input)
// Format: // Format:
// "HKLM\Software\Microsoft\Windows NT\CurrentVersion\EditionID" // "HKLM\Software\Microsoft\Windows NT\CurrentVersion\EditionID"
@ -130,7 +131,7 @@ func (term *Terminal) WindowsRegistryKeyValue(input string) (*WindowsRegistryVal
rootKey, regPath, found := strings.Cut(input, `\`) rootKey, regPath, found := strings.Cut(input, `\`)
if !found { if !found {
err := fmt.Errorf("Error, malformed registry path: '%s'", input) err := fmt.Errorf("Error, malformed registry path: '%s'", input)
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
@ -156,19 +157,19 @@ func (term *Terminal) WindowsRegistryKeyValue(input string) (*WindowsRegistryVal
key = windows.HKEY_USERS key = windows.HKEY_USERS
default: default:
err := fmt.Errorf("Error, unknown registry key: '%s", rootKey) err := fmt.Errorf("Error, unknown registry key: '%s", rootKey)
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
k, err := registry.OpenKey(key, regPath, registry.READ) k, err := registry.OpenKey(key, regPath, registry.READ)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
_, valType, err := k.GetValue(regKey, nil) _, valType, err := k.GetValue(regKey, nil)
if err != nil { if err != nil {
term.Error(err) log.Error(err)
return nil, err return nil, err
} }
@ -194,7 +195,7 @@ func (term *Terminal) WindowsRegistryKeyValue(input string) (*WindowsRegistryVal
return nil, errors.New(errorLogMsg) return nil, errors.New(errorLogMsg)
} }
term.Debug(fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String)) log.Debug(fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String))
return regValue, nil return regValue, nil
} }
@ -211,7 +212,7 @@ func (term *Terminal) ConvertToLinuxPath(input string) string {
} }
func (term *Terminal) DirIsWritable(input string) bool { func (term *Terminal) DirIsWritable(input string) bool {
defer term.Trace(time.Now()) defer log.Trace(time.Now())
return term.isWriteable(input) return term.isWriteable(input)
} }
@ -230,6 +231,6 @@ func (term *Terminal) Connection(connectionType ConnectionType) (*Connection, er
} }
} }
term.Error(fmt.Errorf("Network type '%s' not found", connectionType)) log.Error(fmt.Errorf("Network type '%s' not found", connectionType))
return nil, &NotImplemented{} return nil, &NotImplemented{}
} }

View file

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

View file

@ -8,6 +8,7 @@ import (
"syscall" "syscall"
"unsafe" "unsafe"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
"golang.org/x/sys/windows" "golang.org/x/sys/windows"
@ -223,20 +224,20 @@ func (env *Terminal) isWriteable(folder string) bool {
if err != nil { if err != nil {
// unable to get current user // unable to get current user
env.Error(err) log.Error(err)
return false return false
} }
si, err := windows.GetNamedSecurityInfo(folder, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) si, err := windows.GetNamedSecurityInfo(folder, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)
if err != nil { if err != nil {
env.Error(err) log.Error(err)
return false return false
} }
dacl, _, err := si.DACL() dacl, _, err := si.DACL()
if err != nil || dacl == nil { if err != nil || dacl == nil {
// no dacl implies full access // no dacl implies full access
env.Debug("no dacl") log.Debug("no dacl")
return true return true
} }
@ -248,32 +249,32 @@ func (env *Terminal) isWriteable(folder string) bool {
ret, _, _ := procGetAce.Call(uintptr(unsafe.Pointer(dacl)), uintptr(i), uintptr(unsafe.Pointer(&ace))) ret, _, _ := procGetAce.Call(uintptr(unsafe.Pointer(dacl)), uintptr(i), uintptr(unsafe.Pointer(&ace)))
if ret == 0 { if ret == 0 {
env.Debug("no ace found") log.Debug("no ace found")
return false return false
} }
aceSid := (*windows.SID)(unsafe.Pointer(&ace.SidStart)) aceSid := (*windows.SID)(unsafe.Pointer(&ace.SidStart))
if !cu.isMemberOf(aceSid) { if !cu.isMemberOf(aceSid) {
env.Debug("not current user or in group") log.Debug("not current user or in group")
continue continue
} }
env.Debug(fmt.Sprintf("current user is member of %s", aceSid.String())) log.Debug(fmt.Sprintf("current user is member of %s", aceSid.String()))
// this gets priority over the other access types // this gets priority over the other access types
if ace.AceType == ACCESS_DENIED_ACE_TYPE { if ace.AceType == ACCESS_DENIED_ACE_TYPE {
env.Debug("ACCESS_DENIED_ACE_TYPE") log.Debug("ACCESS_DENIED_ACE_TYPE")
return false return false
} }
env.DebugF("%v", ace.AccessMask.permissions()) log.Debugf("%v", ace.AccessMask.permissions())
if ace.AccessMask.canWrite() { if ace.AccessMask.canWrite() {
env.Debug("user has write access") log.Debug("user has write access")
return true return true
} }
} }
env.Debug("no write access") log.Debug("no write access")
return false return false
} }
@ -299,7 +300,7 @@ func (env *Terminal) Memory() (*Memory, error) {
memStat.Length = uint32(unsafe.Sizeof(memStat)) memStat.Length = uint32(unsafe.Sizeof(memStat))
r0, _, err := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memStat))) r0, _, err := globalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memStat)))
if r0 == 0 { if r0 == 0 {
env.Error(err) log.Error(err)
return nil, err return nil, err
} }
return &Memory{ return &Memory{

View file

@ -6,6 +6,7 @@ import (
"path" "path"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -45,7 +46,7 @@ func (a *Argocd) Enabled() bool {
configPath := a.getConfigPath() configPath := a.getConfigPath()
succeeded, err := a.parseConfig(configPath) succeeded, err := a.parseConfig(configPath)
if err != nil { if err != nil {
a.env.Error(err) log.Error(err)
return false return false
} }
return succeeded return succeeded
@ -83,7 +84,7 @@ func (a *Argocd) parseConfig(file string) (bool, error) {
var data ArgocdConfig var data ArgocdConfig
err := yaml.Unmarshal([]byte(config), &data) err := yaml.Unmarshal([]byte(config), &data)
if err != nil { if err != nil {
a.env.Error(err) log.Error(err)
return false, errors.New(argocdInvalidYaml) return false, errors.New(argocdInvalidYaml)
} }
a.Name = data.CurrentContext a.Name = data.CurrentContext

View file

@ -9,7 +9,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -160,7 +159,6 @@ users:
for _, tc := range cases { for _, tc := range cases {
env := new(mock.Environment) env := new(mock.Environment)
env.On("FileContent", configFile).Return(tc.Config) env.On("FileContent", configFile).Return(tc.Config)
env.On("Error", testify_.Anything).Return()
argocd := &Argocd{ argocd := &Argocd{
base: base{ base: base{
@ -257,7 +255,6 @@ servers:
env.On("Home").Return(poshHome) env.On("Home").Return(poshHome)
env.On("Getenv", argocdOptsEnv).Return(tc.Opts) env.On("Getenv", argocdOptsEnv).Return(tc.Opts)
env.On("FileContent", configFile).Return(tc.Config) env.On("FileContent", configFile).Return(tc.Config)
env.On("Error", testify_.Anything).Return()
env.On("Flags").Return(&runtime.Flags{}) env.On("Flags").Return(&runtime.Flags{})
argocd := &Argocd{} argocd := &Argocd{}

View file

@ -4,6 +4,8 @@ import (
"encoding/json" "encoding/json"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
) )
type Azd struct { type Azd struct {
@ -33,7 +35,7 @@ func (t *Azd) Enabled() bool {
} }
if len(parentFilePath) == 0 { if len(parentFilePath) == 0 {
t.env.Debug("no .azure folder found in parent directories") log.Debug("no .azure folder found in parent directories")
return false return false
} }

View file

@ -10,7 +10,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestAzdSegment(t *testing.T) { func TestAzdSegment(t *testing.T) {
@ -36,7 +35,6 @@ func TestAzdSegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.Environment) env := new(mock.Environment)
env.On("Debug", testify_.Anything)
env.On("Flags").Return(&runtime.Flags{}) env.On("Flags").Return(&runtime.Flags{})
if tc.IsInited { if tc.IsInited {

View file

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
) )
@ -64,7 +65,7 @@ func (d *CarbonIntensity) Enabled() bool {
err := d.setStatus() err := d.setStatus()
if err != nil { if err != nil {
d.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -10,7 +10,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -226,7 +225,6 @@ func TestCarbonIntensitySegmentSingle(t *testing.T) {
} }
env.On("HTTPRequest", CARBONINTENSITYURL).Return([]byte(jsonResponse), responseError) env.On("HTTPRequest", CARBONINTENSITYURL).Return([]byte(jsonResponse), responseError)
env.On("Error", testify_.Anything)
env.On("Flags").Return(&runtime.Flags{}) env.On("Flags").Return(&runtime.Flags{})
d := &CarbonIntensity{} d := &CarbonIntensity{}

View file

@ -5,6 +5,8 @@ import (
"errors" "errors"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
) )
const ( const (
@ -29,13 +31,13 @@ func (f *Firebase) Enabled() bool {
cfgDir := filepath.Join(f.env.Home(), ".config", "configstore") cfgDir := filepath.Join(f.env.Home(), ".config", "configstore")
configFile, err := f.getActiveConfig(cfgDir) configFile, err := f.getActiveConfig(cfgDir)
if err != nil { if err != nil {
f.env.Error(err) log.Error(err)
return false return false
} }
data, err := f.getFirebaseData(configFile) data, err := f.getFirebaseData(configFile)
if err != nil { if err != nil {
f.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -7,7 +7,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestFirebaseSegment(t *testing.T) { func TestFirebaseSegment(t *testing.T) {
@ -59,7 +58,6 @@ func TestFirebaseSegment(t *testing.T) {
env.On("Pwd").Return(tc.ActivePath) env.On("Pwd").Return(tc.ActivePath)
fcPath := filepath.Join("home", ".config", "configstore", "firebase-tools.json") fcPath := filepath.Join("home", ".config", "configstore", "firebase-tools.json")
env.On("FileContent", fcPath).Return(tc.ActiveConfig) env.On("FileContent", fcPath).Return(tc.ActiveConfig)
env.On("Error", testify_.Anything).Return()
f := &Firebase{} f := &Firebase{}
f.Init(properties.Map{}, env) f.Init(properties.Map{}, env)
@ -104,7 +102,6 @@ func TestGetFirebaseActiveConfig(t *testing.T) {
configPath := filepath.Join("home", ".config", "configstore") configPath := filepath.Join("home", ".config", "configstore")
contentPath := filepath.Join(configPath, "firebase-tools.json") contentPath := filepath.Join(configPath, "firebase-tools.json")
env.On("FileContent", contentPath).Return(tc.ActiveConfig) env.On("FileContent", contentPath).Return(tc.ActiveConfig)
env.On("Error", testify_.Anything).Return()
f := &Firebase{} f := &Firebase{}
f.Init(properties.Map{}, env) f.Init(properties.Map{}, env)

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"path" "path"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"gopkg.in/ini.v1" "gopkg.in/ini.v1"
@ -29,7 +30,7 @@ func (g *Gcp) Enabled() bool {
cfgDir := g.getConfigDirectory() cfgDir := g.getConfigDirectory()
configFile, err := g.getActiveConfig(cfgDir) configFile, err := g.getActiveConfig(cfgDir)
if err != nil { if err != nil {
g.env.Error(err) log.Error(err)
return false return false
} }
@ -37,13 +38,13 @@ func (g *Gcp) Enabled() bool {
cfg := g.env.FileContent(cfgpath) cfg := g.env.FileContent(cfgpath)
if len(cfg) == 0 { if len(cfg) == 0 {
g.env.Error(errors.New("config file is empty")) log.Error(errors.New("config file is empty"))
return false return false
} }
data, err := ini.Load([]byte(cfg)) data, err := ini.Load([]byte(cfg))
if err != nil { if err != nil {
g.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -9,7 +9,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestGcpSegment(t *testing.T) { func TestGcpSegment(t *testing.T) {
@ -58,7 +57,6 @@ func TestGcpSegment(t *testing.T) {
env.On("FileContent", fcPath).Return(tc.ActiveConfig) env.On("FileContent", fcPath).Return(tc.ActiveConfig)
cfgpath := path.Join("config", "configurations", "config_production") cfgpath := path.Join("config", "configurations", "config_production")
env.On("FileContent", cfgpath).Return(tc.CfgData) env.On("FileContent", cfgpath).Return(tc.CfgData)
env.On("Error", testify_.Anything).Return()
g := &Gcp{} g := &Gcp{}
g.Init(properties.Map{}, env) g.Init(properties.Map{}, env)

View file

@ -8,6 +8,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
@ -401,7 +402,7 @@ func (g *Git) hasWorktree(gitdir *runtime.FileInfo) bool {
matches := regex.FindNamedRegexMatch(`^gitdir: (?P<dir>.*)$`, content) matches := regex.FindNamedRegexMatch(`^gitdir: (?P<dir>.*)$`, content)
if len(matches) == 0 { if len(matches) == 0 {
g.env.Debug("no matches found, directory isn't a worktree") log.Debug("no matches found, directory isn't a worktree")
return false return false
} }

View file

@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
) )
@ -54,7 +55,7 @@ func (d *LastFM) Enabled() bool {
err := d.setStatus() err := d.setStatus()
if err != nil { if err != nil {
d.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -61,7 +60,6 @@ func TestLFMSegmentSingle(t *testing.T) {
} }
env.On("HTTPRequest", LFMAPIURL).Return([]byte(tc.APIJSONResponse), tc.Error) env.On("HTTPRequest", LFMAPIURL).Return([]byte(tc.APIJSONResponse), tc.Error)
env.On("Error", testify_.Anything)
lfm := &LastFM{} lfm := &LastFM{}
lfm.Init(props, env) lfm.Init(props, env)

View file

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"time" "time"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
) )
@ -292,17 +293,17 @@ func (nba *Nba) getResult() (*NBAData, error) {
httpTimeout := nba.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout) httpTimeout := nba.props.GetInt(properties.HTTPTimeout, properties.DefaultHTTPTimeout)
nba.env.Debug("fetching available data for " + teamName) log.Debug("fetching available data for " + teamName)
data, err := nba.getAvailableGameData(teamName, httpTimeout) data, err := nba.getAvailableGameData(teamName, httpTimeout)
if err != nil { if err != nil {
nba.env.Error(errors.Join(err, fmt.Errorf("unable to get data for team %s", teamName))) log.Error(errors.Join(err, fmt.Errorf("unable to get data for team %s", teamName)))
return nil, err return nil, err
} }
if !data.GameStatus.Valid() { if !data.GameStatus.Valid() {
err := fmt.Errorf("%d is not a valid game status", data.GameStatus) err := fmt.Errorf("%d is not a valid game status", data.GameStatus)
nba.env.Error(err) log.Error(err)
return nil, err return nil, err
} }

View file

@ -10,7 +10,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func getTestData(file string) string { func getTestData(file string) string {
@ -80,8 +79,6 @@ func TestNBASegment(t *testing.T) {
DaysOffset: tc.DaysOffset, DaysOffset: tc.DaysOffset,
} }
env.On("Error", testify_.Anything)
env.On("Debug", testify_.Anything)
env.On("HTTPRequest", NBAScoreURL).Return([]byte(tc.JSONResponse), tc.Error) env.On("HTTPRequest", NBAScoreURL).Return([]byte(tc.JSONResponse), tc.Error)
// Add all the daysOffset to the http request responses // Add all the daysOffset to the http request responses

View file

@ -7,6 +7,7 @@ import (
"math" "math"
"net/url" "net/url"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
) )
@ -53,7 +54,7 @@ func (d *Owm) Enabled() bool {
err := d.setStatus() err := d.setStatus()
if err != nil { if err != nil {
d.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -10,7 +10,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
const ( const (
@ -82,7 +81,6 @@ func TestOWMSegmentSingle(t *testing.T) {
location := url.QueryEscape(tc.Location) location := url.QueryEscape(tc.Location)
testURL := fmt.Sprintf(OWMWEATHERAPIURL, location) testURL := fmt.Sprintf(OWMWEATHERAPIURL, location)
env.On("HTTPRequest", testURL).Return([]byte(tc.WeatherJSONResponse), tc.Error) env.On("HTTPRequest", testURL).Return([]byte(tc.WeatherJSONResponse), tc.Error)
env.On("Error", testify_.Anything)
o := &Owm{} o := &Owm{}
o.Init(props, env) o.Init(props, env)

View file

@ -6,6 +6,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
@ -249,13 +250,13 @@ func (pt *Path) getMaxWidth() int {
text, err := tmpl.Render() text, err := tmpl.Render()
if err != nil { if err != nil {
pt.env.Error(err) log.Error(err)
return 0 return 0
} }
value, err := strconv.Atoi(text) value, err := strconv.Atoi(text)
if err != nil { if err != nil {
pt.env.Error(err) log.Error(err)
return 0 return 0
} }
@ -281,7 +282,7 @@ func (pt *Path) getFolderSeparator() string {
text, err := tmpl.Render() text, err := tmpl.Render()
if err != nil { if err != nil {
pt.env.Error(err) log.Error(err)
} }
if len(text) == 0 { if len(text) == 0 {
@ -574,7 +575,7 @@ func (pt *Path) setMappedLocations() {
location, err := tmpl.Render() location, err := tmpl.Render()
if err != nil { if err != nil {
pt.env.Error(err) log.Error(err)
} }
if len(location) == 0 { if len(location) == 0 {

View file

@ -122,8 +122,6 @@ func TestAgnosterPathStyles(t *testing.T) {
} }
env.On("Shell").Return(tc.Shell) env.On("Shell").Return(tc.Shell)
env.On("DebugF", testify_.Anything, testify_.Anything).Return(nil)
displayCygpath := tc.Cygwin displayCygpath := tc.Cygwin
if displayCygpath { if displayCygpath {
env.On("RunCommand", "cygpath", []string{"-u", tc.Pwd}).Return(tc.Cygpath, tc.CygpathError) env.On("RunCommand", "cygpath", []string{"-u", tc.Pwd}).Return(tc.Cygpath, tc.CygpathError)
@ -360,7 +358,6 @@ func TestGetFolderSeparator(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.Environment) env := new(mock.Environment)
env.On("Error", testify_.Anything)
env.On("Shell").Return(shell.GENERIC) env.On("Shell").Return(shell.GENERIC)
template.Cache = &cache.Template{ template.Cache = &cache.Template{
@ -481,7 +478,6 @@ func TestGetMaxWidth(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.Environment) env := new(mock.Environment)
env.On("Error", testify_.Anything).Return(nil)
env.On("Getenv", "MAX_WIDTH").Return("120") env.On("Getenv", "MAX_WIDTH").Return("120")
env.On("Shell").Return(shell.BASH) env.On("Shell").Return(shell.BASH)

View file

@ -4,6 +4,8 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
) )
const ( const (
@ -46,14 +48,14 @@ func (s *GitStatus) parsePoshGitStatus(p *poshGitStatus) {
func (g *Git) hasPoshGitStatus() bool { func (g *Git) hasPoshGitStatus() bool {
envStatus := g.env.Getenv(poshGitEnv) envStatus := g.env.Getenv(poshGitEnv)
if len(envStatus) == 0 { if len(envStatus) == 0 {
g.env.Error(fmt.Errorf("%s environment variable not set, do you have the posh-git module installed?", poshGitEnv)) log.Error(fmt.Errorf("%s environment variable not set, do you have the posh-git module installed?", poshGitEnv))
return false return false
} }
var posh poshGit var posh poshGit
err := json.Unmarshal([]byte(envStatus), &posh) err := json.Unmarshal([]byte(envStatus), &posh)
if err != nil { if err != nil {
g.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestPoshGitSegment(t *testing.T) { func TestPoshGitSegment(t *testing.T) {
@ -187,7 +186,6 @@ func TestPoshGitSegment(t *testing.T) {
env.On("Getenv", poshGitEnv).Return(tc.PoshGitJSON) env.On("Getenv", poshGitEnv).Return(tc.PoshGitJSON)
env.On("Home").Return("/Users/bill") env.On("Home").Return("/Users/bill")
env.On("GOOS").Return(runtime.LINUX) env.On("GOOS").Return(runtime.LINUX)
env.On("Error", testify_.Anything)
env.On("RunCommand", "git", []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false", env.On("RunCommand", "git", []string{"-C", "", "--no-optional-locks", "-c", "core.quotepath=false",
"-c", "color.status=false", "remote", "get-url", "origin"}).Return("github.com/cli", nil) "-c", "color.status=false", "remote", "get-url", "origin"}).Return("github.com/cli", nil)

View file

@ -7,6 +7,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
@ -256,7 +257,7 @@ func (n *Project) getDotnetProject(_ ProjectItem) *ProjectData {
} }
if len(target) == 0 { if len(target) == 0 {
n.env.Error(fmt.Errorf("cannot extract TFM from %s project file", name)) log.Error(fmt.Errorf("cannot extract TFM from %s project file", name))
} }
return &ProjectData{ return &ProjectData{

View file

@ -487,7 +487,6 @@ func TestDotnetProject(t *testing.T) {
}, },
}) })
env.On("FileContent", tc.FileName).Return(tc.ProjectContents) env.On("FileContent", tc.FileName).Return(tc.ProjectContents)
env.On("Error", testify_.Anything)
pkg := &Project{} pkg := &Project{}
pkg.Init(properties.Map{}, env) pkg.Init(properties.Map{}, env)
assert.Equal(t, tc.ExpectedEnabled, pkg.Enabled(), tc.Case) assert.Equal(t, tc.ExpectedEnabled, pkg.Enabled(), tc.Case)

View file

@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/path" "github.com/jandedobbeleer/oh-my-posh/src/runtime/path"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
@ -58,7 +59,7 @@ func (p *Pulumi) Enabled() bool {
err := p.getProjectName() err := p.getProjectName()
if err != nil { if err != nil {
p.env.Error(err) log.Error(err)
return false return false
} }
@ -75,7 +76,7 @@ func (p *Pulumi) Enabled() bool {
func (p *Pulumi) getPulumiStackName() { func (p *Pulumi) getPulumiStackName() {
if len(p.Name) == 0 || len(p.workspaceSHA1) == 0 { if len(p.Name) == 0 || len(p.workspaceSHA1) == 0 {
p.env.Debug("pulumi project name or workspace sha1 is empty") log.Debug("pulumi project name or workspace sha1 is empty")
return return
} }
@ -94,11 +95,11 @@ func (p *Pulumi) getPulumiStackName() {
var pulumiWorkspaceSpec pulumiWorkSpaceFileSpec var pulumiWorkspaceSpec pulumiWorkSpaceFileSpec
err := json.Unmarshal([]byte(workspaceCacheFileContent), &pulumiWorkspaceSpec) err := json.Unmarshal([]byte(workspaceCacheFileContent), &pulumiWorkspaceSpec)
if err != nil { if err != nil {
p.env.Error(fmt.Errorf("pulumi workspace file decode error")) log.Error(fmt.Errorf("pulumi workspace file decode error"))
return return
} }
p.env.DebugF("pulumi stack name: %s", pulumiWorkspaceSpec.Stack) log.Debugf("pulumi stack name: %s", pulumiWorkspaceSpec.Stack)
p.Stack = pulumiWorkspaceSpec.Stack p.Stack = pulumiWorkspaceSpec.Stack
} }
@ -130,7 +131,7 @@ func (p *Pulumi) getProjectName() error {
} }
if err != nil { if err != nil {
p.env.Error(err) log.Error(err)
return nil return nil
} }
@ -146,7 +147,7 @@ func (p *Pulumi) sha1HexString(s string) string {
_, err := h.Write([]byte(s)) _, err := h.Write([]byte(s))
if err != nil { if err != nil {
p.env.Error(err) log.Error(err)
return "" return ""
} }
@ -155,14 +156,14 @@ func (p *Pulumi) sha1HexString(s string) string {
func (p *Pulumi) getPulumiAbout() { func (p *Pulumi) getPulumiAbout() {
if len(p.Stack) == 0 { if len(p.Stack) == 0 {
p.env.Error(fmt.Errorf("pulumi stack name is empty, use `fetch_stack` property to enable stack fetching")) log.Error(fmt.Errorf("pulumi stack name is empty, use `fetch_stack` property to enable stack fetching"))
return return
} }
aboutOutput, err := p.env.RunCommand("pulumi", "about", "--json") aboutOutput, err := p.env.RunCommand("pulumi", "about", "--json")
if err != nil { if err != nil {
p.env.Error(fmt.Errorf("unable to get pulumi about output")) log.Error(fmt.Errorf("unable to get pulumi about output"))
return return
} }
@ -172,12 +173,12 @@ func (p *Pulumi) getPulumiAbout() {
err = json.Unmarshal([]byte(aboutOutput), &about) err = json.Unmarshal([]byte(aboutOutput), &about)
if err != nil { if err != nil {
p.env.Error(fmt.Errorf("pulumi about output decode error")) log.Error(fmt.Errorf("pulumi about output decode error"))
return return
} }
if about.Backend == nil { if about.Backend == nil {
p.env.Debug("pulumi about backend is not set") log.Debug("pulumi about backend is not set")
return return
} }

View file

@ -10,7 +10,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/path" "github.com/jandedobbeleer/oh-my-posh/src/runtime/path"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestPulumi(t *testing.T) { func TestPulumi(t *testing.T) {
@ -166,9 +165,6 @@ description: A Console App
pwd := "/home/foobar/Work/oh-my-posh/pulumi/projects/awesome-project" pwd := "/home/foobar/Work/oh-my-posh/pulumi/projects/awesome-project"
env.On("Pwd").Return(pwd) env.On("Pwd").Return(pwd)
env.On("Home").Return(filepath.Clean("/home/foobar")) env.On("Home").Return(filepath.Clean("/home/foobar"))
env.On("Error", testify_.Anything)
env.On("Debug", testify_.Anything)
env.On("DebugF", testify_.Anything, testify_.Anything)
env.On("HasFiles", pulumiYAML).Return(len(tc.YAMLConfig) > 0) env.On("HasFiles", pulumiYAML).Return(len(tc.YAMLConfig) > 0)
env.On("FileContent", pulumiYAML).Return(tc.YAMLConfig, nil) env.On("FileContent", pulumiYAML).Return(tc.YAMLConfig, nil)

View file

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"path" "path"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
) )
@ -32,14 +33,14 @@ type UserConfig struct {
func (s *Sitecore) Enabled() bool { func (s *Sitecore) Enabled() bool {
if !s.env.HasFiles(sitecoreFileName) || !s.env.HasFilesInDir(sitecoreFolderName, userFileName) { if !s.env.HasFiles(sitecoreFileName) || !s.env.HasFilesInDir(sitecoreFolderName, userFileName) {
s.env.Debug("sitecore cli configuration files were not found") log.Debug("sitecore cli configuration files were not found")
return false return false
} }
var userConfig, err = getUserConfig(s) var userConfig, err = getUserConfig(s)
if err != nil { if err != nil {
s.env.Error(err) log.Error(err)
return false return false
} }
@ -48,7 +49,7 @@ func (s *Sitecore) Enabled() bool {
displayDefault := s.props.GetBool(properties.DisplayDefault, true) displayDefault := s.props.GetBool(properties.DisplayDefault, true)
if !displayDefault && s.EndpointName == defaultEnpointName { if !displayDefault && s.EndpointName == defaultEnpointName {
s.env.Debug("displaying of the default environment is turned off") log.Debug("displaying of the default environment is turned off")
return false return false
} }

View file

@ -8,7 +8,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestSitecoreSegment(t *testing.T) { func TestSitecoreSegment(t *testing.T) {
@ -89,8 +88,6 @@ func TestSitecoreSegment(t *testing.T) {
env.On("HasFiles", "sitecore.json").Return(tc.SitecoreFileExists) env.On("HasFiles", "sitecore.json").Return(tc.SitecoreFileExists)
env.On("HasFilesInDir", ".sitecore", "user.json").Return(tc.UserFileExists) env.On("HasFilesInDir", ".sitecore", "user.json").Return(tc.UserFileExists)
env.On("FileContent", path.Join(".sitecore", "user.json")).Return(tc.UserFileContent) env.On("FileContent", path.Join(".sitecore", "user.json")).Return(tc.UserFileContent)
env.On("Debug", testify_.Anything)
env.On("Error", testify_.Anything)
props := properties.Map{ props := properties.Map{
properties.DisplayDefault: tc.DisplayDefault, properties.DisplayDefault: tc.DisplayDefault,

View file

@ -4,6 +4,7 @@ import (
"errors" "errors"
"path/filepath" "path/filepath"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
) )
@ -21,13 +22,13 @@ func (t *TalosCTL) Enabled() bool {
cfgDir := filepath.Join(t.env.Home(), ".talos") cfgDir := filepath.Join(t.env.Home(), ".talos")
configFile, err := t.getActiveConfig(cfgDir) configFile, err := t.getActiveConfig(cfgDir)
if err != nil { if err != nil {
t.env.Error(err) log.Error(err)
return false return false
} }
err = yaml.Unmarshal([]byte(configFile), t) err = yaml.Unmarshal([]byte(configFile), t)
if err != nil { if err != nil {
t.env.Error(err) log.Error(err)
return false return false
} }

View file

@ -7,7 +7,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestTalosctlSegment(t *testing.T) { func TestTalosctlSegment(t *testing.T) {
@ -44,7 +43,6 @@ func TestTalosctlSegment(t *testing.T) {
env.On("Home").Return("home") env.On("Home").Return("home")
fcPath := filepath.Join("home", ".talos", "config") fcPath := filepath.Join("home", ".talos", "config")
env.On("FileContent", fcPath).Return(tc.ActiveConfig) env.On("FileContent", fcPath).Return(tc.ActiveConfig)
env.On("Error", testify_.Anything).Return()
talos := TalosCTL{} talos := TalosCTL{}
talos.Init(properties.Map{}, env) talos.Init(properties.Map{}, env)
@ -82,7 +80,6 @@ func TestGetTalosctlActiveConfig(t *testing.T) {
configPath := filepath.Join("home", ".talos") configPath := filepath.Join("home", ".talos")
contentPath := filepath.Join(configPath, "config") contentPath := filepath.Join(configPath, "config")
env.On("FileContent", contentPath).Return(tc.ActiveConfig) env.On("FileContent", contentPath).Return(tc.ActiveConfig)
env.On("Error", testify_.Anything).Return()
talos := TalosCTL{} talos := TalosCTL{}
talos.Init(properties.Map{}, env) talos.Init(properties.Map{}, env)

View file

@ -4,6 +4,8 @@ import (
"encoding/xml" "encoding/xml"
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
) )
type Umbraco struct { type Umbraco struct {
@ -40,7 +42,7 @@ func (u *Umbraco) Enabled() bool {
} }
if len(location) == 0 { if len(location) == 0 {
u.env.Debug("no umbraco folder found in parent directories") log.Debug("no umbraco folder found in parent directories")
return false return false
} }
@ -85,7 +87,7 @@ func (u *Umbraco) Template() string {
func (u *Umbraco) TryFindModernUmbraco(configPath string) bool { func (u *Umbraco) TryFindModernUmbraco(configPath string) bool {
// Check the passed in filepath is not empty // Check the passed in filepath is not empty
if len(configPath) == 0 { if len(configPath) == 0 {
u.env.Debug("no configPath provided") log.Debug("no configPath provided")
return false return false
} }
@ -102,7 +104,7 @@ func (u *Umbraco) TryFindModernUmbraco(configPath string) bool {
err := xml.Unmarshal([]byte(contents), &csProjPackages) err := xml.Unmarshal([]byte(contents), &csProjPackages)
if err != nil { if err != nil {
u.env.Debug(err.Error()) log.Debug(err.Error())
} }
// Loop over all the package references // Loop over all the package references
@ -121,7 +123,7 @@ func (u *Umbraco) TryFindModernUmbraco(configPath string) bool {
func (u *Umbraco) TryFindLegacyUmbraco(configPath string) bool { func (u *Umbraco) TryFindLegacyUmbraco(configPath string) bool {
// Check the passed in filepath is not empty // Check the passed in filepath is not empty
if len(configPath) == 0 { if len(configPath) == 0 {
u.env.Debug("no configPath provided") log.Debug("no configPath provided")
return false return false
} }
@ -138,7 +140,7 @@ func (u *Umbraco) TryFindLegacyUmbraco(configPath string) bool {
err := xml.Unmarshal([]byte(contents), &webConfigAppSettings) err := xml.Unmarshal([]byte(contents), &webConfigAppSettings)
if err != nil { if err != nil {
u.env.Debug(err.Error()) log.Debug(err.Error())
} }
// Loop over all the package references // Loop over all the package references

View file

@ -12,7 +12,6 @@ import (
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
testify_ "github.com/stretchr/testify/mock"
) )
func TestUmbracoSegment(t *testing.T) { func TestUmbracoSegment(t *testing.T) {
@ -137,7 +136,6 @@ func TestUmbracoSegment(t *testing.T) {
env.On("FileContent", filepath.Join(umbracoProjectDirectory, "MyProject.csproj")).Return(sampleCSProj) env.On("FileContent", filepath.Join(umbracoProjectDirectory, "MyProject.csproj")).Return(sampleCSProj)
env.On("FileContent", filepath.Join(umbracoProjectDirectory, "ANonUmbracoProject.csproj")).Return(sampleNonUmbracoCSProj) env.On("FileContent", filepath.Join(umbracoProjectDirectory, "ANonUmbracoProject.csproj")).Return(sampleNonUmbracoCSProj)
env.On("FileContent", filepath.Join(umbracoProjectDirectory, "web.config")).Return(sampleWebConfig) env.On("FileContent", filepath.Join(umbracoProjectDirectory, "web.config")).Return(sampleWebConfig)
env.On("Debug", testify_.Anything)
if tc.HasUmbracoFolder { if tc.HasUmbracoFolder {
fileInfo := &runtime.FileInfo{ fileInfo := &runtime.FileInfo{

View file

@ -6,6 +6,7 @@ import (
"path/filepath" "path/filepath"
"strings" "strings"
"github.com/jandedobbeleer/oh-my-posh/src/log"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/regex" "github.com/jandedobbeleer/oh-my-posh/src/regex"
) )
@ -24,7 +25,7 @@ func (u *Unity) Template() string {
func (u *Unity) Enabled() bool { func (u *Unity) Enabled() bool {
unityVersion, err := u.GetUnityVersion() unityVersion, err := u.GetUnityVersion()
if err != nil { if err != nil {
u.env.Error(err) log.Error(err)
return false return false
} }
if len(unityVersion) == 0 { if len(unityVersion) == 0 {
@ -34,7 +35,7 @@ func (u *Unity) Enabled() bool {
csharpVersion, err := u.GetCSharpVersion() csharpVersion, err := u.GetCSharpVersion()
if err != nil { if err != nil {
u.env.Error(err) log.Error(err)
} }
u.CSharpVersion = csharpVersion u.CSharpVersion = csharpVersion
@ -44,12 +45,12 @@ func (u *Unity) Enabled() bool {
func (u *Unity) GetUnityVersion() (string, error) { func (u *Unity) GetUnityVersion() (string, error) {
projectDir, err := u.env.HasParentFilePath("ProjectSettings", false) projectDir, err := u.env.HasParentFilePath("ProjectSettings", false)
if err != nil { if err != nil {
u.env.Debug("no ProjectSettings parent folder found") log.Debug("no ProjectSettings parent folder found")
return "", err return "", err
} }
if !u.env.HasFilesInDir(projectDir.Path, "ProjectVersion.txt") { if !u.env.HasFilesInDir(projectDir.Path, "ProjectVersion.txt") {
u.env.Debug("no ProjectVersion.txt file found") log.Debug("no ProjectVersion.txt file found")
return "", err return "", err
} }
@ -114,7 +115,7 @@ func (u *Unity) GetCSharpVersion() (version string, err error) {
return csharpVersion, nil return csharpVersion, nil
} }
u.env.Debug(fmt.Sprintf("Unity version %s doesn't exist in the map", shortUnityVersion)) log.Debug(fmt.Sprintf("Unity version %s doesn't exist in the map", shortUnityVersion))
return u.GetCSharpVersionFromWeb(shortUnityVersion) return u.GetCSharpVersionFromWeb(shortUnityVersion)
} }

View file

@ -5,8 +5,6 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
testify_ "github.com/stretchr/testify/mock"
"github.com/jandedobbeleer/oh-my-posh/src/properties" "github.com/jandedobbeleer/oh-my-posh/src/properties"
"github.com/jandedobbeleer/oh-my-posh/src/runtime" "github.com/jandedobbeleer/oh-my-posh/src/runtime"
"github.com/jandedobbeleer/oh-my-posh/src/runtime/mock" "github.com/jandedobbeleer/oh-my-posh/src/runtime/mock"
@ -69,8 +67,6 @@ func TestUnitySegment(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.Environment) env := new(mock.Environment)
env.On("Error", testify_.Anything).Return()
env.On("Debug", testify_.Anything)
err := errors.New("no match at root level") err := errors.New("no match at root level")
var projectDir *runtime.FileInfo var projectDir *runtime.FileInfo
@ -158,8 +154,6 @@ func TestUnitySegmentCSharpWebRequest(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.Environment) env := new(mock.Environment)
env.On("Error", testify_.Anything).Return()
env.On("Debug", testify_.Anything)
err := errors.New("no match at root level") err := errors.New("no match at root level")
var projectDir *runtime.FileInfo var projectDir *runtime.FileInfo