From aa9ef12d434bfdb4052e15c53fed48cbbb5ae25b Mon Sep 17 00:00:00 2001 From: Davyd McColl Date: Fri, 11 Jun 2021 17:01:22 +0200 Subject: [PATCH] :sparkles: make log-watching work on windows --- pkg/app/app.go | 72 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 61 insertions(+), 11 deletions(-) diff --git a/pkg/app/app.go b/pkg/app/app.go index a624a0d30..ad655aa33 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -4,15 +4,6 @@ import ( "bufio" "errors" "fmt" - "io" - "io/ioutil" - "log" - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "github.com/aybabtme/humanlog" "github.com/jesseduffield/lazygit/pkg/commands" "github.com/jesseduffield/lazygit/pkg/commands/oscommands" @@ -23,6 +14,15 @@ import ( "github.com/jesseduffield/lazygit/pkg/secureexec" "github.com/jesseduffield/lazygit/pkg/updates" "github.com/sirupsen/logrus" + "io" + "io/ioutil" + "log" + "os" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" ) // App struct @@ -318,6 +318,9 @@ func TailLogs() { fmt.Printf("Tailing log file %s\n\n", logFilePath) + opts := humanlog.DefaultOptions + opts.Truncates = false + _, err = os.Stat(logFilePath) if err != nil { if os.IsNotExist(err) { @@ -326,6 +329,11 @@ func TailLogs() { log.Fatal(err) } + if runtime.GOOS == "windows" { + TailLogsNative(logFilePath, opts) + return + } + cmd := secureexec.Command("tail", "-f", logFilePath) stdout, _ := cmd.StdoutPipe() @@ -333,8 +341,6 @@ func TailLogs() { log.Fatal(err) } - opts := humanlog.DefaultOptions - opts.Truncates = false if err := humanlog.Scanner(stdout, os.Stdout, opts); err != nil { log.Fatal(err) } @@ -345,3 +351,47 @@ func TailLogs() { os.Exit(0) } + +func TailLogsNative(logFilePath string, opts *humanlog.HandlerOptions) { + var lastModified int64 = 0 + var lastOffset int64 = 0 + for { + stat, err := os.Stat(logFilePath) + if err != nil { + log.Fatal(err) + } + if stat.ModTime().Unix() > lastModified { + err = TailFrom(lastOffset, logFilePath, opts) + if err != nil { + log.Fatal(err) + } + } + lastOffset = stat.Size() + } +} + +func TailFrom(lastOffset int64, logFilePath string, opts *humanlog.HandlerOptions) error { + file, err := os.Open(logFilePath) + if err != nil { + return err + } + file.Seek(lastOffset, 0) + fileScanner := bufio.NewScanner(file) + var lines []string + for fileScanner.Scan() { + lines = append(lines, fileScanner.Text()) + } + file.Close() + lineCount := len(lines) + lastTen := lines + if lineCount > 10 { + lastTen = lines[lineCount-10:] + } + for _, line := range lastTen { + reader := strings.NewReader(line) + if err := humanlog.Scanner(reader, os.Stdout, opts); err != nil { + log.Fatal(err) + } + } + return nil +}