refactor(debug): extract log from platform

This commit is contained in:
Jan De Dobbeleer 2022-11-21 11:10:50 +01:00 committed by Jan De Dobbeleer
parent 67d9a2589e
commit 59c1c3f7ba
21 changed files with 199 additions and 119 deletions

View file

@ -3,7 +3,6 @@ package http
import ( import (
"fmt" "fmt"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/platform"
"oh-my-posh/properties" "oh-my-posh/properties"
"testing" "testing"
@ -161,7 +160,7 @@ 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("Log", platform.Error, "OAuth", mock2.Anything).Return() env.On("Error", "OAuth", mock2.Anything).Return()
oauth := &OAuthRequest{ oauth := &OAuthRequest{
AccessTokenKey: accessTokenKey, AccessTokenKey: accessTokenKey,

View file

@ -34,13 +34,13 @@ func getCacheValue[a any](r *Request, key string) (a, error) {
if val, found := r.env.Cache().Get(key); found { if val, found := r.env.Cache().Get(key); found {
err := json.Unmarshal([]byte(val), &data) err := json.Unmarshal([]byte(val), &data)
if err != nil { if err != nil {
r.env.Log(platform.Error, "OAuth", err.Error()) r.env.Error("OAuth", err)
return data, err return data, err
} }
return data, nil return data, nil
} }
err := errors.New("no data in cache") err := errors.New("no data in cache")
r.env.Log(platform.Error, "OAuth", err.Error()) r.env.Error("OAuth", err)
return data, err return data, err
} }
@ -50,13 +50,13 @@ func do[a any](r *Request, url string, body io.Reader, requestModifiers ...platf
responseBody, err := r.env.HTTPRequest(url, body, httpTimeout, requestModifiers...) responseBody, err := r.env.HTTPRequest(url, body, httpTimeout, requestModifiers...)
if err != nil { if err != nil {
r.env.Log(platform.Error, "OAuth", err.Error()) r.env.Error("OAuth", err)
return data, err return data, err
} }
err = json.Unmarshal(responseBody, &data) err = json.Unmarshal(responseBody, &data)
if err != nil { if err != nil {
r.env.Log(platform.Error, "OAuth", err.Error()) r.env.Error("OAuth", err)
return data, err return data, err
} }

View file

@ -3,7 +3,6 @@ package http
import ( import (
"net" "net"
"oh-my-posh/mock" "oh-my-posh/mock"
"oh-my-posh/platform"
"oh-my-posh/properties" "oh-my-posh/properties"
"testing" "testing"
@ -75,7 +74,7 @@ func TestRequestResult(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("Log", platform.Error, "OAuth", mock2.Anything).Return() env.On("Error", "OAuth", mock2.Anything).Return()
request := &Request{} request := &Request{}
request.Init(env, props) request.Init(env, props)

24
src/log/entry.go Normal file
View file

@ -0,0 +1,24 @@
package log
type format byte
const (
Red format = 1 << iota
Yellow
)
type entry string
func (e *entry) Format(formats ...format) {
str := *e
for _, format := range formats {
switch format {
case Red:
str = "\033[31m" + str
case Yellow:
str = "\033[33m" + str
}
str += "\033[0m"
}
*e = str
}

67
src/log/log.go Normal file
View file

@ -0,0 +1,67 @@
package log
import (
"fmt"
"log"
"strings"
"time"
)
var enabled bool
var logBuilder strings.Builder
func Enable() {
enabled = true
log.SetOutput(&logBuilder)
}
func Info(message string) {
if !enabled {
return
}
log.Println(message)
}
func Trace(start time.Time, function string, args ...string) {
if !enabled {
return
}
elapsed := time.Since(start)
var argString string
if len(args) > 0 {
argString = fmt.Sprintf(", args: %s", strings.Join(args, " "))
}
trace := entry(fmt.Sprintf("%s: %s%s", function, elapsed, argString))
log.Println(trace)
}
func Debug(funcName, message string) {
if !enabled {
return
}
trace := entry(fmt.Sprintf("%s\n%s", funcName, message))
trace.Format(Yellow)
log.Println(trace)
}
func DebugF(function string, fn func() string) {
if !enabled {
return
}
trace := entry(fmt.Sprintf("%s\n%s", function, fn()))
trace.Format(Yellow)
log.Println(trace)
}
func Error(funcName string, err error) {
if !enabled {
return
}
trace := entry(fmt.Sprintf("%s\n%s", funcName, err.Error()))
trace.Format(Red)
log.Println(trace)
}
func String() string {
return logBuilder.String()
}

View file

@ -246,8 +246,12 @@ func (env *MockedEnvironment) Trace(start time.Time, function string, args ...st
_ = env.Called(start, function, args) _ = env.Called(start, function, args)
} }
func (env *MockedEnvironment) Log(logType platform.LogType, funcName, message string) { func (env *MockedEnvironment) Debug(funcName, message string) {
_ = env.Called(logType, funcName, message) _ = env.Called(funcName, message)
}
func (env *MockedEnvironment) Error(funcName string, err error) {
_ = env.Called(funcName, err)
} }
func (env *MockedEnvironment) DirIsWritable(path string) bool { func (env *MockedEnvironment) DirIsWritable(path string) bool {

View file

@ -244,7 +244,7 @@ func (env *Shell) parseNetworkInterface(network *WLAN_INTERFACE_INFO, clientHand
uintptr(unsafe.Pointer(&wlanAttr)), uintptr(unsafe.Pointer(&wlanAttr)),
uintptr(unsafe.Pointer(nil))) uintptr(unsafe.Pointer(nil)))
if e != 0 { if e != 0 {
env.Log(Error, "parseNetworkInterface", "wlan_intf_opcode_current_connection error") env.Error("parseNetworkInterface", err)
return &info, err return &info, err
} }

View file

@ -8,9 +8,9 @@ import (
"fmt" "fmt"
"io" "io"
"io/fs" "io/fs"
"log"
"net/http" "net/http"
"net/http/httputil" "net/http/httputil"
"oh-my-posh/log"
"oh-my-posh/platform/battery" "oh-my-posh/platform/battery"
"oh-my-posh/platform/cmd" "oh-my-posh/platform/cmd"
"oh-my-posh/regex" "oh-my-posh/regex"
@ -208,7 +208,8 @@ type Environment interface {
Connection(connectionType ConnectionType) (*Connection, error) Connection(connectionType ConnectionType) (*Connection, error)
TemplateCache() *TemplateCache TemplateCache() *TemplateCache
LoadTemplateCache() LoadTemplateCache()
Log(logType LogType, funcName, message string) Debug(funcName, message string)
Error(funcName string, err error)
Trace(start time.Time, function string, args ...string) Trace(start time.Time, function string, args ...string)
} }
@ -229,23 +230,15 @@ func (c *commandCache) get(command string) (string, bool) {
return command, ok return command, ok
} }
type LogType string
const (
Error LogType = "error"
Debug LogType = "debug"
)
type Shell struct { type Shell struct {
CmdFlags *Flags CmdFlags *Flags
Version string Version string
cwd string cwd string
cmdCache *commandCache cmdCache *commandCache
fileCache *fileCache fileCache *fileCache
tmplCache *TemplateCache tmplCache *TemplateCache
logBuilder strings.Builder networks []*Connection
networks []*Connection
} }
func (env *Shell) Init() { func (env *Shell) Init() {
@ -254,7 +247,7 @@ func (env *Shell) Init() {
env.CmdFlags = &Flags{} env.CmdFlags = &Flags{}
} }
if env.CmdFlags.Debug { if env.CmdFlags.Debug {
log.SetOutput(&env.logBuilder) log.Enable()
} }
env.fileCache = &fileCache{} env.fileCache = &fileCache{}
env.fileCache.Init(env.CachePath()) env.fileCache.Init(env.CachePath())
@ -316,34 +309,25 @@ func (env *Shell) downloadConfig(location string) error {
} }
func (env *Shell) Trace(start time.Time, function string, args ...string) { func (env *Shell) Trace(start time.Time, function string, args ...string) {
if env.CmdFlags == nil || !env.CmdFlags.Debug { log.Trace(start, function, args...)
return
}
elapsed := time.Since(start)
trace := fmt.Sprintf("%s duration: %s, args: %s", function, elapsed, strings.Trim(fmt.Sprint(args), "[]"))
log.Println(trace)
} }
func (env *Shell) Log(logType LogType, funcName, message string) { func (env *Shell) Debug(funcName, message string) {
if !env.CmdFlags.Debug { log.Debug(funcName, message)
return }
}
trace := fmt.Sprintf("%s: %s\n%s", logType, funcName, message) func (env *Shell) Error(funcName string, err error) {
log.Println(trace) log.Error(funcName, err)
} }
func (env *Shell) debugF(function string, fn func() string) { func (env *Shell) debugF(function string, fn func() string) {
if !env.CmdFlags.Debug { log.DebugF(function, fn)
return
}
trace := fmt.Sprintf("%s: %s\n%s", Debug, function, fn())
log.Println(trace)
} }
func (env *Shell) Getenv(key string) string { func (env *Shell) Getenv(key string) string {
defer env.Trace(time.Now(), "Getenv", key) defer env.Trace(time.Now(), "Getenv", key)
val := os.Getenv(key) val := os.Getenv(key)
env.Log(Debug, "Getenv", val) env.Debug("Getenv", val)
return val return val
} }
@ -352,7 +336,7 @@ func (env *Shell) Pwd() string {
lock.Lock() lock.Lock()
defer func() { defer func() {
lock.Unlock() lock.Unlock()
env.Log(Debug, "Pwd", env.cwd) env.Debug("Pwd", env.cwd)
}() }()
if env.cwd != "" { if env.cwd != "" {
return env.cwd return env.cwd
@ -371,7 +355,7 @@ func (env *Shell) Pwd() string {
} }
dir, err := os.Getwd() dir, err := os.Getwd()
if err != nil { if err != nil {
env.Log(Error, "Pwd", err.Error()) env.Error("Pwd", err)
return "" return ""
} }
env.cwd = correctPath(dir) env.cwd = correctPath(dir)
@ -384,7 +368,7 @@ func (env *Shell) HasFiles(pattern string) bool {
fileSystem := os.DirFS(cwd) fileSystem := os.DirFS(cwd)
matches, err := fs.Glob(fileSystem, pattern) matches, err := fs.Glob(fileSystem, pattern)
if err != nil { if err != nil {
env.Log(Error, "HasFiles", err.Error()) env.Error("HasFiles", err)
return false return false
} }
for _, match := range matches { for _, match := range matches {
@ -402,7 +386,7 @@ func (env *Shell) HasFilesInDir(dir, pattern string) bool {
fileSystem := os.DirFS(dir) fileSystem := os.DirFS(dir)
matches, err := fs.Glob(fileSystem, pattern) matches, err := fs.Glob(fileSystem, pattern)
if err != nil { if err != nil {
env.Log(Error, "HasFilesInDir", err.Error()) env.Error("HasFilesInDir", err)
return false return false
} }
hasFilesInDir := len(matches) > 0 hasFilesInDir := len(matches) > 0
@ -416,18 +400,18 @@ func (env *Shell) HasFileInParentDirs(pattern string, depth uint) bool {
for c := 0; c < int(depth); c++ { for c := 0; c < int(depth); c++ {
if env.HasFilesInDir(currentFolder, pattern) { if env.HasFilesInDir(currentFolder, pattern) {
env.Log(Debug, "HasFileInParentDirs", "true") env.Debug("HasFileInParentDirs", "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 {
env.Log(Debug, "HasFileInParentDirs", "false") env.Debug("HasFileInParentDirs", "false")
return false return false
} }
} }
env.Log(Debug, "HasFileInParentDirs", "false") env.Debug("HasFileInParentDirs", "false")
return false return false
} }
@ -435,7 +419,7 @@ func (env *Shell) HasFolder(folder string) bool {
defer env.Trace(time.Now(), "HasFolder", folder) defer env.Trace(time.Now(), "HasFolder", folder)
f, err := os.Stat(folder) f, err := os.Stat(folder)
if err != nil { if err != nil {
env.Log(Debug, "HasFolder", "false") env.Debug("HasFolder", "false")
return false return false
} }
env.debugF("HasFolder", func() string { return strconv.FormatBool(f.IsDir()) }) env.debugF("HasFolder", func() string { return strconv.FormatBool(f.IsDir()) })
@ -446,10 +430,10 @@ func (env *Shell) ResolveSymlink(path string) (string, error) {
defer env.Trace(time.Now(), "ResolveSymlink", path) defer env.Trace(time.Now(), "ResolveSymlink", path)
link, err := filepath.EvalSymlinks(path) link, err := filepath.EvalSymlinks(path)
if err != nil { if err != nil {
env.Log(Error, "ResolveSymlink", err.Error()) env.Error("ResolveSymlink", err)
return "", err return "", err
} }
env.Log(Debug, "ResolveSymlink", link) env.Debug("ResolveSymlink", link)
return link, nil return link, nil
} }
@ -460,11 +444,11 @@ func (env *Shell) FileContent(file string) string {
} }
content, err := os.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
env.Log(Error, "FileContent", err.Error()) env.Error("FileContent", err)
return "" return ""
} }
fileContent := string(content) fileContent := string(content)
env.Log(Debug, "FileContent", fileContent) env.Debug("FileContent", fileContent)
return fileContent return fileContent
} }
@ -472,7 +456,7 @@ func (env *Shell) LsDir(path string) []fs.DirEntry {
defer env.Trace(time.Now(), "LsDir", path) defer env.Trace(time.Now(), "LsDir", path)
entries, err := os.ReadDir(path) entries, err := os.ReadDir(path)
if err != nil { if err != nil {
env.Log(Error, "LsDir", err.Error()) env.Error("LsDir", err)
return nil return nil
} }
env.debugF("LsDir", func() string { env.debugF("LsDir", func() string {
@ -496,7 +480,7 @@ func (env *Shell) User() string {
if user == "" { if user == "" {
user = os.Getenv("USERNAME") user = os.Getenv("USERNAME")
} }
env.Log(Debug, "User", user) env.Debug("User", user)
return user return user
} }
@ -504,11 +488,11 @@ func (env *Shell) Host() (string, error) {
defer env.Trace(time.Now(), "Host") defer env.Trace(time.Now(), "Host")
hostName, err := os.Hostname() hostName, err := os.Hostname()
if err != nil { if err != nil {
env.Log(Error, "Host", err.Error()) env.Error("Host", err)
return "", err return "", err
} }
hostName = cleanHostName(hostName) hostName = cleanHostName(hostName)
env.Log(Debug, "Host", hostName) env.Debug("Host", hostName)
return hostName, nil return hostName, nil
} }
@ -524,9 +508,9 @@ func (env *Shell) 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 {
env.Log(Error, "RunCommand", "cmd.Run() failed") env.Error("RunCommand", err)
} }
env.Log(Debug, "RunCommand", output) env.Debug("RunCommand", output)
return output, err return output, err
} }
@ -541,22 +525,22 @@ func (env *Shell) RunShellCommand(shell, command string) string {
func (env *Shell) CommandPath(command string) string { func (env *Shell) CommandPath(command string) string {
defer env.Trace(time.Now(), "CommandPath", command) defer env.Trace(time.Now(), "CommandPath", command)
if path, ok := env.cmdCache.get(command); ok { if path, ok := env.cmdCache.get(command); ok {
env.Log(Debug, "CommandPath", path) env.Debug("CommandPath", path)
return path return path
} }
path, err := exec.LookPath(command) path, err := exec.LookPath(command)
if err == nil { if err == nil {
env.cmdCache.set(command, path) env.cmdCache.set(command, path)
env.Log(Debug, "CommandPath", path) env.Debug("CommandPath", path)
return path return path
} }
path, err = env.LookWinAppPath(command) path, err = env.LookWinAppPath(command)
if err == nil { if err == nil {
env.cmdCache.set(command, path) env.cmdCache.set(command, path)
env.Log(Debug, "CommandPath", path) env.Debug("CommandPath", path)
return path return path
} }
env.Log(Error, "CommandPath", err.Error()) env.Error("CommandPath", err)
return "" return ""
} }
@ -595,20 +579,20 @@ func (env *Shell) Shell() string {
p, _ := process.NewProcess(int32(pid)) p, _ := process.NewProcess(int32(pid))
name, err := p.Name() name, err := p.Name()
if err != nil { if err != nil {
env.Log(Error, "Shell", err.Error()) env.Error("Shell", err)
return UNKNOWN return UNKNOWN
} }
env.Log(Debug, "Shell", "process name: "+name) env.Debug("Shell", "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 == "cmd.exe" || name == executable { if name == "cmd.exe" || name == executable {
p, _ = p.Parent() p, _ = p.Parent()
name, err = p.Name() name, err = p.Name()
env.Log(Debug, "Shell", "parent process name: "+name) env.Debug("Shell", "parent process name: "+name)
} }
if err != nil { if err != nil {
env.Log(Error, "Shell", err.Error()) env.Error("Shell", err)
return UNKNOWN return UNKNOWN
} }
// Cache the shell value to speed things up. // Cache the shell value to speed things up.
@ -642,27 +626,27 @@ func (env *Shell) HTTPRequest(targetURL string, body io.Reader, timeout int, req
} }
if env.CmdFlags.Debug { if env.CmdFlags.Debug {
dump, _ := httputil.DumpRequestOut(request, true) dump, _ := httputil.DumpRequestOut(request, true)
env.Log(Debug, "HTTPRequest", string(dump)) env.Debug("HTTPRequest", string(dump))
} }
response, err := client.Do(request) response, err := client.Do(request)
if err != nil { if err != nil {
env.Log(Error, "HTTPRequest", err.Error()) env.Error("HTTPRequest", err)
return nil, env.unWrapError(err) return nil, env.unWrapError(err)
} }
// anything inside the range [200, 299] is considered a success // anything inside the range [200, 299] is considered a success
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)
env.Log(Error, "HTTPRequest", message) env.Error("HTTPRequest", err)
return nil, err return nil, err
} }
defer response.Body.Close() defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body) responseBody, err := io.ReadAll(response.Body)
if err != nil { if err != nil {
env.Log(Error, "HTTPRequest", err.Error()) env.Error("HTTPRequest", err)
return nil, err return nil, err
} }
env.Log(Debug, "HTTPRequest", string(responseBody)) env.Debug("HTTPRequest", string(responseBody))
return responseBody, nil return responseBody, nil
} }
@ -686,7 +670,7 @@ func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
currentFolder = dir currentFolder = dir
continue continue
} }
env.Log(Error, "HasParentFilePath", err.Error()) env.Error("HasParentFilePath", err)
return nil, errors.New("no match at root level") return nil, errors.New("no match at root level")
} }
} }
@ -721,14 +705,14 @@ func (env *Shell) LoadTemplateCache() {
var templateCache TemplateCache var templateCache TemplateCache
err := json.Unmarshal([]byte(val), &templateCache) err := json.Unmarshal([]byte(val), &templateCache)
if err != nil { if err != nil {
env.Log(Error, "LoadTemplateCache", err.Error()) env.Error("LoadTemplateCache", err)
return return
} }
env.tmplCache = &templateCache env.tmplCache = &templateCache
} }
func (env *Shell) Logs() string { func (env *Shell) Logs() string {
return env.logBuilder.String() return log.String()
} }
func (env *Shell) TemplateCache() *TemplateCache { func (env *Shell) TemplateCache() *TemplateCache {
@ -782,8 +766,7 @@ func (env *Shell) 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 {
message := fmt.Sprintf("%s", err) env.Error("DirMatchesOneOf", errors.New("panic"))
env.Log(Error, "DirMatchesOneOf", message)
match = false match = false
} }
}() }()

