sway/run_command.go
2024-02-14 15:12:39 +01:00

55 lines
1.1 KiB
Go

package sway
import (
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"git.milar.in/milarin/slices"
)
func (c *Client) RunCommand(ctx context.Context, cmd string) ([]error, error) {
c.Lock()
defer c.Unlock()
if _, err := fmt.Fprint(c.conn, "i3-ipc"); err != nil {
return nil, err
}
if err := binary.Write(c.conn, binary.LittleEndian, uint32(len(cmd))); err != nil {
return nil, err
}
if err := binary.Write(c.conn, binary.LittleEndian, uint32(0)); err != nil {
return nil, err
}
if _, err := fmt.Fprint(c.conn, cmd); err != nil {
return nil, err
}
if _, err := c.conn.Read(make([]byte, 6)); err != nil {
return nil, err
}
var length uint32
if err := binary.Read(c.conn, binary.LittleEndian, &length); err != nil {
return nil, err
}
var messageType uint32
if err := binary.Read(c.conn, binary.LittleEndian, &messageType); err != nil {
return nil, err
}
results := []commandResult{}
if err := json.NewDecoder(io.LimitReader(c.conn, int64(length))).Decode(&results); err != nil {
return nil, err
}
errors := slices.Map(slices.Filter(results, commandResult.HasError), commandResult.GetError)
return errors, nil
}