chore(logs): pretty logs

This commit is contained in:
Jan De Dobbeleer 2023-01-16 20:58:43 +01:00 committed by Jan De Dobbeleer
parent 32fcf792ab
commit 3ef7f1b481
25 changed files with 260 additions and 216 deletions

View file

@ -97,7 +97,7 @@ func LoadConfig(env platform.Environment) *Config {
} }
func loadConfig(env platform.Environment) *Config { func loadConfig(env platform.Environment) *Config {
defer env.Trace(time.Now(), "config.loadConfig") defer env.Trace(time.Now())
configFile := env.Flags().Config configFile := env.Flags().Config
if len(configFile) == 0 { if len(configFile) == 0 {

View file

@ -221,9 +221,8 @@ func (e *Engine) renderBlock(block *Block) {
// debug will loop through your config file and output the timings for each segments // debug will loop through your config file and output the timings for each segments
func (e *Engine) PrintDebug(startTime time.Time, version string) string { func (e *Engine) PrintDebug(startTime time.Time, version string) string {
var segmentTimings []*SegmentTiming var segmentTimings []*SegmentTiming
largestSegmentNameLength := 0 e.write(fmt.Sprintf("\n\x1b[38;2;191;207;240m\x1b[1mVersion:\x1b[0m %s\n", version))
e.write(fmt.Sprintf("\n\x1b[1mVersion:\x1b[0m %s\n", version)) e.write("\n\x1b[38;2;191;207;240m\x1b[1mSegments:\x1b[0m\n\n")
e.write("\n\x1b[1mSegments:\x1b[0m\n\n")
// console title timing // console title timing
titleStartTime := time.Now() titleStartTime := time.Now()
title := e.getTitleTemplateText() title := e.getTitleTemplateText()
@ -234,6 +233,7 @@ func (e *Engine) PrintDebug(startTime time.Time, version string) string {
text: title, text: title,
duration: time.Since(titleStartTime), duration: time.Since(titleStartTime),
} }
largestSegmentNameLength := 12
segmentTimings = append(segmentTimings, segmentTiming) segmentTimings = append(segmentTimings, segmentTiming)
// cache a pointer to the color cycle // cache a pointer to the color cycle
cycle = &e.Config.Cycle cycle = &e.Config.Cycle
@ -254,10 +254,10 @@ func (e *Engine) PrintDebug(startTime time.Time, version string) string {
segmentName := fmt.Sprintf("%s(%t)", segment.name, segment.active) segmentName := fmt.Sprintf("%s(%t)", segment.name, segment.active)
e.write(fmt.Sprintf("%-*s - %3d ms - %s\n", largestSegmentNameLength, segmentName, duration, segment.text)) e.write(fmt.Sprintf("%-*s - %3d ms - %s\n", largestSegmentNameLength, segmentName, duration, segment.text))
} }
e.write(fmt.Sprintf("\n\x1b[1mRun duration:\x1b[0m %s\n", time.Since(startTime))) e.write(fmt.Sprintf("\n\x1b[38;2;191;207;240m\x1b[1mRun duration:\x1b[0m %s\n", time.Since(startTime)))
e.write(fmt.Sprintf("\n\x1b[1mCache path:\x1b[0m %s\n", e.Env.CachePath())) e.write(fmt.Sprintf("\n\x1b[38;2;191;207;240m\x1b[1mCache path:\x1b[0m %s\n", e.Env.CachePath()))
e.write(fmt.Sprintf("\n\x1b[1mConfig path:\x1b[0m %s\n", e.Env.Flags().Config)) e.write(fmt.Sprintf("\n\x1b[38;2;191;207;240m\x1b[1mConfig path:\x1b[0m %s\n", e.Env.Flags().Config))
e.write("\n\x1b[1mLogs:\x1b[0m\n\n") e.write("\n\x1b[38;2;191;207;240m\x1b[1mLogs:\x1b[0m\n\n")
e.write(e.Env.Logs()) e.write(e.Env.Logs())
return e.string() return e.string()
} }

View file

@ -161,7 +161,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("Error", "OAuth", mock2.Anything).Return() env.On("Error", mock2.Anything).Return()
oauth := &OAuthRequest{ oauth := &OAuthRequest{
AccessTokenKey: accessTokenKey, AccessTokenKey: accessTokenKey,

View file

@ -35,13 +35,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.Error("OAuth", err) r.env.Error(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.Error("OAuth", err) r.env.Error(err)
return data, err return data, err
} }
@ -51,13 +51,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.Error("OAuth", err) r.env.Error(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.Error("OAuth", err) r.env.Error(err)
return data, err return data, err
} }

View file

@ -75,7 +75,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("Error", "OAuth", mock2.Anything).Return() env.On("Error", mock2.Anything).Return()
request := &Request{} request := &Request{}
request.Init(env, props) request.Init(env, props)

View file

@ -1,24 +0,0 @@
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
}

View file

@ -2,66 +2,77 @@ package log
import ( import (
"fmt" "fmt"
"log" "path/filepath"
"runtime"
"strings" "strings"
"time" "time"
) )
var enabled bool var enabled bool
var logBuilder strings.Builder var log strings.Builder
func Enable() { func Enable() {
enabled = true enabled = true
log.SetOutput(&logBuilder)
} }
func Info(message string) { func Info(message string) {
if !enabled { if !enabled {
return return
} }
log.Println(message) log.WriteString(message)
} }
func Trace(start time.Time, function string, args ...string) { func Trace(start time.Time, args ...string) {
if !enabled { if !enabled {
return return
} }
elapsed := time.Since(start) elapsed := time.Since(start)
var argString string fn, _ := funcSpec()
if len(args) > 0 { header := fmt.Sprintf("%s(%s) - \x1b[38;2;156;231;201m%s\033[0m", fn, strings.Join(args, " "), elapsed)
argString = fmt.Sprintf(", args: %s", strings.Join(args, " ")) printLn(trace, header)
}
trace := entry(fmt.Sprintf("%s: %s%s", function, elapsed, argString))
log.Println(trace)
} }
func Debug(funcName, message string) { func Debug(message string) {
if !enabled { if !enabled {
return return
} }
trace := entry(fmt.Sprintf("%s\n%s", funcName, message)) fn, line := funcSpec()
trace.Format(Yellow) header := fmt.Sprintf("%s:%d", fn, line)
log.Println(trace) printLn(debug, header, message)
} }
func DebugF(function string, fn func() string) { func DebugF(fn func() string) {
if !enabled { if !enabled {
return return
} }
trace := entry(fmt.Sprintf("%s\n%s", function, fn())) fn2, line := funcSpec()
trace.Format(Yellow) header := fmt.Sprintf("%s:%d", fn2, line)
log.Println(trace) printLn(debug, header, fn())
} }
func Error(funcName string, err error) { func Error(err error) {
if !enabled { if !enabled {
return return
} }
trace := entry(fmt.Sprintf("%s\n%s", funcName, err.Error())) fn, line := funcSpec()
trace.Format(Red) header := fmt.Sprintf("%s:%d", fn, line)
log.Println(trace) printLn(bug, header, err.Error())
} }
func String() string { func String() string {
return logBuilder.String() return log.String()
}
func funcSpec() (string, int) {
pc, file, line, OK := runtime.Caller(3)
if !OK {
return "", 0
}
fn := runtime.FuncForPC(pc).Name()
fn = fn[strings.LastIndex(fn, ".")+1:]
file = filepath.Base(file)
if strings.HasPrefix(fn, "func") {
return file, line
}
return fmt.Sprintf("%s:%s", file, fn), line
} }

61
src/log/print.go Normal file
View file

@ -0,0 +1,61 @@
package log
import (
"fmt"
"strings"
"time"
)
type logType byte
const (
debug logType = 1 << iota
bug
trace
)
func printLn(lt logType, args ...string) {
if len(args) == 0 {
return
}
var str string
switch lt {
case debug:
str = "\x1b[38;2;191;207;240m[DEBUG] "
case bug:
str = "\x1b[38;2;253;122;140m[ERROR] "
case trace:
str = "\x1b[38;2;204;137;214m[TRACE] "
}
// timestamp 156, 231, 201
str += fmt.Sprintf("\x1b[38;2;156;231;201m%s ", time.Now().Format("15:04:05.000"))
str += "\033[0m"
str += args[0]
str += parseArgs(args...)
log.WriteString(str)
}
func parseArgs(args ...string) string {
if len(args) == 1 {
return "\n"
}
// display empty return values as NO DATA
if len(args[1]) == 0 {
return " \x1b[38;2;156;231;201m\u2192\033[0m \x1b[38;2;253;122;140mNO DATA\033[0m\n"
}
// print a single line for single output
splitted := strings.Split(args[1], "\n")
if len(splitted) == 1 {
return fmt.Sprintf(" \x1b[38;2;156;231;201m\u2192\033[0m %s\n", args[1])
}
// indent multiline output with 4 spaces
var str string
str += " \x1b[38;2;156;231;201m\u2193\033[0m\n"
for _, line := range splitted {
str += fmt.Sprintf(" %s\n", line)
}
return str
}

View file

@ -248,16 +248,16 @@ func (env *MockedEnvironment) DirMatchesOneOf(dir string, regexes []string) bool
return args.Bool(0) return args.Bool(0)
} }
func (env *MockedEnvironment) Trace(start time.Time, function string, args ...string) { func (env *MockedEnvironment) Trace(start time.Time, args ...string) {
_ = env.Called(start, function, args) _ = env.Called(start, args)
} }
func (env *MockedEnvironment) Debug(funcName, message string) { func (env *MockedEnvironment) Debug(message string) {
_ = env.Called(funcName, message) _ = env.Called(message)
} }
func (env *MockedEnvironment) Error(funcName string, err error) { func (env *MockedEnvironment) Error(err error) {
_ = env.Called(funcName, err) _ = env.Called(err)
} }
func (env *MockedEnvironment) DirIsWritable(path string) bool { func (env *MockedEnvironment) DirIsWritable(path string) bool {

View file

@ -200,7 +200,7 @@ func (env *Shell) getConnections() []*Connection {
} }
func (env *Shell) wifiNetwork() (*Connection, error) { func (env *Shell) wifiNetwork() (*Connection, error) {
env.Trace(time.Now(), "wifiNetwork") env.Trace(time.Now())
// Open handle // Open handle
var pdwNegotiatedVersion uint32 var pdwNegotiatedVersion uint32
var phClientHandle uint32 var phClientHandle uint32
@ -250,7 +250,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.Error("parseNetworkInterface", err) env.Error(err)
return &info, err return &info, err
} }

View file

@ -205,9 +205,9 @@ type Environment interface {
Connection(connectionType ConnectionType) (*Connection, error) Connection(connectionType ConnectionType) (*Connection, error)
TemplateCache() *TemplateCache TemplateCache() *TemplateCache
LoadTemplateCache() LoadTemplateCache()
Debug(funcName, message string) Debug(message string)
Error(funcName string, err error) Error(err error)
Trace(start time.Time, function string, args ...string) Trace(start time.Time, args ...string)
} }
type commandCache struct { type commandCache struct {
@ -241,7 +241,7 @@ type Shell struct {
} }
func (env *Shell) Init() { func (env *Shell) Init() {
defer env.Trace(time.Now(), "Init") defer env.Trace(time.Now())
if env.CmdFlags == nil { if env.CmdFlags == nil {
env.CmdFlags = &Flags{} env.CmdFlags = &Flags{}
} }
@ -257,7 +257,7 @@ func (env *Shell) Init() {
} }
func (env *Shell) resolveConfigPath() { func (env *Shell) resolveConfigPath() {
defer env.Trace(time.Now(), "resolveConfigPath") defer env.Trace(time.Now())
if len(env.CmdFlags.Config) == 0 { if len(env.CmdFlags.Config) == 0 {
env.CmdFlags.Config = env.Getenv("POSH_THEME") env.CmdFlags.Config = env.Getenv("POSH_THEME")
} }
@ -288,7 +288,7 @@ func (env *Shell) resolveConfigPath() {
} }
func (env *Shell) downloadConfig(location string) error { func (env *Shell) downloadConfig(location string) error {
defer env.Trace(time.Now(), "downloadConfig", location) defer env.Trace(time.Now(), location)
ext := filepath.Ext(location) ext := filepath.Ext(location)
configPath := filepath.Join(env.CachePath(), "config.omp"+ext) configPath := filepath.Join(env.CachePath(), "config.omp"+ext)
cfg, err := env.HTTPRequest(location, nil, 5000) cfg, err := env.HTTPRequest(location, nil, 5000)
@ -308,34 +308,32 @@ func (env *Shell) downloadConfig(location string) error {
return nil return nil
} }
func (env *Shell) Trace(start time.Time, function string, args ...string) { func (env *Shell) Trace(start time.Time, args ...string) {
log.Trace(start, function, args...) log.Trace(start, args...)
} }
func (env *Shell) Debug(funcName, message string) { func (env *Shell) Debug(message string) {
log.Debug(funcName, message) log.Debug(message)
} }
func (env *Shell) Error(funcName string, err error) { func (env *Shell) Error(err error) {
log.Error(funcName, err) log.Error(err)
} }
func (env *Shell) debugF(function string, fn func() string) { func (env *Shell) debugF(fn func() string) {
log.DebugF(function, fn) log.DebugF(fn)
} }
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(), key)
val := os.Getenv(key) val := os.Getenv(key)
env.Debug("Getenv", val) env.Debug(val)
return val return val
} }
func (env *Shell) Pwd() string { func (env *Shell) Pwd() string {
defer env.Trace(time.Now(), "Pwd") defer env.Trace(time.Now())
defer func() { defer env.Debug(env.cwd)
env.Debug("Pwd", env.cwd)
}()
if env.cwd != "" { if env.cwd != "" {
return env.cwd return env.cwd
} }
@ -353,7 +351,7 @@ func (env *Shell) Pwd() string {
} }
dir, err := os.Getwd() dir, err := os.Getwd()
if err != nil { if err != nil {
env.Error("Pwd", err) env.Error(err)
return "" return ""
} }
env.cwd = correctPath(dir) env.cwd = correctPath(dir)
@ -361,12 +359,12 @@ func (env *Shell) Pwd() string {
} }
func (env *Shell) HasFiles(pattern string) bool { func (env *Shell) HasFiles(pattern string) bool {
defer env.Trace(time.Now(), "HasFiles", pattern) defer env.Trace(time.Now(), pattern)
cwd := env.Pwd() cwd := env.Pwd()
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.Error("HasFiles", err) env.Error(err)
return false return false
} }
for _, match := range matches { for _, match := range matches {
@ -380,84 +378,84 @@ func (env *Shell) HasFiles(pattern string) bool {
} }
func (env *Shell) HasFilesInDir(dir, pattern string) bool { func (env *Shell) HasFilesInDir(dir, pattern string) bool {
defer env.Trace(time.Now(), "HasFilesInDir", pattern) defer env.Trace(time.Now(), pattern)
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.Error("HasFilesInDir", err) env.Error(err)
return false return false
} }
hasFilesInDir := len(matches) > 0 hasFilesInDir := len(matches) > 0
env.debugF("HasFilesInDir", func() string { return strconv.FormatBool(hasFilesInDir) }) env.debugF(func() string { return strconv.FormatBool(hasFilesInDir) })
return hasFilesInDir return hasFilesInDir
} }
func (env *Shell) HasFileInParentDirs(pattern string, depth uint) bool { func (env *Shell) HasFileInParentDirs(pattern string, depth uint) bool {
defer env.Trace(time.Now(), "HasFileInParent", pattern, fmt.Sprint(depth)) defer env.Trace(time.Now(), pattern, fmt.Sprint(depth))
currentFolder := env.Pwd() currentFolder := env.Pwd()
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.Debug("HasFileInParentDirs", "true") env.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 {
env.Debug("HasFileInParentDirs", "false") env.Debug("false")
return false return false
} }
} }
env.Debug("HasFileInParentDirs", "false") env.Debug("false")
return false return false
} }
func (env *Shell) HasFolder(folder string) bool { func (env *Shell) HasFolder(folder string) bool {
defer env.Trace(time.Now(), "HasFolder", folder) defer env.Trace(time.Now(), folder)
f, err := os.Stat(folder) f, err := os.Stat(folder)
if err != nil { if err != nil {
env.Debug("HasFolder", "false") env.Debug("false")
return false return false
} }
env.debugF("HasFolder", func() string { return strconv.FormatBool(f.IsDir()) }) env.debugF(func() string { return strconv.FormatBool(f.IsDir()) })
return f.IsDir() return f.IsDir()
} }
func (env *Shell) ResolveSymlink(path string) (string, error) { func (env *Shell) ResolveSymlink(path string) (string, error) {
defer env.Trace(time.Now(), "ResolveSymlink", path) defer env.Trace(time.Now(), path)
link, err := filepath.EvalSymlinks(path) link, err := filepath.EvalSymlinks(path)
if err != nil { if err != nil {
env.Error("ResolveSymlink", err) env.Error(err)
return "", err return "", err
} }
env.Debug("ResolveSymlink", link) env.Debug(link)
return link, nil return link, nil
} }
func (env *Shell) FileContent(file string) string { func (env *Shell) FileContent(file string) string {
defer env.Trace(time.Now(), "FileContent", file) defer env.Trace(time.Now(), file)
if !filepath.IsAbs(file) { if !filepath.IsAbs(file) {
file = filepath.Join(env.Pwd(), file) file = filepath.Join(env.Pwd(), file)
} }
content, err := os.ReadFile(file) content, err := os.ReadFile(file)
if err != nil { if err != nil {
env.Error("FileContent", err) env.Error(err)
return "" return ""
} }
fileContent := string(content) fileContent := string(content)
env.Debug("FileContent", fileContent) env.Debug(fileContent)
return fileContent return fileContent
} }
func (env *Shell) LsDir(path string) []fs.DirEntry { func (env *Shell) LsDir(path string) []fs.DirEntry {
defer env.Trace(time.Now(), "LsDir", path) defer env.Trace(time.Now(), path)
entries, err := os.ReadDir(path) entries, err := os.ReadDir(path)
if err != nil { if err != nil {
env.Error("LsDir", err) env.Error(err)
return nil return nil
} }
env.debugF("LsDir", func() string { env.debugF(func() string {
var entriesStr string var entriesStr string
for _, entry := range entries { for _, entry := range entries {
entriesStr += entry.Name() + "\n" entriesStr += entry.Name() + "\n"
@ -468,52 +466,52 @@ func (env *Shell) LsDir(path string) []fs.DirEntry {
} }
func (env *Shell) PathSeparator() string { func (env *Shell) PathSeparator() string {
defer env.Trace(time.Now(), "PathSeparator") defer env.Trace(time.Now())
return string(os.PathSeparator) return string(os.PathSeparator)
} }
func (env *Shell) User() string { func (env *Shell) User() string {
defer env.Trace(time.Now(), "User") defer env.Trace(time.Now())
user := os.Getenv("USER") user := os.Getenv("USER")
if user == "" { if user == "" {
user = os.Getenv("USERNAME") user = os.Getenv("USERNAME")
} }
env.Debug("User", user) env.Debug(user)
return user return user
} }
func (env *Shell) Host() (string, error) { func (env *Shell) Host() (string, error) {
defer env.Trace(time.Now(), "Host") defer env.Trace(time.Now())
hostName, err := os.Hostname() hostName, err := os.Hostname()
if err != nil { if err != nil {
env.Error("Host", err) env.Error(err)
return "", err return "", err
} }
hostName = cleanHostName(hostName) hostName = cleanHostName(hostName)
env.Debug("Host", hostName) env.Debug(hostName)
return hostName, nil return hostName, nil
} }
func (env *Shell) GOOS() string { func (env *Shell) GOOS() string {
defer env.Trace(time.Now(), "GOOS") defer env.Trace(time.Now())
return runtime.GOOS return runtime.GOOS
} }
func (env *Shell) RunCommand(command string, args ...string) (string, error) { func (env *Shell) RunCommand(command string, args ...string) (string, error) {
defer env.Trace(time.Now(), "RunCommand", append([]string{command}, args...)...) defer env.Trace(time.Now(), append([]string{command}, args...)...)
if cacheCommand, ok := env.cmdCache.get(command); ok { if cacheCommand, ok := env.cmdCache.get(command); ok {
command = cacheCommand command = cacheCommand
} }
output, err := cmd.Run(command, args...) output, err := cmd.Run(command, args...)
if err != nil { if err != nil {
env.Error("RunCommand", err) env.Error(err)
} }
env.Debug("RunCommand", output) env.Debug(output)
return output, err return output, err
} }
func (env *Shell) RunShellCommand(shell, command string) string { func (env *Shell) RunShellCommand(shell, command string) string {
defer env.Trace(time.Now(), "RunShellCommand") defer env.Trace(time.Now())
if out, err := env.RunCommand(shell, "-c", command); err == nil { if out, err := env.RunCommand(shell, "-c", command); err == nil {
return out return out
} }
@ -521,23 +519,23 @@ 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(), command)
if path, ok := env.cmdCache.get(command); ok { if path, ok := env.cmdCache.get(command); ok {
env.Debug("CommandPath", path) env.Debug(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.Debug("CommandPath", path) env.Debug(path)
return path return path
} }
env.Error("CommandPath", err) env.Error(err)
return "" return ""
} }
func (env *Shell) HasCommand(command string) bool { func (env *Shell) HasCommand(command string) bool {
defer env.Trace(time.Now(), "HasCommand", command) defer env.Trace(time.Now(), command)
if path := env.CommandPath(command); path != "" { if path := env.CommandPath(command); path != "" {
return true return true
} }
@ -545,12 +543,12 @@ func (env *Shell) HasCommand(command string) bool {
} }
func (env *Shell) ErrorCode() int { func (env *Shell) ErrorCode() int {
defer env.Trace(time.Now(), "ErrorCode") defer env.Trace(time.Now())
return env.CmdFlags.ErrorCode return env.CmdFlags.ErrorCode
} }
func (env *Shell) ExecutionTime() float64 { func (env *Shell) ExecutionTime() float64 {
defer env.Trace(time.Now(), "ExecutionTime") defer env.Trace(time.Now())
if env.CmdFlags.ExecutionTime < 0 { if env.CmdFlags.ExecutionTime < 0 {
return 0 return 0
} }
@ -558,12 +556,12 @@ func (env *Shell) ExecutionTime() float64 {
} }
func (env *Shell) Flags() *Flags { func (env *Shell) Flags() *Flags {
defer env.Trace(time.Now(), "Flags") defer env.Trace(time.Now())
return env.CmdFlags return env.CmdFlags
} }
func (env *Shell) Shell() string { func (env *Shell) Shell() string {
defer env.Trace(time.Now(), "Shell") defer env.Trace(time.Now())
if env.CmdFlags.Shell != "" { if env.CmdFlags.Shell != "" {
return env.CmdFlags.Shell return env.CmdFlags.Shell
} }
@ -571,20 +569,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.Error("Shell", err) env.Error(err)
return UNKNOWN return UNKNOWN
} }
env.Debug("Shell", "process name: "+name) env.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 == "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.Debug("Shell", "parent process name: "+name) env.Debug("parent process name: " + name)
} }
if err != nil { if err != nil {
env.Error("Shell", err) env.Error(err)
return UNKNOWN return UNKNOWN
} }
// Cache the shell value to speed things up. // Cache the shell value to speed things up.
@ -606,7 +604,7 @@ func (env *Shell) unWrapError(err error) error {
} }
func (env *Shell) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) { func (env *Shell) HTTPRequest(targetURL string, body io.Reader, timeout int, requestModifiers ...HTTPRequestModifier) ([]byte, error) {
defer env.Trace(time.Now(), "HTTPRequest", targetURL) defer env.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()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, body) request, err := http.NewRequestWithContext(ctx, http.MethodGet, targetURL, body)
@ -618,32 +616,32 @@ 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.Debug("HTTPRequest", string(dump)) env.Debug(string(dump))
} }
response, err := client.Do(request) response, err := client.Do(request)
if err != nil { if err != nil {
env.Error("HTTPRequest", err) env.Error(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.Error("HTTPRequest", err) env.Error(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.Error("HTTPRequest", err) env.Error(err)
return nil, err return nil, err
} }
env.Debug("HTTPRequest", string(responseBody)) env.Debug(string(responseBody))
return responseBody, nil return responseBody, nil
} }
func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) { func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
defer env.Trace(time.Now(), "HasParentFilePath", path) defer env.Trace(time.Now(), path)
currentFolder := env.Pwd() currentFolder := env.Pwd()
for { for {
fileSystem := os.DirFS(currentFolder) fileSystem := os.DirFS(currentFolder)
@ -662,13 +660,13 @@ func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
currentFolder = dir currentFolder = dir
continue continue
} }
env.Error("HasParentFilePath", err) env.Error(err)
return nil, errors.New("no match at root level") return nil, errors.New("no match at root level")
} }
} }
func (env *Shell) StackCount() int { func (env *Shell) StackCount() int {
defer env.Trace(time.Now(), "StackCount") defer env.Trace(time.Now())
if env.CmdFlags.StackCount < 0 { if env.CmdFlags.StackCount < 0 {
return 0 return 0
} }
@ -680,7 +678,7 @@ func (env *Shell) Cache() Cache {
} }
func (env *Shell) Close() { func (env *Shell) Close() {
defer env.Trace(time.Now(), "Close") defer env.Trace(time.Now())
templateCache, err := json.Marshal(env.TemplateCache()) templateCache, err := json.Marshal(env.TemplateCache())
if err == nil { if err == nil {
env.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440) env.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440)
@ -689,7 +687,7 @@ func (env *Shell) Close() {
} }
func (env *Shell) LoadTemplateCache() { func (env *Shell) LoadTemplateCache() {
defer env.Trace(time.Now(), "LoadTemplateCache") defer env.Trace(time.Now())
val, OK := env.fileCache.Get(TEMPLATECACHE) val, OK := env.fileCache.Get(TEMPLATECACHE)
if !OK { if !OK {
return return
@ -697,7 +695,7 @@ 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.Error("LoadTemplateCache", err) env.Error(err)
return return
} }
env.tmplCache = &templateCache env.tmplCache = &templateCache
@ -709,10 +707,8 @@ func (env *Shell) Logs() string {
func (env *Shell) TemplateCache() *TemplateCache { func (env *Shell) TemplateCache() *TemplateCache {
env.Lock() env.Lock()
defer func() { defer env.Trace(time.Now())
env.Trace(time.Now(), "TemplateCache") defer env.Unlock()
env.Unlock()
}()
if env.tmplCache != nil { if env.tmplCache != nil {
return env.tmplCache return env.tmplCache
} }
@ -761,7 +757,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 {
env.Error("DirMatchesOneOf", errors.New("panic")) env.Error(errors.New("panic"))
match = false match = false
} }
}() }()

View file

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

View file

@ -14,7 +14,7 @@ import (
) )
func (env *Shell) Root() bool { func (env *Shell) Root() bool {
defer env.Trace(time.Now(), "Root") defer env.Trace(time.Now())
return os.Geteuid() == 0 return os.Geteuid() == 0
} }
@ -27,7 +27,7 @@ func (env *Shell) QueryWindowTitles(processName, windowTitleRegex string) (strin
} }
func (env *Shell) IsWsl() bool { func (env *Shell) IsWsl() bool {
defer env.Trace(time.Now(), "IsWsl") defer env.Trace(time.Now())
// one way to check // one way to check
// version := env.FileContent("/proc/version") // version := env.FileContent("/proc/version")
// return strings.Contains(version, "microsoft") // return strings.Contains(version, "microsoft")
@ -36,7 +36,7 @@ func (env *Shell) IsWsl() bool {
} }
func (env *Shell) IsWsl2() bool { func (env *Shell) IsWsl2() bool {
defer env.Trace(time.Now(), "IsWsl2") defer env.Trace(time.Now())
if !env.IsWsl() { if !env.IsWsl() {
return false return false
} }
@ -45,13 +45,13 @@ func (env *Shell) IsWsl2() bool {
} }
func (env *Shell) TerminalWidth() (int, error) { func (env *Shell) TerminalWidth() (int, error) {
defer env.Trace(time.Now(), "TerminalWidth") defer env.Trace(time.Now())
if env.CmdFlags.TerminalWidth != 0 { if env.CmdFlags.TerminalWidth != 0 {
return env.CmdFlags.TerminalWidth, nil return env.CmdFlags.TerminalWidth, nil
} }
width, err := terminal.Width() width, err := terminal.Width()
if err != nil { if err != nil {
env.Error("TerminalWidth", err) env.Error(err)
} }
return int(width), err return int(width), err
} }
@ -77,12 +77,12 @@ func (env *Shell) Platform() string {
platform = "manjaro" platform = "manjaro"
} }
} }
env.Debug("Platform", platform) env.Debug(platform)
return platform return platform
} }
func (env *Shell) CachePath() string { func (env *Shell) CachePath() string {
defer env.Trace(time.Now(), "CachePath") defer env.Trace(time.Now())
// get XDG_CACHE_HOME if present // get XDG_CACHE_HOME if present
if cachePath := returnOrBuildCachePath(env.Getenv("XDG_CACHE_HOME")); len(cachePath) != 0 { if cachePath := returnOrBuildCachePath(env.Getenv("XDG_CACHE_HOME")); len(cachePath) != 0 {
return cachePath return cachePath
@ -126,7 +126,7 @@ func (env *Shell) LookWinAppPath(file string) (string, error) {
} }
func (env *Shell) DirIsWritable(path string) bool { func (env *Shell) DirIsWritable(path string) bool {
defer env.Trace(time.Now(), "DirIsWritable", path) defer env.Trace(time.Now(), path)
return unix.Access(path, unix.W_OK) == nil return unix.Access(path, unix.W_OK) == nil
} }

View file

@ -14,7 +14,7 @@ import (
) )
func (env *Shell) Root() bool { func (env *Shell) Root() bool {
defer env.Trace(time.Now(), "Root") defer env.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 +29,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.Error("Root", err) env.Error(err)
return false return false
} }
defer func() { defer func() {
@ -43,7 +43,7 @@ func (env *Shell) Root() bool {
member, err := token.IsMember(sid) member, err := token.IsMember(sid)
if err != nil { if err != nil {
env.Error("Root", err) env.Error(err)
return false return false
} }
@ -53,7 +53,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.Debug("Home", home) env.Debug(home)
}() }()
if len(home) > 0 { if len(home) > 0 {
return home return home
@ -67,37 +67,37 @@ func (env *Shell) Home() string {
} }
func (env *Shell) QueryWindowTitles(processName, windowTitleRegex string) (string, error) { func (env *Shell) QueryWindowTitles(processName, windowTitleRegex string) (string, error) {
defer env.Trace(time.Now(), "WindowTitle", windowTitleRegex) defer env.Trace(time.Now(), windowTitleRegex)
title, err := queryWindowTitles(processName, windowTitleRegex) title, err := queryWindowTitles(processName, windowTitleRegex)
if err != nil { if err != nil {
env.Error("QueryWindowTitles", err) env.Error(err)
} }
return title, err return title, err
} }
func (env *Shell) IsWsl() bool { func (env *Shell) IsWsl() bool {
defer env.Trace(time.Now(), "IsWsl") defer env.Trace(time.Now())
return false return false
} }
func (env *Shell) IsWsl2() bool { func (env *Shell) IsWsl2() bool {
defer env.Trace(time.Now(), "IsWsl2") defer env.Trace(time.Now())
return false return false
} }
func (env *Shell) TerminalWidth() (int, error) { func (env *Shell) TerminalWidth() (int, error) {
defer env.Trace(time.Now(), "TerminalWidth") defer env.Trace(time.Now())
if env.CmdFlags.TerminalWidth != 0 { if env.CmdFlags.TerminalWidth != 0 {
return env.CmdFlags.TerminalWidth, nil return env.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 {
env.Error("TerminalWidth", err) env.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 {
env.Error("TerminalWidth", err) env.Error(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
@ -109,7 +109,7 @@ func (env *Shell) Platform() string {
} }
func (env *Shell) CachePath() string { func (env *Shell) CachePath() string {
defer env.Trace(time.Now(), "CachePath") defer env.Trace(time.Now())
// get LOCALAPPDATA if present // get LOCALAPPDATA if present
if cachePath := returnOrBuildCachePath(env.Getenv("LOCALAPPDATA")); len(cachePath) != 0 { if cachePath := returnOrBuildCachePath(env.Getenv("LOCALAPPDATA")); len(cachePath) != 0 {
return cachePath return cachePath
@ -127,7 +127,7 @@ func (env *Shell) CachePath() 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 (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error) { func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error) {
env.Trace(time.Now(), "WindowsRegistryKeyValue", path) env.Trace(time.Now(), path)
// Format:sudo -u postgres psql // Format:sudo -u postgres psql
// "HKLM\Software\Microsoft\Windows NT\CurrentVersion\EditionID" // "HKLM\Software\Microsoft\Windows NT\CurrentVersion\EditionID"
@ -144,7 +144,7 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
rootKey, regPath, found := strings.Cut(path, `\`) rootKey, regPath, found := strings.Cut(path, `\`)
if !found { if !found {
err := fmt.Errorf("Error, malformed registry path: '%s'", path) err := fmt.Errorf("Error, malformed registry path: '%s'", path)
env.Error("WindowsRegistryKeyValue", err) env.Error(err)
return nil, err return nil, err
} }
@ -167,18 +167,18 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
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)
env.Error("WindowsRegistryKeyValue", err) env.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 {
env.Error("WindowsRegistryKeyValue", err) env.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 {
env.Error("WindowsRegistryKeyValue", err) env.Error(err)
return nil, err return nil, err
} }
@ -203,7 +203,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.Debug("WindowsRegistryKeyValue", fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String)) env.Debug(fmt.Sprintf("%s(%s): %s", regKey, regValue.ValueType, regValue.String))
return regValue, nil return regValue, nil
} }
@ -220,7 +220,7 @@ func (env *Shell) ConvertToLinuxPath(path string) string {
} }
func (env *Shell) DirIsWritable(path string) bool { func (env *Shell) DirIsWritable(path string) bool {
defer env.Trace(time.Now(), "DirIsWritable") defer env.Trace(time.Now())
return env.isWriteable(path) return env.isWriteable(path)
} }
@ -237,6 +237,6 @@ func (env *Shell) Connection(connectionType ConnectionType) (*Connection, error)
return network, nil return network, nil
} }
} }
env.Error("network", fmt.Errorf("Network type '%s' not found", connectionType)) env.Error(fmt.Errorf("Network type '%s' not found", connectionType))
return nil, &NotImplemented{} return nil, &NotImplemented{}
} }

View file

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

View file

@ -264,20 +264,20 @@ func (env *Shell) isWriteable(folder string) bool {
if err != nil { if err != nil {
// unable to get current user // unable to get current user
env.Error("isWriteable", err) env.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("isWriteable", err) env.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("isWriteable", "no dacl") env.Debug("no dacl")
return true return true
} }
@ -289,31 +289,31 @@ func (env *Shell) 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("isWriteable", "no ace found") env.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("isWriteable", "not current user or in group") env.Debug("not current user or in group")
continue continue
} }
env.Debug("isWriteable", fmt.Sprintf("current user is member of %s", aceSid.String())) env.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("isWriteable", "ACCESS_DENIED_ACE_TYPE") env.Debug("ACCESS_DENIED_ACE_TYPE")
return false return false
} }
env.debugF("isWriteable", func() string { return ace.AccessMask.permissions() }) env.debugF(func() string { return ace.AccessMask.permissions() })
if ace.AccessMask.canWrite() { if ace.AccessMask.canWrite() {
env.Debug("isWriteable", "user has write access") env.Debug("user has write access")
return true return true
} }
} }
env.Debug("isWriteable", "no write access") env.Debug("no write access")
return false return false
} }

View file

@ -36,7 +36,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("Gcp.Enabled()", err) g.env.Error(err)
return false return false
} }
@ -44,13 +44,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("Gcp.Enabled()", errors.New("config file is empty")) g.env.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("Gcp.Enabled()", err) g.env.Error(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("Error", "Gcp.Enabled()", mock2.Anything).Return() env.On("Error", mock2.Anything).Return()
g := &Gcp{ g := &Gcp{
env: env, env: env,
} }

View file

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

View file

@ -27,8 +27,8 @@ func renderTemplate(env *mock.MockedEnvironment, segmentTemplate string, context
Env: make(map[string]string), Env: make(map[string]string),
}) })
} }
env.On("Error", mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything) env.On("Debug", mock2.Anything)
tmpl := &template.Text{ tmpl := &template.Text{
Template: segmentTemplate, Template: segmentTemplate,
Context: context, Context: context,
@ -1294,8 +1294,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("Error", mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything) env.On("Debug", mock2.Anything)
path := &Path{ path := &Path{
env: env, env: env,
} }

View file

@ -127,7 +127,7 @@ func TestWTGetUrl(t *testing.T) {
for _, tc := range cases { for _, tc := range cases {
env := &mock.MockedEnvironment{} env := &mock.MockedEnvironment{}
env.On("Error", mock2.Anything, mock2.Anything) env.On("Error", 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

@ -25,8 +25,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("Error", mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything) env.On("Debug", mock2.Anything)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,

View file

@ -32,8 +32,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("Error", mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything)
env.On("Debug", mock2.Anything, mock2.Anything) env.On("Debug", mock2.Anything)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,

View file

@ -49,7 +49,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.Error("Render", err) t.Env.Error(err)
return "", errors.New(InvalidTemplate) return "", errors.New(InvalidTemplate)
} }
context := &Context{} context := &Context{}
@ -58,7 +58,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.Error("Render", err) t.Env.Error(err)
msg := regex.FindNamedRegexMatch(`at (?P<MSG><.*)$`, err.Error()) msg := regex.FindNamedRegexMatch(`at (?P<MSG><.*)$`, err.Error())
if len(msg) == 0 { if len(msg) == 0 {
return "", errors.New(IncorrectTemplate) return "", errors.New(IncorrectTemplate)

View file

@ -159,7 +159,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("Error", mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything)
for _, tc := range cases { for _, tc := range cases {
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,
@ -216,7 +216,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("Error", mock2.Anything, mock2.Anything) env.On("Error", mock2.Anything)
tmpl := &Text{ tmpl := &Text{
Template: tc.Template, Template: tc.Template,
Context: tc.Context, Context: tc.Context,