hypr/get_instances.go
2024-02-09 20:24:48 +01:00

71 lines
1.3 KiB
Go

package hypr
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"strconv"
"strings"
"git.milar.in/milarin/slices"
)
func GetInstance(signature string) (*Instance, error) {
lockFilePath := fmt.Sprintf("/tmp/hypr/%s.lock", signature)
file, err := os.Open(lockFilePath)
if err != nil {
return nil, err
}
defer file.Close()
data, err := io.ReadAll(file)
if err != nil {
return nil, err
}
lines := strings.Split(string(data), "\n")
pid, err := strconv.Atoi(lines[0])
if err != nil {
return nil, err
}
return &Instance{
Signature: signature,
PID: pid,
WaylandSocket: lines[1],
}, nil
}
func GetDefaultInstance() (*Instance, error) {
signature, ok := os.LookupEnv("HYPRLAND_INSTANCE_SIGNATURE")
if !ok {
return nil, errors.New("default instance not found because HYPRLAND_INSTANCE_SIGNATURE is not set")
}
return GetInstance(signature)
}
func GetInstances() ([]*Instance, error) {
entries, err := os.ReadDir("/tmp/hypr")
if err != nil {
return nil, err
}
entries = slices.Filter(entries, fs.DirEntry.IsDir)
instances := make([]*Instance, 0, len(entries))
for _, entry := range entries {
instance, err := GetInstance(entry.Name())
if err != nil {
fmt.Println(err)
continue
}
instances = append(instances, instance)
}
return instances, nil
}