switch utils.deadline to a context manager

This commit is contained in:
jesopo 2019-08-30 18:13:12 +01:00
parent 162aab9851
commit a57a06b1cc
2 changed files with 11 additions and 8 deletions

View file

@ -55,10 +55,10 @@ class Module(ModuleManager.BaseModule):
for_user = event["user"].nickname if self._closest_setting(event, for_user = event["user"].nickname if self._closest_setting(event,
"sed-sender-only", False) else None "sed-sender-only", False) else None
def _find(): with utils.deadline():
return event["target"].buffer.find(pattern, from_self=False, match = event["target"].buffer.find(pattern, from_self=False,
for_user=for_user, not_pattern=REGEX_SED) for_user=for_user, not_pattern=REGEX_SED)
match = utils.deadline(_find)
if match: if match:
new_message = re.sub(pattern, replace, match.line.message, new_message = re.sub(pattern, replace, match.line.message,
count) count)

View file

@ -1,4 +1,5 @@
import datetime, decimal, enum, io, ipaddress, re, signal, threading, typing import contextlib, datetime, decimal, enum, io, ipaddress, re, signal
import threading, typing
from src.utils import cli, consts, irc, http, parse, security from src.utils import cli, consts, irc, http, parse, security
class Direction(enum.Enum): class Direction(enum.Enum):
@ -348,11 +349,13 @@ class DeadlineExceededException(Exception):
def _raise_deadline(): def _raise_deadline():
raise DeadlineExceededException() raise DeadlineExceededException()
def deadline(f: typing.Callable[[], typing.Any], seconds: int=10) -> typing.Any: @contextlib.contextmanager
signal.signal(signal.SIGALRM, lambda _1, _2: _raise_deadline()) def deadline(seconds: int=10):
old_handler = signal.signal(signal.SIGALRM,
lambda _1, _2: _raise_deadline())
signal.alarm(seconds) signal.alarm(seconds)
try: try:
return f() yield
finally: finally:
signal.signal(signal.SIGALRM, signal.SIG_IGN) signal.signal(signal.SIGALRM, old_handler)