Merge pull request 'refactor-and-add-tests' (#1) from refactor-and-add-tests into main

Reviewed-on: https://codeberg.org/Pata1704/tmux_popup/pulls/1
This commit is contained in:
Pata1704 2024-12-25 07:23:44 +00:00
commit 9812ae48d6
4 changed files with 139 additions and 73 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=

144
main.go
View file

@ -1,49 +1,92 @@
package main
import (
"bytes"
"fmt"
"log/slog"
"os"
"os/exec"
"strings"
"github.com/spf13/cobra"
)
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: "A CLI tool for various actions",
Long: "tmux_popup is a CLI tool that supports various actions like tmux, lazygit, harlequin, and postings. It opens these programs in a floating tmux pane.",
}
action := os.Args[1]
width := "80%"
height := "80%"
rootCmd.PersistentFlags().String("width", "80%", "Width of the popup (e.g., 80%)")
rootCmd.PersistentFlags().String("height", "80%", "Height of the popup (e.g., 80%)")
if len(os.Args) > 2 {
width = os.Args[2]
height = os.Args[2]
rootCmd.AddCommand(tmuxCmd)
rootCmd.AddCommand(lazygitCmd)
rootCmd.AddCommand(harlequinCmd)
rootCmd.AddCommand(postingsCmd)
rootCmd.AddCommand(checkCmd)
if err := rootCmd.Execute(); err != nil {
fmt.Println("Error:", err)
os.Exit(1)
}
}
switch action {
case "tmux":
var tmuxCmd = &cobra.Command{
Use: "tmux",
Short: "Opens a 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: "Opens lazygit in a 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: "Opens harlequin in a 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: "Opens postings in a popup",
Run: func(cmd *cobra.Command, args []string) {
width, _ := cmd.Flags().GetString("width")
height, _ := cmd.Flags().GetString("height")
openPopup("postings", "posting", width, height)
default:
CheckDependencies()
fmt.Println("Unbekannte Aktion")
}
},
}
var checkCmd = &cobra.Command{
Use: "check",
Short: "Checks the dependencies",
Run: func(cmd *cobra.Command, args []string) {
if err := CheckDependencies(); err != nil {
fmt.Println("Error checking dependencies:", err)
os.Exit(1)
}
fmt.Println("All dependencies are present.")
},
}
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)
fmt.Println("Error retrieving the current session:", err)
return
}
@ -63,70 +106,25 @@ func openPopup(sessionName, command string, width, height string) {
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 {
if dep == "posting" {
if err := runCmd(dep, []string{"--help"}); err != nil {
return err
}
} else {
err := runCmd(dep, []string{"--help"})
if err != nil {
if err := runCmd(dep, args); 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
if err := cmd.Run(); err != nil {
return fmt.Errorf("Error checking %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, _ := 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
}

51
main_test.go Normal file
View file

@ -0,0 +1,51 @@
package main
import (
"bytes"
"os/exec"
"strings"
"testing"
)
func TestOpenPopup(t *testing.T) {
// Mock tmux command for testing
cmd := exec.Command("echo", "mock_session")
output, err := cmd.Output()
if err != nil {
t.Fatalf("Failed to mock tmux command: %v", err)
}
currentSession := strings.TrimSpace(string(output))
if currentSession != "mock_session" {
t.Errorf("Expected mock_session, got %s", currentSession)
}
}
func TestCheckDependencies(t *testing.T) {
// Create a mock dependency list for testing
mockDeps := []string{"echo", "ls"}
for _, dep := range mockDeps {
cmd := exec.Command(dep, "--version")
err := cmd.Run()
if err != nil {
t.Errorf("Dependency %s check failed: %v", dep, err)
}
}
}
func TestRunCmd(t *testing.T) {
var stdout, stderr bytes.Buffer
cmd := exec.Command("echo", "Hello, World!")
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
t.Fatalf("runCmd failed: %v", err)
}
if stdout.String() != "Hello, World!\n" {
t.Errorf("Expected 'Hello, World!', got %s", stdout.String())
}
}