stockholm/krebs/5pkgs/simple/Reaktor/scripts/sed-plugin.py

59 lines
1.5 KiB
Python
Raw Normal View History

2015-12-08 17:05:46 +00:00
#!/usr/bin/env python3
# Usage:
2015-12-08 18:38:19 +00:00
# _from=krebs state_dir=. python sed-plugin.py 'dick butt'
# _from=krebs state_dir=. python sed-plugin.py 's/t/l/g'
2017-05-12 17:24:41 +00:00
# > dick bull
2015-12-08 17:05:46 +00:00
import shelve
from os import environ
from os.path import join
from sys import argv
from time import sleep
2015-12-08 17:05:46 +00:00
import re
# try to open the shelve file until it succeeds
while True:
try:
d = shelve.open(
join(environ['state_dir'], 'sed-plugin.shelve'),
writeback=True
)
break
except: # noqa: E722
sleep(0.2)
2017-05-12 17:24:41 +00:00
usr = environ['_from']
2015-12-08 17:05:46 +00:00
def is_regex(line):
myre = re.compile(r'^s/(?:\\/|[^/])+/(?:\\/|[^/])*/[ig]?$')
2015-12-08 17:05:46 +00:00
return myre.match(line)
2018-03-28 19:16:03 +00:00
2015-12-08 17:05:46 +00:00
line = argv[1]
if is_regex(line):
2017-05-12 17:24:41 +00:00
last = d.get(usr, None)
2015-12-08 17:05:46 +00:00
if last:
2017-05-12 17:24:41 +00:00
from subprocess import Popen, PIPE
2018-03-28 19:16:03 +00:00
p = Popen(['sed', line], stdin=PIPE, stdout=PIPE, stderr=PIPE)
2017-05-12 17:24:41 +00:00
so, se = p.communicate(bytes("{}\n".format(last), "UTF-8"))
2015-12-08 17:26:08 +00:00
if p.returncode:
2018-03-28 19:16:03 +00:00
print("something went wrong when trying to process your regex: {}".format(line.strip()))
2015-12-08 18:38:19 +00:00
ret = so.decode()
2018-03-28 19:16:03 +00:00
if len(ret) > 512:
print('message to long, skipped')
elif len(ret.split('\n')) > 5:
print('to many lines, skipped')
else:
if last.strip() != ret.strip():
print("\x02{}\x02 meant: {}".format(usr, ret.strip()))
2018-03-28 19:16:03 +00:00
if ret:
d[usr] = ret
2015-12-08 17:26:08 +00:00
2015-12-08 17:05:46 +00:00
else:
print("no last message")
else:
2015-12-08 18:38:19 +00:00
d[usr] = line
2015-12-08 17:05:46 +00:00
d.close()