refactor: change from args to usage of cobra

This commit is contained in:
Patryk Hegenberg 2024-12-25 08:09:41 +01:00
parent 03941d0d41
commit e17e071443
3 changed files with 92 additions and 91 deletions

7
go.mod
View file

@ -1,3 +1,10 @@
module tmux_popup
go 1.23.4
require github.com/spf13/cobra v1.8.1
require (
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
)

10
go.sum Normal file
View file

@ -0,0 +1,10 @@
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

166
main.go
View file

@ -1,67 +1,96 @@
package main
import (
"bytes"
"fmt"
"log/slog"
"os"
"os/exec"
"strings"
"github.com/spf13/cobra"
)
type Config struct {
DefaultWidth string
DefaultHeight string
ArgsVersion []string
}
var config = Config{
DefaultWidth: "80%",
DefaultHeight: "80%",
ArgsVersion: []string{"--version"},
}
func main() {
if len(os.Args) < 2 {
fmt.Println("Bitte geben Sie eine Aktion an: tmux, lazygit, harlequin, postings")
return
var rootCmd = &cobra.Command{
Use: "tmux_popup",
Short: "Ein CLI-Tool für verschiedene Aktionen",
Long: "tmux_popup ist ein CLI-Werkzeug, das verschiedene Aktionen wie tmux, lazygit, harlequin und postings unterstützt. Es oeffnet diese Programme in einem floating tmux pane",
}
action := os.Args[1]
width := config.DefaultWidth
height := config.DefaultHeight
rootCmd.PersistentFlags().String("width", "80%", "Breite des Popups (z. B. 80%)")
rootCmd.PersistentFlags().String("height", "80%", "Höhe des Popups (z. B. 80%)")
if len(os.Args) > 3 {
width = os.Args[2]
height = os.Args[3]
rootCmd.AddCommand(tmuxCmd)
rootCmd.AddCommand(lazygitCmd)
rootCmd.AddCommand(harlequinCmd)
rootCmd.AddCommand(postingsCmd)
rootCmd.AddCommand(checkCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println("Fehler:", err)
os.Exit(1)
}
}
switch action {
case "tmux":
var tmuxCmd = &cobra.Command{
Use: "tmux",
Short: "Öffnet ein tmux-Popup",
Run: func(cmd *cobra.Command, args []string) {
width, _ := cmd.Flags().GetString("width")
height, _ := cmd.Flags().GetString("height")
openPopup("popup", "", width, height)
case "lazygit":
},
}
var lazygitCmd = &cobra.Command{
Use: "lazygit",
Short: "Öffnet lazygit in einem Popup",
Run: func(cmd *cobra.Command, args []string) {
width, _ := cmd.Flags().GetString("width")
height, _ := cmd.Flags().GetString("height")
openPopup("lazygit", "lazygit", width, height)
case "harlequin":
},
}
var harlequinCmd = &cobra.Command{
Use: "harlequin",
Short: "Öffnet harlequin in einem Popup",
Run: func(cmd *cobra.Command, args []string) {
width, _ := cmd.Flags().GetString("width")
height, _ := cmd.Flags().GetString("height")
openPopup("harlequin", "harlequin", width, height)
case "postings":
},
}
var postingsCmd = &cobra.Command{
Use: "postings",
Short: "Öffnet postings in einem Popup",
Run: func(cmd *cobra.Command, args []string) {
width, _ := cmd.Flags().GetString("width")
height, _ := cmd.Flags().GetString("height")
openPopup("postings", "posting", width, height)
default:
},
}
var checkCmd = &cobra.Command{
Use: "check",
Short: "Prüft die Abhängigkeiten",
Run: func(cmd *cobra.Command, args []string) {
if err := CheckDependencies(); err != nil {
fmt.Println("Fehler bei der Überprüfung der Abhängigkeiten:", err)
} else {
fmt.Println("Unbekannte Aktion")
os.Exit(1)
}
}
fmt.Println("Alle Abhängigkeiten sind vorhanden.")
},
}
func openPopup(sessionName, command, width, height string) {
isCurrent, err := isCurrentSession(sessionName)
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 isCurrent {
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"}
@ -70,77 +99,32 @@ func openPopup(sessionName, command, width, height string) {
} else {
args = append(args, fmt.Sprintf("tmux attach -t %s || tmux new -s %s '%s'", sessionName, sessionName, command))
}
if err := exec.Command("tmux", args...).Run(); err != nil {
slog.Error("Failed to execute tmux command", "error", err)
}
exec.Command("tmux", args...).Run()
}
}
func isCurrentSession(sessionName string) (bool, error) {
currentSession, err := exec.Command("tmux", "display-message", "-p", "-F", "#{session_name}").Output()
if err != nil {
return false, err
}
return strings.TrimSpace(string(currentSession)) == sessionName, nil
}
func CheckDependencies() error {
deps := []string{"lazygit", "harlequin", "posting"}
args := []string{"--version"}
for _, dep := range deps {
checkArgs := config.ArgsVersion
if dep == "posting" {
checkArgs = []string{"--help"}
}
if err := runCmd(dep, checkArgs); err != nil {
return err
if err := runCmd(dep, []string{"--help"}); err != nil {
return err
}
} else {
if err := runCmd(dep, args); err != nil {
return err
}
}
}
return nil
}
func runCmd(dep string, args []string) error {
slog.Info("Checking dependency", "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")
if err := cmd.Run(); err != nil {
slog.Error("Command execution failed", "error", err)
return err
return fmt.Errorf("Fehler beim Überprüfen von %s: %w", dep, 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, err := os.ReadFile("/etc/os-release")
if err != nil {
return "", err
}
id, _, _ := parseOsRelease(string(osRelease))
return id, nil
}
func parseOsRelease(osRelease string) (id, name, version 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":
id = strings.Trim(splitLine[1], "\"")
case "NAME":
name = strings.Trim(splitLine[1], "\"")
case "VERSION_ID":
version = strings.Trim(splitLine[1], "\"")
}
}
return
}