aboutsummaryrefslogtreecommitdiffstats
path: root/commands/term.go
blob: e8b1919dd1cbe6e19329b1465db664d599adfb98 (plain) (blame)
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
package commands

import (
	"os"
	"os/exec"

	"github.com/riywo/loginshell"

	"git.sr.ht/~rjarry/aerc/app"
	"git.sr.ht/~rjarry/aerc/lib/ui"
)

type Term struct {
	Cmd []string `opt:"..." required:"false"`
}

func init() {
	Register(Term{})
}

func (Term) Context() CommandContext {
	return GLOBAL
}

func (Term) Aliases() []string {
	return []string{"terminal", "term"}
}

func (t Term) Execute(args []string) error {
	return TermCore(t.Cmd)
}

// The help command is an alias for `term man` thus Term requires a simple func
func TermCore(args []string) error {
	return TermCoreDirectory(args, "")
}

func TermCoreDirectory(args []string, dir string) error {
	if len(args) == 0 {
		shell, err := loginshell.Shell()
		if err != nil {
			return err
		}
		args = []string{shell}
	}

	if dir != "" {
		if _, err := os.Stat(dir); os.IsNotExist(err) {
			return err
		}
	}

	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = dir
	term, err := app.NewTerminal(cmd)
	if err != nil {
		return err
	}
	tab := app.NewTab(term, args[0])
	term.OnTitle = func(title string) {
		if title == "" {
			title = args[0]
		}
		if tab.Name != title {
			tab.Name = title
			ui.Invalidate()
		}
	}
	term.OnClose = func(err error) {
		app.RemoveTab(term, false)
		if err != nil {
			app.PushError(err.Error())
		}
	}
	return nil
}