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 {
defer env.Trace(time.Now(), "config.loadConfig")
defer env.Trace(time.Now())
configFile := env.Flags().Config
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
func (e *Engine) PrintDebug(startTime time.Time, version string) string {
var segmentTimings []*SegmentTiming
largestSegmentNameLength := 0
e.write(fmt.Sprintf("\n\x1b[1mVersion:\x1b[0m %s\n", version))
e.write("\n\x1b[1mSegments:\x1b[0m\n\n")
e.write(fmt.Sprintf("\n\x1b[38;2;191;207;240m\x1b[1mVersion:\x1b[0m %s\n", version))
e.write("\n\x1b[38;2;191;207;240m\x1b[1mSegments:\x1b[0m\n\n")
// console title timing
titleStartTime := time.Now()
title := e.getTitleTemplateText()
@ -234,6 +233,7 @@ func (e *Engine) PrintDebug(startTime time.Time, version string) string {
text: title,
duration: time.Since(titleStartTime),
}
largestSegmentNameLength := 12
segmentTimings = append(segmentTimings, segmentTiming)
// cache a pointer to the color 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)
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[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("\n\x1b[1mLogs:\x1b[0m\n\n")
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[38;2;191;207;240m\x1b[1mCache path:\x1b[0m %s\n", e.Env.CachePath()))
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[38;2;191;207;240m\x1b[1mLogs:\x1b[0m\n\n")
e.write(e.Env.Logs())
return e.string()
}

View file

@ -161,7 +161,7 @@ func TestOauthResult(t *testing.T) {
env.On("Cache").Return(cache)
env.On("HTTPRequest", url).Return([]byte(tc.JSONResponse), 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{
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 {
err := json.Unmarshal([]byte(val), &data)
if err != nil {
r.env.Error("OAuth", err)
r.env.Error(err)
return data, err
}
return data, nil
}
err := errors.New("no data in cache")
r.env.Error("OAuth", err)
r.env.Error(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...)
if err != nil {
r.env.Error("OAuth", err)
r.env.Error(err)
return data, err
}
err = json.Unmarshal(responseBody, &data)
if err != nil {
r.env.Error("OAuth", err)
r.env.Error(err)
return data, err
}

View file

@ -75,7 +75,7 @@ func TestRequestResult(t *testing.T) {
env.On("Cache").Return(cache)
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.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 (
"fmt"
"log"
"path/filepath"
"runtime"
"strings"
"time"
)
var enabled bool
var logBuilder strings.Builder
var log strings.Builder
func Enable() {
enabled = true
log.SetOutput(&logBuilder)
}
func Info(message string) {
if !enabled {
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 {
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)
fn, _ := funcSpec()
header := fmt.Sprintf("%s(%s) - \x1b[38;2;156;231;201m%s\033[0m", fn, strings.Join(args, " "), elapsed)
printLn(trace, header)
}
func Debug(funcName, message string) {
func Debug(message string) {
if !enabled {
return
}
trace := entry(fmt.Sprintf("%s\n%s", funcName, message))
trace.Format(Yellow)
log.Println(trace)
fn, line := funcSpec()
header := fmt.Sprintf("%s:%d", fn, line)
printLn(debug, header, message)
}
func DebugF(function string, fn func() string) {
func DebugF(fn func() string) {
if !enabled {
return
}
trace := entry(fmt.Sprintf("%s\n%s", function, fn()))
trace.Format(Yellow)
log.Println(trace)
fn2, line := funcSpec()
header := fmt.Sprintf("%s:%d", fn2, line)
printLn(debug, header, fn())
}
func Error(funcName string, err error) {
func Error(err error) {
if !enabled {
return
}
trace := entry(fmt.Sprintf("%s\n%s", funcName, err.Error()))
trace.Format(Red)
log.Println(trace)
fn, line := funcSpec()
header := fmt.Sprintf("%s:%d", fn, line)
printLn(bug, header, err.Error())
}
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)
}
func (env *MockedEnvironment) Trace(start time.Time, function string, args ...string) {
_ = env.Called(start, function, args)
func (env *MockedEnvironment) Trace(start time.Time, args ...string) {
_ = env.Called(start, args)
}
func (env *MockedEnvironment) Debug(funcName, message string) {
_ = env.Called(funcName, message)
func (env *MockedEnvironment) Debug(message string) {
_ = env.Called(message)
}
func (env *MockedEnvironment) Error(funcName string, err error) {
_ = env.Called(funcName, err)
func (env *MockedEnvironment) Error(err error) {
_ = env.Called(err)
}
func (env *MockedEnvironment) DirIsWritable(path string) bool {

View file

@ -200,7 +200,7 @@ func (env *Shell) getConnections() []*Connection {
}
func (env *Shell) wifiNetwork() (*Connection, error) {
env.Trace(time.Now(), "wifiNetwork")
env.Trace(time.Now())
// Open handle
var pdwNegotiatedVersion uint32
var phClientHandle uint32
@ -250,7 +250,7 @@ func (env *Shell) parseNetworkInterface(network *WLAN_INTERFACE_INFO, clientHand
uintptr(unsafe.Pointer(&wlanAttr)),
uintptr(unsafe.Pointer(nil)))
if e != 0 {
env.Error("parseNetworkInterface", err)
env.Error(err)
return &info, err
}

View file

@ -205,9 +205,9 @@ type Environment interface {
Connection(connectionType ConnectionType) (*Connection, error)
TemplateCache() *TemplateCache
LoadTemplateCache()
Debug(funcName, message string)
Error(funcName string, err error)
Trace(start time.Time, function string, args ...string)
Debug(message string)
Error(err error)
Trace(start time.Time, args ...string)
}
type commandCache struct {
@ -241,7 +241,7 @@ type Shell struct {
}
func (env *Shell) Init() {
defer env.Trace(time.Now(), "Init")
defer env.Trace(time.Now())
if env.CmdFlags == nil {
env.CmdFlags = &Flags{}
}
@ -257,7 +257,7 @@ func (env *Shell) Init() {
}
func (env *Shell) resolveConfigPath() {
defer env.Trace(time.Now(), "resolveConfigPath")
defer env.Trace(time.Now())
if len(env.CmdFlags.Config) == 0 {
env.CmdFlags.Config = env.Getenv("POSH_THEME")
}
@ -288,7 +288,7 @@ func (env *Shell) resolveConfigPath() {
}
func (env *Shell) downloadConfig(location string) error {
defer env.Trace(time.Now(), "downloadConfig", location)
defer env.Trace(time.Now(), location)
ext := filepath.Ext(location)
configPath := filepath.Join(env.CachePath(), "config.omp"+ext)
cfg, err := env.HTTPRequest(location, nil, 5000)
@ -308,34 +308,32 @@ func (env *Shell) downloadConfig(location string) error {
return nil
}
func (env *Shell) Trace(start time.Time, function string, args ...string) {
log.Trace(start, function, args...)
func (env *Shell) Trace(start time.Time, args ...string) {
log.Trace(start, args...)
}
func (env *Shell) Debug(funcName, message string) {
log.Debug(funcName, message)
func (env *Shell) Debug(message string) {
log.Debug(message)
}
func (env *Shell) Error(funcName string, err error) {
log.Error(funcName, err)
func (env *Shell) Error(err error) {
log.Error(err)
}
func (env *Shell) debugF(function string, fn func() string) {
log.DebugF(function, fn)
func (env *Shell) debugF(fn func() string) {
log.DebugF(fn)
}
func (env *Shell) Getenv(key string) string {
defer env.Trace(time.Now(), "Getenv", key)
defer env.Trace(time.Now(), key)
val := os.Getenv(key)
env.Debug("Getenv", val)
env.Debug(val)
return val
}
func (env *Shell) Pwd() string {
defer env.Trace(time.Now(), "Pwd")
defer func() {
env.Debug("Pwd", env.cwd)
}()
defer env.Trace(time.Now())
defer env.Debug(env.cwd)
if env.cwd != "" {
return env.cwd
}
@ -353,7 +351,7 @@ func (env *Shell) Pwd() string {
}
dir, err := os.Getwd()
if err != nil {
env.Error("Pwd", err)
env.Error(err)
return ""
}
env.cwd = correctPath(dir)
@ -361,12 +359,12 @@ func (env *Shell) Pwd() string {
}
func (env *Shell) HasFiles(pattern string) bool {
defer env.Trace(time.Now(), "HasFiles", pattern)
defer env.Trace(time.Now(), pattern)
cwd := env.Pwd()
fileSystem := os.DirFS(cwd)
matches, err := fs.Glob(fileSystem, pattern)
if err != nil {
env.Error("HasFiles", err)
env.Error(err)
return false
}
for _, match := range matches {
@ -380,84 +378,84 @@ func (env *Shell) HasFiles(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)
matches, err := fs.Glob(fileSystem, pattern)
if err != nil {
env.Error("HasFilesInDir", err)
env.Error(err)
return false
}
hasFilesInDir := len(matches) > 0
env.debugF("HasFilesInDir", func() string { return strconv.FormatBool(hasFilesInDir) })
env.debugF(func() string { return strconv.FormatBool(hasFilesInDir) })
return hasFilesInDir
}
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()
for c := 0; c < int(depth); c++ {
if env.HasFilesInDir(currentFolder, pattern) {
env.Debug("HasFileInParentDirs", "true")
env.Debug("true")
return true
}
if dir := filepath.Dir(currentFolder); dir != currentFolder {
currentFolder = dir
} else {
env.Debug("HasFileInParentDirs", "false")
env.Debug("false")
return false
}
}
env.Debug("HasFileInParentDirs", "false")
env.Debug("false")
return false
}
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)
if err != nil {
env.Debug("HasFolder", "false")
env.Debug("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()
}
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)
if err != nil {
env.Error("ResolveSymlink", err)
env.Error(err)
return "", err
}
env.Debug("ResolveSymlink", link)
env.Debug(link)
return link, nil
}
func (env *Shell) FileContent(file string) string {
defer env.Trace(time.Now(), "FileContent", file)
defer env.Trace(time.Now(), file)
if !filepath.IsAbs(file) {
file = filepath.Join(env.Pwd(), file)
}
content, err := os.ReadFile(file)
if err != nil {
env.Error("FileContent", err)
env.Error(err)
return ""
}
fileContent := string(content)
env.Debug("FileContent", fileContent)
env.Debug(fileContent)
return fileContent
}
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)
if err != nil {
env.Error("LsDir", err)
env.Error(err)
return nil
}
env.debugF("LsDir", func() string {
env.debugF(func() string {
var entriesStr string
for _, entry := range entries {
entriesStr += entry.Name() + "\n"
@ -468,52 +466,52 @@ func (env *Shell) LsDir(path string) []fs.DirEntry {
}
func (env *Shell) PathSeparator() string {
defer env.Trace(time.Now(), "PathSeparator")
defer env.Trace(time.Now())
return string(os.PathSeparator)
}
func (env *Shell) User() string {
defer env.Trace(time.Now(), "User")
defer env.Trace(time.Now())
user := os.Getenv("USER")
if user == "" {
user = os.Getenv("USERNAME")
}
env.Debug("User", user)
env.Debug(user)
return user
}
func (env *Shell) Host() (string, error) {
defer env.Trace(time.Now(), "Host")
defer env.Trace(time.Now())
hostName, err := os.Hostname()
if err != nil {
env.Error("Host", err)
env.Error(err)
return "", err
}
hostName = cleanHostName(hostName)
env.Debug("Host", hostName)
env.Debug(hostName)
return hostName, nil
}
func (env *Shell) GOOS() string {
defer env.Trace(time.Now(), "GOOS")
defer env.Trace(time.Now())
return runtime.GOOS
}
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 {
command = cacheCommand
}
output, err := cmd.Run(command, args...)
if err != nil {
env.Error("RunCommand", err)
env.Error(err)
}
env.Debug("RunCommand", output)
env.Debug(output)
return output, err
}
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 {
return out
}
@ -521,23 +519,23 @@ func (env *Shell) RunShellCommand(shell, 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 {
env.Debug("CommandPath", path)
env.Debug(path)
return path
}
path, err := exec.LookPath(command)
if err == nil {
env.cmdCache.set(command, path)
env.Debug("CommandPath", path)
env.Debug(path)
return path
}
env.Error("CommandPath", err)
env.Error(err)
return ""
}
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 != "" {
return true
}
@ -545,12 +543,12 @@ func (env *Shell) HasCommand(command string) bool {
}
func (env *Shell) ErrorCode() int {
defer env.Trace(time.Now(), "ErrorCode")
defer env.Trace(time.Now())
return env.CmdFlags.ErrorCode
}
func (env *Shell) ExecutionTime() float64 {
defer env.Trace(time.Now(), "ExecutionTime")
defer env.Trace(time.Now())
if env.CmdFlags.ExecutionTime < 0 {
return 0
}
@ -558,12 +556,12 @@ func (env *Shell) ExecutionTime() float64 {
}
func (env *Shell) Flags() *Flags {
defer env.Trace(time.Now(), "Flags")
defer env.Trace(time.Now())
return env.CmdFlags
}
func (env *Shell) Shell() string {
defer env.Trace(time.Now(), "Shell")
defer env.Trace(time.Now())
if env.CmdFlags.Shell != "" {
return env.CmdFlags.Shell
}
@ -571,20 +569,20 @@ func (env *Shell) Shell() string {
p, _ := process.NewProcess(int32(pid))
name, err := p.Name()
if err != nil {
env.Error("Shell", err)
env.Error(err)
return UNKNOWN
}
env.Debug("Shell", "process name: "+name)
env.Debug("process name: " + name)
// this is used for when scoop creates a shim, see
// https://github.com/jandedobbeleer/oh-my-posh/issues/2806
executable, _ := os.Executable()
if name == "cmd.exe" || name == executable {
p, _ = p.Parent()
name, err = p.Name()
env.Debug("Shell", "parent process name: "+name)
env.Debug("parent process name: " + name)
}
if err != nil {
env.Error("Shell", err)
env.Error(err)
return UNKNOWN
}
// 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) {
defer env.Trace(time.Now(), "HTTPRequest", targetURL)
defer env.Trace(time.Now(), targetURL)
ctx, cncl := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
defer cncl()
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 {
dump, _ := httputil.DumpRequestOut(request, true)
env.Debug("HTTPRequest", string(dump))
env.Debug(string(dump))
}
response, err := client.Do(request)
if err != nil {
env.Error("HTTPRequest", err)
env.Error(err)
return nil, env.unWrapError(err)
}
// anything inside the range [200, 299] is considered a success
if response.StatusCode < 200 || response.StatusCode >= 300 {
message := "HTTP status code " + strconv.Itoa(response.StatusCode)
err := errors.New(message)
env.Error("HTTPRequest", err)
env.Error(err)
return nil, err
}
defer response.Body.Close()
responseBody, err := io.ReadAll(response.Body)
if err != nil {
env.Error("HTTPRequest", err)
env.Error(err)
return nil, err
}
env.Debug("HTTPRequest", string(responseBody))
env.Debug(string(responseBody))
return responseBody, nil
}
func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
defer env.Trace(time.Now(), "HasParentFilePath", path)
defer env.Trace(time.Now(), path)
currentFolder := env.Pwd()
for {
fileSystem := os.DirFS(currentFolder)
@ -662,13 +660,13 @@ func (env *Shell) HasParentFilePath(path string) (*FileInfo, error) {
currentFolder = dir
continue
}
env.Error("HasParentFilePath", err)
env.Error(err)
return nil, errors.New("no match at root level")
}
}
func (env *Shell) StackCount() int {
defer env.Trace(time.Now(), "StackCount")
defer env.Trace(time.Now())
if env.CmdFlags.StackCount < 0 {
return 0
}
@ -680,7 +678,7 @@ func (env *Shell) Cache() Cache {
}
func (env *Shell) Close() {
defer env.Trace(time.Now(), "Close")
defer env.Trace(time.Now())
templateCache, err := json.Marshal(env.TemplateCache())
if err == nil {
env.fileCache.Set(TEMPLATECACHE, string(templateCache), 1440)
@ -689,7 +687,7 @@ func (env *Shell) Close() {
}
func (env *Shell) LoadTemplateCache() {
defer env.Trace(time.Now(), "LoadTemplateCache")
defer env.Trace(time.Now())
val, OK := env.fileCache.Get(TEMPLATECACHE)
if !OK {
return
@ -697,7 +695,7 @@ func (env *Shell) LoadTemplateCache() {
var templateCache TemplateCache
err := json.Unmarshal([]byte(val), &templateCache)
if err != nil {
env.Error("LoadTemplateCache", err)
env.Error(err)
return
}
env.tmplCache = &templateCache
@ -709,10 +707,8 @@ func (env *Shell) Logs() string {
func (env *Shell) TemplateCache() *TemplateCache {
env.Lock()
defer func() {
env.Trace(time.Now(), "TemplateCache")
env.Unlock()
}()
defer env.Trace(time.Now())
defer env.Unlock()
if env.tmplCache != nil {
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
defer func() {
if err := recover(); err != nil {
env.Error("DirMatchesOneOf", errors.New("panic"))
env.Error(errors.New("panic"))
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)
if len(matches) != 2 {
err := errors.New("Unable to find battery state based on output")
env.Error("BatteryState", err)
env.Error(err)
return nil, err
}
var percentage int
var err error
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 &battery.Info{
@ -50,10 +50,10 @@ func (env *Shell) parseBatteryOutput(output string) (*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")
if err != nil {
env.Error("BatteryState", err)
env.Error(err)
return nil, err
}
if !strings.Contains(output, "Battery") {

View file

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

View file

@ -14,7 +14,7 @@ import (
)
func (env *Shell) Root() bool {
defer env.Trace(time.Now(), "Root")
defer env.Trace(time.Now())
var sid *windows.SID
// 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,
&sid)
if err != nil {
env.Error("Root", err)
env.Error(err)
return false
}
defer func() {
@ -43,7 +43,7 @@ func (env *Shell) Root() bool {
member, err := token.IsMember(sid)
if err != nil {
env.Error("Root", err)
env.Error(err)
return false
}
@ -53,7 +53,7 @@ func (env *Shell) Root() bool {
func (env *Shell) Home() string {
home := os.Getenv("HOME")
defer func() {
env.Debug("Home", home)
env.Debug(home)
}()
if len(home) > 0 {
return home
@ -67,37 +67,37 @@ func (env *Shell) Home() string {
}
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)
if err != nil {
env.Error("QueryWindowTitles", err)
env.Error(err)
}
return title, err
}
func (env *Shell) IsWsl() bool {
defer env.Trace(time.Now(), "IsWsl")
defer env.Trace(time.Now())
return false
}
func (env *Shell) IsWsl2() bool {
defer env.Trace(time.Now(), "IsWsl2")
defer env.Trace(time.Now())
return false
}
func (env *Shell) TerminalWidth() (int, error) {
defer env.Trace(time.Now(), "TerminalWidth")
defer env.Trace(time.Now())
if env.CmdFlags.TerminalWidth != 0 {
return env.CmdFlags.TerminalWidth, nil
}
handle, err := syscall.Open("CONOUT$", syscall.O_RDWR, 0)
if err != nil {
env.Error("TerminalWidth", err)
env.Error(err)
return 0, err
}
info, err := winterm.GetConsoleScreenBufferInfo(uintptr(handle))
if err != nil {
env.Error("TerminalWidth", err)
env.Error(err)
return 0, err
}
// return int(float64(info.Size.X) * 0.57), nil
@ -109,7 +109,7 @@ func (env *Shell) Platform() string {
}
func (env *Shell) CachePath() string {
defer env.Trace(time.Now(), "CachePath")
defer env.Trace(time.Now())
// get LOCALAPPDATA if present
if cachePath := returnOrBuildCachePath(env.Getenv("LOCALAPPDATA")); len(cachePath) != 0 {
return cachePath
@ -127,7 +127,7 @@ func (env *Shell) CachePath() string {
//
// Returns a variant type if successful; nil and an error if not.
func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, error) {
env.Trace(time.Now(), "WindowsRegistryKeyValue", path)
env.Trace(time.Now(), path)
// Format:sudo -u postgres psql
// "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, `\`)
if !found {
err := fmt.Errorf("Error, malformed registry path: '%s'", path)
env.Error("WindowsRegistryKeyValue", err)
env.Error(err)
return nil, err
}
@ -167,18 +167,18 @@ func (env *Shell) WindowsRegistryKeyValue(path string) (*WindowsRegistryValue, e
key = windows.HKEY_USERS
default:
err := fmt.Errorf("Error, unknown registry key: '%s", rootKey)
env.Error("WindowsRegistryKeyValue", err)
env.Error(err)
return nil, err
}
k, err := registry.OpenKey(key, regPath, registry.READ)
if err != nil {
env.Error("WindowsRegistryKeyValue", err)
env.Error(err)
return nil, err
}
_, valType, err := k.GetValue(regKey, nil)
if err != nil {
env.Error("WindowsRegistryKeyValue", err)
env.Error(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)
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
}
@ -220,7 +220,7 @@ func (env *Shell) ConvertToLinuxPath(path string) string {
}
func (env *Shell) DirIsWritable(path string) bool {
defer env.Trace(time.Now(), "DirIsWritable")
defer env.Trace(time.Now())
return env.isWriteable(path)
}
@ -237,6 +237,6 @@ func (env *Shell) Connection(connectionType ConnectionType) (*Connection, error)
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{}
}

View file

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

View file

@ -264,20 +264,20 @@ func (env *Shell) isWriteable(folder string) bool {
if err != nil {
// unable to get current user
env.Error("isWriteable", err)
env.Error(err)
return false
}
si, err := windows.GetNamedSecurityInfo(folder, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)
if err != nil {
env.Error("isWriteable", err)
env.Error(err)
return false
}
dacl, _, err := si.DACL()
if err != nil || dacl == nil {
// no dacl implies full access
env.Debug("isWriteable", "no dacl")
env.Debug("no dacl")
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)))
if ret == 0 {
env.Debug("isWriteable", "no ace found")
env.Debug("no ace found")
return false
}
aceSid := (*windows.SID)(unsafe.Pointer(&ace.SidStart))
if !cu.isMemberOf(aceSid) {
env.Debug("isWriteable", "not current user or in group")
env.Debug("not current user or in group")
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
if ace.AceType == ACCESS_DENIED_ACE_TYPE {
env.Debug("isWriteable", "ACCESS_DENIED_ACE_TYPE")
env.Debug("ACCESS_DENIED_ACE_TYPE")
return false
}
env.debugF("isWriteable", func() string { return ace.AccessMask.permissions() })
env.debugF(func() string { return ace.AccessMask.permissions() })
if ace.AccessMask.canWrite() {
env.Debug("isWriteable", "user has write access")
env.Debug("user has write access")
return true
}
}
env.Debug("isWriteable", "no write access")
env.Debug("no write access")
return false
}

View file

@ -36,7 +36,7 @@ func (g *Gcp) Enabled() bool {
cfgDir := g.getConfigDirectory()
configFile, err := g.getActiveConfig(cfgDir)
if err != nil {
g.env.Error("Gcp.Enabled()", err)
g.env.Error(err)
return false
}
@ -44,13 +44,13 @@ func (g *Gcp) Enabled() bool {
cfg := g.env.FileContent(cfgpath)
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
}
data, err := ini.Load([]byte(cfg))
if err != nil {
g.env.Error("Gcp.Enabled()", err)
g.env.Error(err)
return false
}

View file

@ -57,7 +57,7 @@ func TestGcpSegment(t *testing.T) {
env.On("FileContent", fcPath).Return(tc.ActiveConfig)
cfgpath := path.Join("config", "configurations", "config_production")
env.On("FileContent", cfgpath).Return(tc.CfgData)
env.On("Error", "Gcp.Enabled()", mock2.Anything).Return()
env.On("Error", mock2.Anything).Return()
g := &Gcp{
env: env,
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -49,7 +49,7 @@ func (t *Text) Render() (string, error) {
t.cleanTemplate()
tmpl, err := template.New(t.Template).Funcs(funcMap()).Parse(t.Template)
if err != nil {
t.Env.Error("Render", err)
t.Env.Error(err)
return "", errors.New(InvalidTemplate)
}
context := &Context{}
@ -58,7 +58,7 @@ func (t *Text) Render() (string, error) {
defer buffer.Reset()
err = tmpl.Execute(buffer, context)
if err != nil {
t.Env.Error("Render", err)
t.Env.Error(err)
msg := regex.FindNamedRegexMatch(`at (?P<MSG><.*)$`, err.Error())
if len(msg) == 0 {
return "", errors.New(IncorrectTemplate)

View file

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