From a747c2c2904f443d063c3984c9772e8e20c2c62f Mon Sep 17 00:00:00 2001 From: Mike Kazantsev Date: Sun, 27 Oct 2024 03:06:03 +0500 Subject: [PATCH] lsx: add -t/--mtime option --- lsx | 155 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 150 insertions(+), 5 deletions(-) diff --git a/lsx b/lsx index d52837a..376adb1 100755 --- a/lsx +++ b/lsx @@ -4,6 +4,11 @@ import os, sys, stat, re, pathlib as pl, collections as cs p_err = lambda *a,**kw: print('ERROR:', *a, **kw, file=sys.stderr, flush=True) +class adict(dict): + def __init__(self, *args, **kws): + super().__init__(*args, **kws) + self.__dict__ = self + def list_adjacent(paths, specs, files_only=False): p_dirs, stats, p_out = dict(), dict(), dict() @@ -72,6 +77,107 @@ def list_adjacent(paths, specs, files_only=False): return list(ps_print.keys()) +def mtime_parse(mtimes, err_func): + import datetime as dt + ts_now = dt.datetime.now() + _td_days = dict( + y=365.25, yr=365.25, year=365.25, + mo=30.5, month=30.5, w=7, week=7, d=1, day=1 ) + _td_s = dict( h=3600, hr=3600, hour=3600, + m=60, min=60, minute=60, s=1, sec=1, second=1 ) + _td_usort = lambda d: sorted( + d.items(), key=lambda kv: (kv[1], len(kv[0])), reverse=True ) + _td_re = re.compile('(?i)^[-+]?' + ''.join( fr'(?P<{k}>\d+{k}\s*)?' + for k, v in [*_td_usort(_td_days), *_td_usort(_td_s)] ) + '$') + def _ts_parse(ts_str, rel=False): + ts = (ts_str := ts_str.strip()).lower() == 'now' and dt.timedelta(0) + no_ts = lambda: ts in [None, False] + if no_ts(): + try: ts = dt.timedelta(seconds=float(ts_str)) + except: pass + if no_ts() and ( # short time offset like "3d 5h" + (m := _td_re.search(ts_str)) and any(m.groups()) ): + delta = list() + for units in _td_days, _td_s: + val = 0 + for k, v in units.items(): + if not m.group(k): continue + val += v * int(''.join(filter(str.isdigit, m.group(k))) or 1) + delta.append(val) + ts = dt.timedelta(*delta) + if no_ts() and (m := re.search( # common BE format + r'^(?P(?:\d{2}|(?P\d{4}))-\d{2}-\d{2})' + r'(?:[ T](?P