Skip to content

Instantly share code, notes, and snippets.

@Tatsh
Created October 8, 2014 00:22
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 Tatsh/e3cda257be1ca793cbdf to your computer and use it in GitHub Desktop.
Save Tatsh/e3cda257be1ca793cbdf to your computer and use it in GitHub Desktop.
from datetime import datetime, timedelta
from os import listdir, stat
from os.path import getsize, isdir, join as path_join, realpath
import argparse
import logging
import sys
from Crypto.Random.random import StrongRandom
from osext.filesystem import isfile
class SizedDatedDirectory:
path = None
max_size = None
comparison_time = None
_candidate_files = None
def __init__(self, path, max_days=30, max_size=None):
if not isdir(path):
raise ValueError('Not a directory: %s' % (path,))
self.path = realpath(path)
self.max_size = max_size
now = datetime.now()
before_delta = timedelta(days=30)
self.comparison_time = now - before_delta
def get_size(self, path=None):
if not path:
path = self.path
total_size = getsize(path)
for item in listdir(path):
itempath = path_join(path, item)
if isfile(itempath):
total_size += getsize(itempath)
elif isdir(itempath):
total_size += self.get_size(itempath)
return total_size
def should_be_downsized(self):
if not self.max_size:
return False
return self.get_size() > self.max_size
def get_candidate_files(self, refresh=False):
if refresh or self._candidate_files is None:
self._candidate_files = self._get_candidate_files()
return self._candidate_files
def _get_candidate_files(self, start_dir=None):
if not start_dir:
start_dir = self.path
ret = []
for item in listdir(start_dir):
itempath = path_join(start_dir, item)
if isfile(itempath):
if itempath[-4:] == '.nfo':
continue
date_modified = datetime.fromtimestamp(stat(itempath).st_atime)
if date_modified < self.comparison_time:
nfo = itempath[0:-4] + '.nfo'
ret.append((itempath, date_modified,))
if isfile(nfo):
ret.append((nfo, date_modified,))
elif isdir(itempath):
ret.extend(self._get_candidate_files(itempath))
return sorted(ret, key=lambda x: x[1], reverse=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment