tmux_popup/main.go

132 lines
2.9 KiB
Go

package main
import (
"bytes"
"fmt"
"log/slog"
"os"
"os/exec"
"strings"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Bitte geben Sie eine Aktion an: tmux, lazygit, harlequin, postings")
return
}
action := os.Args[1]
width := "80%"
height := "80%"
if len(os.Args) > 2 {
width = os.Args[2]
height = os.Args[2]
}
switch action {
case "tmux":
openPopup("popup", "", width, height)
case "lazygit":
openPopup("lazygit", "lazygit", width, height)
case "harlequin":
openPopup("harlequin", "harlequin", width, height)
case "postings":
openPopup("postings", "posting", width, height)
default:
CheckDependencies()
fmt.Println("Unbekannte Aktion")
}
}
func openPopup(sessionName, command string, width, height string) {
currentSession, err := exec.Command("tmux", "display-message", "-p", "-F", "#{session_name}").Output()
if err != nil {
fmt.Println("Fehler beim Abrufen der aktuellen Session:", err)
return
}
if strings.TrimSpace(string(currentSession)) == sessionName {
exec.Command("tmux", "detach-client").Run()
} else {
args := []string{"popup", "-d", "#{pane_current_path}", "-xC", "-yC", fmt.Sprintf("-w%s", width), fmt.Sprintf("-h%s", height), "-E"}
if command == "" {
args = append(args, fmt.Sprintf("tmux attach -t %s || tmux new -s %s", sessionName, sessionName))
} else {
args = append(args, fmt.Sprintf("tmux attach -t %s || tmux new -s %s '%s'", sessionName, sessionName, command))
}
exec.Command("tmux", args...).Run()
}
}
func CheckDependencies() error {
deps := []string{"lazygit", "harlequin", "posting"}
args := []string{"--version"}
os, err := platformInfo()
slog.Info("OS is: ", "os", os)
if err != nil {
slog.Error("error getting os infos: ", "err", err)
}
for _, dep := range deps {
if dep != "posting" {
err := runCmd(dep, args)
if err != nil {
return err
}
} else {
err := runCmd(dep, []string{"--help"})
if err != nil {
return err
}
}
}
return nil
}
func runCmd(dep string, args []string) error {
slog.Info("checking: ", "dep", dep)
cmd := exec.Command(dep, args...)
var stdo, stde bytes.Buffer
cmd.Stdout = &stdo
cmd.Stderr = &stde
cmd.Env = append(os.Environ(), "LANGUAGE=en")
err := cmd.Run()
if err != nil {
slog.Error(err.Error())
return err
}
return nil
}
func platformInfo() (string, error) {
_, err := os.Stat("/etc/os-release")
if os.IsNotExist(err) {
return "", fmt.Errorf("unable to read system information")
}
osRelease, _ := os.ReadFile("/etc/os-release")
return parseOsRelease(string(osRelease)), nil
}
func parseOsRelease(osRelease string) string {
var result string
lines := strings.Split(osRelease, "\n")
for _, line := range lines {
splitLine := strings.SplitN(line, "=", 2)
if len(splitLine) != 2 {
continue
}
switch splitLine[0] {
case "ID":
case "NAME":
result = strings.Trim(splitLine[1], "\"")
case "VERSION_ID":
}
}
return result
}