summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormathieui <mathieui@mathieui.net>2021-04-09 22:00:57 +0200
committermathieui <mathieui@mathieui.net>2021-04-11 16:33:53 +0200
commit7ece33514592b2af0190a5c28309050fa04ac66f (patch)
treebb3842b3bfdf22cced176bc5e599696baf74ab54
parenta3fcfd3ffdb73bc3d0f90edb10c77fcaddb8800f (diff)
downloadpoezio-7ece33514592b2af0190a5c28309050fa04ac66f.tar.gz
poezio-7ece33514592b2af0190a5c28309050fa04ac66f.tar.bz2
poezio-7ece33514592b2af0190a5c28309050fa04ac66f.tar.xz
poezio-7ece33514592b2af0190a5c28309050fa04ac66f.zip
feature: add a function to iterate over all messages of a log file
in reverse order
-rw-r--r--poezio/logger.py30
1 files changed, 30 insertions, 0 deletions
diff --git a/poezio/logger.py b/poezio/logger.py
index 329b9283..23a4fbeb 100644
--- a/poezio/logger.py
+++ b/poezio/logger.py
@@ -289,6 +289,36 @@ def build_log_message(nick: str,
return logged_msg + ''.join(' %s\n' % line for line in lines)
+def iterate_messages_reverse(filepath: Path):
+ """Get the latest messages from the log file, one at a time.
+
+ :param fd: the file descriptor
+ """
+ try:
+ with open(filepath, 'rb') as fd:
+ with mmap.mmap(fd.fileno(), 0, prot=mmap.PROT_READ) as m:
+ # start of messages begin with MI or MR, after a \n
+ pos = m.rfind(b"\nM") + 1
+ lines = parse_log_lines(
+ m[pos:-1].decode(errors='replace').splitlines()
+ )
+ if lines:
+ yield lines[0]
+ # number of message found so far
+ count = 0
+ while pos > 0:
+ count += 1
+ old_pos = pos
+ pos = m.rfind(b"\nM", 0, pos) + 1
+ lines = parse_log_lines(
+ m[pos:old_pos].decode(errors='replace').splitlines()
+ )
+ if lines:
+ yield lines[0]
+ except OSError:
+ pass
+
+
def _get_lines_from_fd(fd: IO[Any], nb: int = 10) -> List[str]:
"""
Get the last log lines from a fileno with mmap