4 # Copyright (c) 2009-2010 Evert Pot
6 # http://www.rooftopsolutions.nl/
8 # This utility is distributed along with SabreDAV
9 # license: http://code.google.com/p/sabredav/wiki/License Modified BSD License
12 from optparse import OptionParser
15 def getfreespace(path):
16 stat = os.statvfs(path)
17 return stat.f_frsize * stat.f_bavail
19 def getbytesleft(path,treshold):
20 return getfreespace(path)-treshold
22 def run(cacheDir, treshold, sleep=5, simulate=False, min_erase = 0):
24 bytes = getbytesleft(cacheDir,treshold)
26 print "Bytes to go before we hit treshhold:", bytes
28 print "Treshold exceeded with:", -bytes, "bytes"
29 dir = os.listdir(cacheDir)
32 path = cacheDir + '/' + file
35 "atime": os.stat(path).st_atime,
36 "size" : os.stat(path).st_size
39 dir2.sort(lambda x,y: int(x["atime"]-y["atime"]))
44 # Left is the amount of bytes that need to be freed up
45 # The default is the 'min_erase setting'
48 # If the min_erase setting is lower than the amount of bytes over
49 # the treshold, we use that number instead.
53 print "Need to delete at least:", left;
57 # Only deleting files if we're not simulating
58 if not simulate: os.unlink(file["path"])
59 left = int(left - file["size"])
60 gainedspace = gainedspace + file["size"]
61 filesunlinked = filesunlinked + 1
66 print "%d files deleted (%d bytes)" % (filesunlinked, gainedspace)
74 parser = OptionParser(
75 version="naturalselecton v0.3",
76 description="Cache directory manager. Deletes cache entries based on accesstime and free space tresholds.\n" +
77 "This utility is distributed alongside SabreDAV.",
78 usage="usage: %prog [options] cacheDirectory",
84 help="Don't actually make changes, but just simulate the behaviour",
88 help="How many times to check before exiting. -1 is infinite, which is the default",
95 help="Sleep time in seconds (default = 5)",
102 help="Treshhold in bytes (default = 10737418240, which is 10GB)",
109 help="Minimum number of bytes to erase when the treshold is reached. " +
110 "Setting this option higher will reduce the amount of times the cache directory will need to be scanned. " +
111 "(the default is 1073741824, which is 1GB.)",
117 options,args = parser.parse_args()
119 parser.error("This utility requires at least 1 argument")
122 print "Natural Selection"
123 print "Cache directory:", cacheDir
124 free = getfreespace(cacheDir);
125 print "Current free disk space:", free
132 simulate=options.simulate,
133 treshold=options.treshold,
134 min_erase=options.min_erase
139 if __name__ == '__main__' :