summaryrefslogtreecommitdiffstats
path: root/pkg/gui/test_mode.go
blob: 9c6b5f30d73129141f0242141295941d44b46eda (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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package gui

import (
	"encoding/json"
	"log"
	"os"
	"strconv"
	"time"

	"github.com/jesseduffield/gocui"
	"github.com/jesseduffield/lazygit/pkg/integration/components"
	integrationTypes "github.com/jesseduffield/lazygit/pkg/integration/types"
	"github.com/jesseduffield/lazygit/pkg/utils"
)

type IntegrationTest interface {
	Run(guiAdapter *GuiDriver)
}

func (gui *Gui) handleTestMode(test integrationTypes.IntegrationTest) {
	if os.Getenv(components.SANDBOX_ENV_VAR) == "true" {
		return
	}

	if test != nil {
		go func() {
			time.Sleep(time.Millisecond * 100)

			test.Run(&GuiDriver{gui: gui})

			gui.g.Update(func(*gocui.Gui) error {
				return gocui.ErrQuit
			})

			time.Sleep(time.Second * 1)

			log.Fatal("gocui should have already exited")
		}()

		go utils.Safe(func() {
			time.Sleep(time.Second * 40)
			log.Fatal("40 seconds is up, lazygit recording took too long to complete")
		})
	}

	if Replaying() {
		gui.g.RecordingConfig = gocui.RecordingConfig{
			Speed:  GetRecordingSpeed(),
			Leeway: 1000,
		}

		var err error
		gui.g.Recording, err = LoadRecording()
		if err != nil {
			panic(err)
		}

		go utils.Safe(func() {
			time.Sleep(time.Second * 40)
			log.Fatal("40 seconds is up, lazygit recording took too long to complete")
		})
	}
}

func Headless() bool {
	return os.Getenv("HEADLESS") != ""
}

// OLD integration test format stuff

func Replaying() bool {
	return os.Getenv("REPLAY_EVENTS_FROM") != ""
}

func RecordingEvents() bool {
	return recordEventsTo() != ""
}

func recordEventsTo() string {
	return os.Getenv("RECORD_EVENTS_TO")
}

func GetRecordingSpeed() float64 {
	// humans are slow so this speeds things up.
	speed := 1.0
	envReplaySpeed := os.Getenv("SPEED")
	if envReplaySpeed != "" {
		var err error
		speed, err = strconv.ParseFloat(envReplaySpeed, 64)
		if err != nil {
			log.Fatal(err)
		}
	}
	return speed
}

func LoadRecording() (*gocui.Recording, error) {
	path := os.Getenv("REPLAY_EVENTS_FROM")

	data, err := os.ReadFile(path)
	if err != nil {
		return nil, err
	}

	recording := &gocui.Recording{}

	err = json.Unmarshal(data, &recording)
	if err != nil {
		return nil, err
	}

	return recording, nil
}

func SaveRecording(recording *gocui.Recording) error {
	if !RecordingEvents() {
		return nil
	}

	jsonEvents, err := json.Marshal(recording)
	if err != nil {
		return err
	}

	path := recordEventsTo()

	return os.WriteFile(path, jsonEvents, 0o600)
}