View file

@ -32,14 +32,14 @@ func mapMostLogicalState(state string) battery.State {
func (env *Shell) parseBatteryOutput(output string) (*battery.Info, error) { func (env *Shell) 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 {
msg := "Unable to find battery state based on output" err := errors.New("Unable to find battery state based on output")
env.Log(Error, "BatteryState", msg) env.Error("BatteryState", err)
return nil, errors.New(msg) 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 {
env.Log(Error, "BatteryState", err.Error()) env.Error("BatteryState", 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{
@ -52,7 +52,7 @@ func (env *Shell) BatteryState() (*battery.Info, error) {
defer env.Trace(time.Now(), "BatteryState") defer env.Trace(time.Now(), "BatteryState")
output, err := env.RunCommand("pmset", "-g", "batt") output, err := env.RunCommand("pmset", "-g", "batt")
if err != nil { if err != nil {
env.Log(Error, "BatteryState", err.Error()) env.Error("BatteryState", err)
return nil, err return nil, err
} }
if !strings.Contains(output, "Battery") { if !strings.Contains(output, "Battery") {

View file

@ -51,7 +51,7 @@ func (env *Shell) TerminalWidth() (int, error) {
} }
width, err := terminal.Width() width, err := terminal.Width()
if err != nil { if err != nil {
env.Log(Error, "TerminalWidth", err.Error()) env.Error("TerminalWidth", err)
} }
return int(width), err return int(width), err
} }

View file

@ -30,7 +30,7 @@ func (env *Shell) Root() bool {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
&sid) &sid)
if err != nil { if err != nil {
env.Log(Error, "Root", err.Error()) env.Error("Root", err)
return false return false
} }
defer func() { defer func() {
@ -44,7 +44,7 @@ func (env *Shell) Root() bool {
member, err := token.IsMember(sid) member, err := token.IsMember(sid)
if err != nil { if err != nil {
env.Log(Error, "Root", err.Error()) env.Error("Root", err)
return false return false
} }
@ -54,7 +54,7 @@ func (env *Shell) Root() bool {
func (env *Shell) Home() string { func (env *Shell) Home() string {
home := os.Getenv("HOME") home := os.Getenv("HOME")
defer func() { defer func() {
env.Log(Debug, "Home", home) env.Debug("Home", home)
}() }()
if len(home) > 0 { if len(home) > 0 {
return home return home
@ -71,7 +71,7 @@ func (env *Shell) QueryWindowTitles(processName, windowTitleRegex string) (strin
defer env.Trace(time.Now(), "WindowTitle", windowTitleRegex) defer env.Trace(time.Now(), "WindowTitle", windowTitleRegex)
title, err := queryWindowTitles(processName, windowTitleRegex) title, err := queryWindowTitles(processName, windowTitleRegex)
if err != nil { if err != nil {
env.Log(Error, "QueryWindowTitles", err.Error()) env.Error("QueryWindowTitles", err)
} }
return title, err return title, err
} }
@ -93,12 +93,12 @@ func (env *Shell) TerminalWidth() (int, error) {
} }
handle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0) handle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0)
if err != nil { if err != nil {
env.Log(Error, "TerminalWidth", err.Error()) env.Error("TerminalWidth", 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 {
env.Log(Error, "TerminalWidth", err.Error()) env.Error("TerminalWidth", err)
return 0, err return 0, err
} }
// return int(float64(info.Size.X) * 0.57), nil // return int(float64(info.Size.X) * 0.57), nil
@ -157,9 +157,9 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
// //
rootKey, regPath, found := strings.Cut(path, `\`) rootKey, regPath, found := strings.Cut(path, `\`)
if !found { if !found {
errorLogMsg := fmt.Sprintf("Error, malformed registry path: '%s'", path) err := fmt.Errorf("Error, malformed registry path: '%s'", path)
env.Log(Error, "WindowsRegistryKeyValue", errorLogMsg) env.Error("WindowsRegistryKeyValue", err)
return nil, errors.New(errorLogMsg) return nil, err
} }
regKey := Base(env, regPath) regKey := Base(env, regPath)
@ -180,19 +180,19 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
case "HKU", "HKEY_USERS": case "HKU", "HKEY_USERS":
key = windows.HKEY_USERS key = windows.HKEY_USERS
default: default:
errorLogMsg := fmt.Sprintf("Error, unknown registry key: '%s'", rootKey) err := fmt.Errorf("Error, unknown registry key: '%s", rootKey)
env.Log(Error, "WindowsRegistryKeyValue", errorLogMsg) env.Error("WindowsRegistryKeyValue", err)
return nil, errors.New(errorLogMsg) 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 {
env.Log(Error, "WindowsRegistryKeyValue", err.Error()) env.Error("WindowsRegistryKeyValue", 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 {
env.Log(Error, "WindowsRegistryKeyValue", err.Error()) env.Error("WindowsRegistryKeyValue", err)
return nil, err return nil, err
} }
@ -217,7 +217,7 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
errorLogMsg := fmt.Sprintf("Error, no formatter for type: %d", valType) errorLogMsg := fmt.Sprintf("Error, no formatter for type: %d", valType)
return nil, errors.New(errorLogMsg) return nil, errors.New(errorLogMsg)
} }
env.Log(Debug, "WindowsRegistryKeyValue", fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String)) env.Debug("WindowsRegistryKeyValue", fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String))
return regValue, nil return regValue, nil
} }
@ -251,6 +251,6 @@ func (env *Shell) Connection(connectionType ConnectionType) (*Connection, error)
return network, nil return network, nil
} }
} }
env.Log(Error, "network", fmt.Sprintf("Network type '%s' not found", connectionType)) env.Error("network", fmt.Errorf("Network type '%s' not found", connectionType))
return nil, &NotImplemented{} return nil, &NotImplemented{}
} }

View file

@ -11,7 +11,7 @@ func (env *Shell) BatteryState() (*battery.Info, error) {
defer env.Trace(time.Now(), "BatteryState") defer env.Trace(time.Now(), "BatteryState")
info, err := battery.Get() info, err := battery.Get()
if err != nil { if err != nil {
env.Log(Error, "BatteryState", err.Error()) env.Error("BatteryState", err)
return nil, err return nil, err
} }
return info, nil return info, nil

View file

@ -35,7 +35,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.Log(platform.Error, "Gcp.Enabled()", err.Error()) g.env.Error("Gcp.Enabled()", err)
return false return false
} }
@ -43,13 +43,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.Log(platform.Error, "Gcp.Enabled()", "config file is empty") g.env.Error("Gcp.Enabled()", 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.Log(platform.Error, "Gcp.Enabled()", err.Error()) g.env.Error("Gcp.Enabled()", err)
return false return false
} }

View file

@ -57,7 +57,7 @@ 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("Log", platform.Error, "Gcp.Enabled()", mock2.Anything).Return() env.On("Error", "Gcp.Enabled()", mock2.Anything).Return()
g := &Gcp{ g := &Gcp{
env: env, env: env,
} }

View file

@ -177,7 +177,7 @@ func (pt *Path) getFolderSeparator() string {
} }
text, err := tmpl.Render() text, err := tmpl.Render()
if err != nil { if err != nil {
pt.env.Log(platform.Error, "getFolderSeparator", err.Error()) pt.env.Error("getFolderSeparator", err)
} }
if len(text) == 0 { if len(text) == 0 {
return pt.env.PathSeparator() return pt.env.PathSeparator()
@ -404,7 +404,7 @@ func (pt *Path) replaceMappedLocations() (string, string) {
} }
path, err := tmpl.Render() path, err := tmpl.Render()
if err != nil { if err != nil {
pt.env.Log(platform.Error, "replaceMappedLocations", err.Error()) pt.env.Error("replaceMappedLocations", err)
} }
if len(path) == 0 { if len(path) == 0 {
continue continue

View file

@ -26,7 +26,8 @@ func renderTemplate(env *mock.MockedEnvironment, segmentTemplate string, context
Env: make(map[string]string), Env: make(map[string]string),
}) })
} }
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything)
tmpl := &template.Text{ tmpl := &template.Text{
Template: segmentTemplate, Template: segmentTemplate,
Context: context, Context: context,
@ -1292,7 +1293,8 @@ func TestGetFolderSeparator(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := new(mock.MockedEnvironment) env := new(mock.MockedEnvironment)
env.On("PathSeparator").Return("/") env.On("PathSeparator").Return("/")
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything)
path := &Path{ path := &Path{
env: env, env: env,
} }

View file

@ -126,7 +126,7 @@ func TestWTGetUrl(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
env.On("TemplateCache").Return(&platform.TemplateCache{ env.On("TemplateCache").Return(&platform.TemplateCache{
Env: map[string]string{"HELLO": "hello"}, Env: map[string]string{"HELLO": "hello"},
}) })

View file

@ -24,7 +24,8 @@ func TestUrl(t *testing.T) {
env.On("TemplateCache").Return(&platform.TemplateCache{ env.On("TemplateCache").Return(&platform.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
}) })
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,

View file

@ -31,7 +31,8 @@ func TestRoundSeconds(t *testing.T) {
env.On("TemplateCache").Return(&platform.TemplateCache{ env.On("TemplateCache").Return(&platform.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
}) })
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,

View file

@ -48,7 +48,7 @@ func (t *Text) Render() (string, error) {
t.cleanTemplate() t.cleanTemplate()
tmpl, err := template.New(t.Template).Funcs(funcMap()).Parse(t.Template) tmpl, err := template.New(t.Template).Funcs(funcMap()).Parse(t.Template)
if err != nil { if err != nil {
t.Env.Log(platform.Error, "Render", err.Error()) t.Env.Error("Render", err)
return "", errors.New(InvalidTemplate) return "", errors.New(InvalidTemplate)
} }
context := &Context{} context := &Context{}
@ -57,7 +57,7 @@ func (t *Text) Render() (string, error) {
defer buffer.Reset() defer buffer.Reset()
err = tmpl.Execute(buffer, context) err = tmpl.Execute(buffer, context)
if err != nil { if err != nil {
t.Env.Log(platform.Error, "Render", err.Error()) t.Env.Error("Render", err)
return "", errors.New(IncorrectTemplate) return "", errors.New(IncorrectTemplate)
} }
text := buffer.String() text := buffer.String()

View file

@ -152,7 +152,7 @@ func TestRenderTemplate(t *testing.T) {
env.On("TemplateCache").Return(&platform.TemplateCache{ env.On("TemplateCache").Return(&platform.TemplateCache{
Env: make(map[string]string), Env: make(map[string]string),
}) })
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,
@ -209,7 +209,7 @@ func TestRenderTemplateEnvVar(t *testing.T) {
env.On("TemplateCache").Return(&platform.TemplateCache{ env.On("TemplateCache").Return(&platform.TemplateCache{
Env: tc.Env, Env: tc.Env,
}) })
env.On("Log", mock2.Anything, mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything, mock2.Anything)
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,
Context: tc.Context, Context: tc.Context,