summaryrefslogtreecommitdiffstats
path: root/pkg/app/logging_windows.go
blob: 8c3e937a1749f688789bc53d669e584a42e6622c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// +build windows

package app

import (
	"bufio"
	"fmt"
	"github.com/aybabtme/humanlog"
	"github.com/jesseduffield/lazygit/pkg/config"
	"log"
	"os"
	"strings"
	"time"
)

func TailLogs() {
	logFilePath, err := config.LogPath()
	if err != nil {
		log.Fatal(err)
	}

	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) {
			log.Fatal("Log file does not exist. Run `lazygit --debug` first to create the log file")
		}
		log.Fatal(err)
	}

	TailLogsNative(logFilePath, opts)
}

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()
		time.Sleep(1 * time.Second)
	}
}

func OpenAndSeek(filepath string, offset int64) (*os.File, error) {
	file, err := os.Open(filepath)
	if err != nil {
		return nil, err
	}

	_, err = file.Seek(offset, 0)
	if err != nil {
		_ = file.Close()
		return nil, err
	}
	return file, nil
}

func TailFrom(lastOffset int64, logFilePath string, opts *humanlog.HandlerOptions) error {
	file, err := OpenAndSeek(logFilePath, lastOffset)
	if err != nil {
		return err
	}

	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
}