1package gui
2
3import (
4	"os"
5
6	"github.com/jesseduffield/gocui"
7)
8
9// when a user runs lazygit with the LAZYGIT_NEW_DIR_FILE env variable defined
10// we will write the current directory to that file on exit so that their
11// shell can then change to that directory. That means you don't get kicked
12// back to the directory that you started with.
13func (gui *Gui) recordCurrentDirectory() error {
14	if os.Getenv("LAZYGIT_NEW_DIR_FILE") == "" {
15		return nil
16	}
17
18	// determine current directory, set it in LAZYGIT_NEW_DIR_FILE
19	dirName, err := os.Getwd()
20	if err != nil {
21		return err
22	}
23
24	return gui.OSCommand.CreateFileWithContent(os.Getenv("LAZYGIT_NEW_DIR_FILE"), dirName)
25}
26
27func (gui *Gui) handleQuitWithoutChangingDirectory() error {
28	gui.State.RetainOriginalDir = true
29	return gui.quit()
30}
31
32func (gui *Gui) handleQuit() error {
33	gui.State.RetainOriginalDir = false
34	return gui.quit()
35}
36
37func (gui *Gui) handleTopLevelReturn() error {
38	currentContext := gui.currentContext()
39
40	parentContext, hasParent := currentContext.GetParentContext()
41	if hasParent && currentContext != nil && parentContext != nil {
42		// TODO: think about whether this should be marked as a return rather than adding to the stack
43		return gui.pushContext(parentContext)
44	}
45
46	for _, mode := range gui.modeStatuses() {
47		if mode.isActive() {
48			return mode.reset()
49		}
50	}
51
52	repoPathStack := gui.RepoPathStack
53	if len(repoPathStack) > 0 {
54		n := len(repoPathStack) - 1
55
56		path := repoPathStack[n]
57
58		gui.RepoPathStack = repoPathStack[:n]
59
60		return gui.dispatchSwitchToRepo(path, true)
61	}
62
63	if gui.Config.GetUserConfig().QuitOnTopLevelReturn {
64		return gui.handleQuit()
65	}
66
67	return nil
68}
69
70func (gui *Gui) quit() error {
71	if gui.State.Updating {
72		return gui.createUpdateQuitConfirmation()
73	}
74
75	if gui.Config.GetUserConfig().ConfirmOnQuit {
76		return gui.ask(askOpts{
77			title:  "",
78			prompt: gui.Tr.ConfirmQuit,
79			handleConfirm: func() error {
80				return gocui.ErrQuit
81			},
82		})
83	}
84
85	return gocui.ErrQuit
86}
87