2020-04-13 22:06:09 -04:00
|
|
|
package tmux
|
|
|
|
|
|
|
|
import (
|
2022-09-13 22:37:21 -04:00
|
|
|
"errors"
|
2020-04-13 22:06:09 -04:00
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
|
|
|
type Tmux struct {
|
|
|
|
BinPath string
|
|
|
|
Debug bool
|
|
|
|
}
|
|
|
|
|
|
|
|
func CreateTmux(debug bool) *Tmux {
|
|
|
|
return &Tmux{Debug: debug}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Tmux) Exec(args ...string) ([]byte, error) {
|
2022-09-13 22:37:21 -04:00
|
|
|
bin, err := t.getBinary()
|
|
|
|
if err != nil {
|
|
|
|
return []byte{}, err
|
|
|
|
}
|
2020-04-13 22:06:09 -04:00
|
|
|
if t.Debug {
|
|
|
|
fmt.Println(bin, strings.Join(args, " "))
|
|
|
|
}
|
|
|
|
return exec.Command(bin, args...).CombinedOutput()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Tmux) Run(args ...string) {
|
|
|
|
output, err := t.Exec(args...)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Println(err, string(output))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-13 22:37:21 -04:00
|
|
|
func (t *Tmux) Attach(name string) error {
|
2020-04-13 22:06:09 -04:00
|
|
|
args := []string{}
|
|
|
|
args = append(args, "-u", "attach-session", "-t", name)
|
|
|
|
|
2022-09-13 22:37:21 -04:00
|
|
|
bin, err := t.getBinary()
|
2020-04-13 22:06:09 -04:00
|
|
|
if err != nil {
|
2022-09-13 22:37:21 -04:00
|
|
|
return err
|
2020-04-13 22:06:09 -04:00
|
|
|
}
|
2022-09-13 22:37:21 -04:00
|
|
|
err = syscall.Exec(bin, args, os.Environ())
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
2020-04-13 22:06:09 -04:00
|
|
|
}
|
|
|
|
|
2022-09-13 22:37:21 -04:00
|
|
|
func (t *Tmux) ListSessions() ([]string, error) {
|
2021-12-01 22:14:34 -05:00
|
|
|
sessions := []string{}
|
|
|
|
result, err := t.Exec("ls", "-F", "#{session_name}")
|
2022-09-13 22:37:21 -04:00
|
|
|
if errors.Is(err, exec.ErrNotFound) {
|
2021-12-04 19:38:23 -05:00
|
|
|
// No active sessions returns as an error.
|
2022-09-13 22:37:21 -04:00
|
|
|
return sessions, err
|
2021-12-01 22:14:34 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
lines := strings.Trim(string(result), "\n")
|
2022-09-13 22:37:21 -04:00
|
|
|
return strings.Split(lines, "\n"), nil
|
2021-12-01 22:14:34 -05:00
|
|
|
}
|
|
|
|
|
2021-12-04 21:35:41 -05:00
|
|
|
func (t *Tmux) KillSession(name string) error {
|
|
|
|
_, err := t.Exec("kill-session", "-t", name)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2022-09-13 22:37:21 -04:00
|
|
|
func (t *Tmux) getBinary() (string, error) {
|
2020-04-13 22:06:09 -04:00
|
|
|
if t.BinPath != "" {
|
2022-09-13 22:37:21 -04:00
|
|
|
return t.BinPath, nil
|
2020-04-13 22:06:09 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
tmux, err := exec.LookPath("tmux")
|
|
|
|
if err != nil {
|
2022-09-13 22:37:21 -04:00
|
|
|
return "", err
|
2020-04-13 22:06:09 -04:00
|
|
|
}
|
|
|
|
|
2022-09-13 22:37:21 -04:00
|
|
|
return tmux, nil
|
2020-04-13 22:06:09 -04:00
|
|
|
}
|