From 8461abd6a2b97616e993ef0524db8f672cc6d9d4 Mon Sep 17 00:00:00 2001 From: Wolfgang Müller Date: Sun, 2 May 2021 13:21:34 +0200 Subject: Add option to specify the order for printed messages As mentioned in the previous commit, this change makes it possible to select the first or last N matches in conjunction with the -l flag. --- quarg/actions.py | 7 +++++++ quarg/main.py | 16 +++++++++++----- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/quarg/actions.py b/quarg/actions.py index 70cde03..6aadc3d 100644 --- a/quarg/actions.py +++ b/quarg/actions.py @@ -45,6 +45,13 @@ class ParseDate(argparse.Action): def __call__(self, parser, namespace, datespec, option_string=None): setattr(namespace, self.dest, parse_isodate(datespec)) +class ParseOrder(argparse.Action): + def __call__(self, parser, namespace, orderspec, option_string=None): + if orderspec not in ['asc', 'desc']: + errx(f'Invalid order \'{orderspec}\'. Possible values are: asc, desc') + + setattr(namespace, self.dest, orderspec) + class ParseAround(argparse.Action): def __call__(self, parser, namespace, aroundspec, option_string=None): if '/' in aroundspec: diff --git a/quarg/main.py b/quarg/main.py index 8b9987b..69c99de 100644 --- a/quarg/main.py +++ b/quarg/main.py @@ -19,6 +19,7 @@ cli.add_argument('keyword', nargs='*', help='match messages containing this keyw cli.add_argument('-d', action='store_true', dest='debug', help='print debug and SQL query information') cli.add_argument('-e', action='store_true', dest='expr', help='interpret keywords as LIKE expression') cli.add_argument('-l', dest='limit', metavar='NUM', type=int, help='limit the number of matches') +cli.add_argument('-o', action=actions.ParseOrder, dest='order', metavar='asc|desc', help='sort matches in this order') matchers = cli.add_argument_group('matching message context') matchers.add_argument('-b', action='append', dest='buffer', help='match this buffer') matchers.add_argument('-B', action=actions.ParseBufferType, dest='buftype', help='match buffers of this type') @@ -95,7 +96,7 @@ def collect_predicates(args): else: yield fun(value) -def run_query(session, predicates, limit): +def run_query(session, predicates, args): start = timer() query = session.query(Backlog).join(Sender).join(Buffer).join(Network).join(QuasselUser) @@ -103,9 +104,14 @@ def run_query(session, predicates, limit): for predicate in predicates: query = query.filter(predicate) - query = query.order_by(Backlog.time) - if limit: - query = query.limit(limit) + order = Backlog.time.asc() + if args.order == 'desc': + order = Backlog.time.desc() + + query = query.order_by(order) + + if args.limit: + query = query.limit(args.limit) rows = query.all() @@ -130,7 +136,7 @@ def main(): if not predicates: errx('Nothing to match.') - rows, time = run_query(session, predicates, args.limit) + rows, time = run_query(session, predicates, args) for row in rows: print(format_from(row)) -- cgit v1.2.3-2-gb3c3