2023-05-03 20:03:22 +02:00
|
|
|
package app
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/gob"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2023-05-04 01:01:22 +02:00
|
|
|
"net"
|
2023-05-03 20:03:22 +02:00
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
Query = 0
|
|
|
|
Flush = 1
|
|
|
|
)
|
|
|
|
|
|
|
|
type Request struct {
|
|
|
|
Request int
|
|
|
|
Pattern string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Response struct {
|
|
|
|
Err error
|
|
|
|
Actions ReadableMap
|
|
|
|
}
|
|
|
|
|
2023-05-04 01:01:22 +02:00
|
|
|
func SocketPath() string {
|
|
|
|
return fmt.Sprintf("/run/user/%v/reaction.sock", os.Getuid())
|
2023-05-03 20:03:22 +02:00
|
|
|
}
|
|
|
|
|
2023-05-04 01:01:22 +02:00
|
|
|
func SendAndRetrieve(data Request) Response {
|
|
|
|
conn, err := net.Dial("unix", SocketPath())
|
2023-05-03 20:03:22 +02:00
|
|
|
if err != nil {
|
2023-05-04 01:01:22 +02:00
|
|
|
log.Fatalln("Error opening connection top daemon:", err)
|
2023-05-03 20:03:22 +02:00
|
|
|
}
|
2023-05-04 01:01:22 +02:00
|
|
|
|
|
|
|
err = gob.NewEncoder(conn).Encode(data)
|
2023-05-03 20:03:22 +02:00
|
|
|
if err != nil {
|
2023-05-04 01:01:22 +02:00
|
|
|
log.Fatalln("Can't send message:", err)
|
2023-05-03 20:03:22 +02:00
|
|
|
}
|
|
|
|
|
2023-05-04 01:01:22 +02:00
|
|
|
var response Response
|
|
|
|
err = gob.NewDecoder(conn).Decode(&response)
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalln("Invalid answer from daemon:", err)
|
2023-05-03 20:03:22 +02:00
|
|
|
}
|
2023-05-04 01:01:22 +02:00
|
|
|
return response
|
2023-05-03 20:03:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func usage(err string) {
|
|
|
|
fmt.Println("Usage: reactionc")
|
|
|
|
fmt.Println("Usage: reactionc flush <PATTERN>")
|
|
|
|
log.Fatalln(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
func CLI() {
|
|
|
|
if len(os.Args) <= 1 {
|
2023-05-04 01:01:22 +02:00
|
|
|
response := SendAndRetrieve(Request{Query, ""})
|
2023-05-03 20:03:22 +02:00
|
|
|
if response.Err != nil {
|
|
|
|
log.Fatalln("Received error from daemon:", response.Err)
|
|
|
|
}
|
|
|
|
fmt.Println(response.Actions.ToString())
|
|
|
|
os.Exit(0)
|
|
|
|
}
|
|
|
|
switch os.Args[1] {
|
|
|
|
case "flush":
|
|
|
|
if len(os.Args) != 3 {
|
|
|
|
usage("flush takes one <PATTERN> argument")
|
|
|
|
}
|
2023-05-04 01:01:22 +02:00
|
|
|
response := SendAndRetrieve(Request{Flush, os.Args[2]})
|
2023-05-03 20:03:22 +02:00
|
|
|
if response.Err != nil {
|
|
|
|
log.Fatalln("Received error from daemon:", response.Err)
|
|
|
|
}
|
|
|
|
os.Exit(0)
|
|
|
|
default:
|
|
|
|
usage("first argument must be `flush`")
|
|
|
|
}
|
|
|
|
}
|