Skip to content

Instantly share code, notes, and snippets.

@jhrmnn
Created June 29, 2022 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhrmnn/65c1a0d07018235263c98c6ba93b90e3 to your computer and use it in GitHub Desktop.
Save jhrmnn/65c1a0d07018235263c98c6ba93b90e3 to your computer and use it in GitHub Desktop.
#!/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