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

42 lines
1.0 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
import re
2017-05-12 17:24:41 +00:00
d = shelve.open(join(environ['state_dir'], 'sed-plugin.shelve'), writeback=True)
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)
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
p = Popen(['sed', line], stdin=PIPE, stdout=PIPE)
so, se = p.communicate(bytes("{}\n".format(last), "UTF-8"))
2015-12-08 17:26:08 +00:00
if p.returncode:
2015-12-08 18:38:19 +00:00
print("something went wrong when trying to process your regex: {}".format(se.decode()))
ret = so.decode()
2017-05-12 17:25:39 +00:00
print("\x1b[1m{}\x1b[0m meant: {}".format(usr, ret.strip()))
2015-12-08 18:38:19 +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()