Created
June 29, 2022 10:19
-
-
Save jhrmnn/65c1a0d07018235263c98c6ba93b90e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
from argparse import ArgumentParser | |
from pathlib import Path | |
from datetime import datetime, timedelta | |
import subprocess | |
from math import log, sqrt | |
def prune(seq, key, cum, dist): | |
pruned = [] | |
n = 0 | |
for x in sorted(seq, key=key): | |
if n <= cum(key(x)): | |
n += 1 | |
pruned.append(x) | |
return pruned | |
def prune2(seq, key, cum, dist): | |
pruned = [] | |
n = 0 | |
for x in sorted(seq, key=key): | |
if not pruned or 1/(key(x)-key(pruned[-1])) < dist(key(pruned[-1])): | |
n += 1 | |
pruned.append(x) | |
return pruned | |
def main(root, confirmed=False): | |
keep = {} | |
now = datetime.today() | |
paths = list(root.glob('????-??-??-??????')) | |
keep = prune2( | |
paths, | |
lambda p: (now-datetime.strptime(p.name, '%Y-%m-%d-%H%M%S'))/timedelta(1), | |
lambda x: 60*log(1+sqrt(x)), | |
lambda x: 30/(sqrt(x)+x) | |
) | |
delete = set(paths) - set(keep) | |
for path in sorted(paths): | |
print('x' if path in delete else ' ', path) | |
print(f'Will delete ({len(delete)}/{len(paths)}):') | |
if not confirmed and len(keep) < len(paths): | |
answer = input('Proceed? [y]: ') | |
if answer != 'y': | |
return | |
for path in sorted(delete): | |
print(f'Deleting {path}...', end='', flush=True) | |
subprocess.run(['rm', '-rf', str(path)]) | |
print(' Done.') | |
def wrapper(roots, **kwargs): | |
for root in roots: | |
main(root, **kwargs) | |
def cli(): | |
parser = ArgumentParser() | |
arg = parser.add_argument | |
arg('roots', metavar='root', type=Path, nargs='+') | |
arg('--confirmed', action='store_true') | |
return vars(parser.parse_args()) | |
if __name__ == '__main__': | |
try: | |
wrapper(**cli()) | |
except KeyboardInterrupt: | |
raise SystemExit(2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment