robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
3e21d49836
master
1#!/usr/bin/env python3 2 3import os 4import sys 5import codecs 6 7from enum import Enum 8from datetime import datetime 9from functools import reduce 10 11import msgpack 12 13 14class EntryTypes (Enum ): 15Unknown = - 1 16Missing = 0 17Header = 1 18SearchPattern = 2 19SubString = 3 20HistoryEntry = 4 21Register = 5 22Variable = 6 23GlobalMark = 7 24Jump = 8 25BufferList = 9 26LocalMark = 10 27Change = 11 28 29 30def strtrans_errors (e ): 31if not isinstance (e ,UnicodeDecodeError ): 32raise NotImplementedError ('don’t know how to handle {0} error' .format ( 33e .__class__ .__name__ )) 34return '<{0:x}>' .format (reduce ((lambda a ,b :a * 0x100 + b ), 35list (e .object [e .start :e .end ]))),e .end 36 37 38codecs .register_error ('strtrans' ,strtrans_errors ) 39 40 41def idfunc (o ): 42return o 43 44 45class CharInt (int ): 46def __repr__ (self ): 47return super (CharInt ,self ).__repr__ ()+ ' (\'%s\')' % chr (self ) 48 49 50ctable = { 51bytes :lambda s :s .decode ('utf-8' ,'strtrans' ), 52dict :lambda d :dict ((mnormalize (k ),mnormalize (v ))for k ,v in d .items ()), 53list :lambda l :list (mnormalize (i )for i in l ), 54int :lambda n :CharInt (n )if 0x20 <= n <= 0x7E else n , 55} 56 57 58def mnormalize (o ): 59return ctable .get (type (o ),idfunc )(o ) 60 61 62fname = sys .argv [1 ] 63try : 64filt = sys .argv [2 ] 65except IndexError : 66def filt (entry ):return True 67else : 68_filt = filt 69def filt (entry ):return eval (_filt ,globals (), {'entry' :entry })# noqa 70 71poswidth = len (str (os .stat (fname ).st_size or 1000 )) 72 73 74class FullEntry (dict ): 75def __init__ (self ,val ): 76self .__dict__ .update (val ) 77 78 79with open (fname ,'rb' )as fp : 80unpacker = msgpack .Unpacker (file_like = fp ,read_size = 1 ) 81max_type = max (typ .value for typ in EntryTypes ) 82while True : 83try : 84pos = fp .tell () 85typ = unpacker .unpack () 86except msgpack .OutOfData : 87break 88else : 89timestamp = unpacker .unpack () 90time = datetime .fromtimestamp (timestamp ) 91length = unpacker .unpack () 92if typ > max_type : 93entry = fp .read (length ) 94typ = EntryTypes .Unknown 95else : 96entry = unpacker .unpack () 97typ = EntryTypes (typ ) 98full_entry = FullEntry ({ 99'value' :entry , 100'timestamp' :timestamp , 101'time' :time , 102'length' :length , 103'pos' :pos , 104'type' :typ , 105 }) 106if not filt (full_entry ): 107continue 108'%*u %13s %s %5u %r' % ( 109poswidth ,pos ,typ .name ,time .isoformat (),length ,mnormalize (entry )))