]> git.lizzy.rs Git - bspwm.git/blob - contrib/rules/rulc
Fail when no command is provided
[bspwm.git] / contrib / rules / rulc
1 #! /usr/bin/env lua
2
3 local p = require "posix"
4 local port = 54321
5
6 local short = "hp:arltq"
7 local long = {
8     {"help", "none", 'h'},
9     {"port", "required", 'p'},
10     {"add", "none", 'a'},
11     {"remove", "none", 'r'},
12     {"list", "none", 'l'},
13     {"test", "none", 't'},
14     {"quit", "none", 'q'}
15 }
16
17 local cmd_assoc = {
18     a = "add",
19     r = "remove",
20     l = "list",
21     t = "test",
22     q = "quit"
23 }
24
25 local cmd
26 local data_idx = 1
27 for opt, optarg, optind, longind in p.getopt(arg, short, long) do
28     if opt == '?' then
29         print("Unrecognized option")
30         os.exit(1)
31     elseif opt == 'h' then
32         print("Usage: rulc [-h|-p PORT|-a|-r|-l|-t|-q] DATA ...")
33         os.exit(0)
34     elseif opt == 'p' then
35         port = optarg
36     else
37         cmd = cmd_assoc[opt]
38     end
39     data_idx = optind
40 end
41
42 if not cmd then
43     os.exit(1)
44 end
45
46 local msg = cmd
47 if cmd == "test" then
48     msg = string.format("%s {class=%q, instance=%q, title=%q, type=%q, state=%q}", msg, arg[data_idx], arg[data_idx+1], arg[data_idx+2], arg[data_idx+3], arg[data_idx+4])
49 elseif cmd == "add" then
50     msg = string.format("%s {%q, %q, %s}", msg, arg[data_idx], arg[data_idx+1], arg[data_idx+2] and string.format("{%s}", arg[data_idx+2]) or "")
51 elseif cmd == "remove" then
52     msg = string.format("%s %s", msg, arg[data_idx])
53 end
54
55 local fd = p.socket(p.AF_INET, p.SOCK_STREAM, 0)
56 local s = p.connect(fd, {family=p.AF_INET, addr="127.0.0.1", port=port})
57 if not s then
58     p.close(fd)
59     os.exit(1)
60 end
61 p.send(fd, msg)
62 rsp = p.recv(fd, p.BUFSIZ)
63
64 if rsp and #rsp > 0 then
65     print(rsp)
66 end
67
68 p.close(fd)