Commits

Randle Taylor committed 0dd862a

working script

Comments (0)

Files changed (1)

 import argparse
 import datetime
+import logging
 import os
 import time
 
+DATETIME_FORMAT = "%d %b %Y" #1 Jan 2013
+LOGFILENAME = "log.txt"
+
+
 #----------------------------------------------------------------------
 def days_validator(days):
     try:
     return path
 
 #----------------------------------------------------------------------
-def clean_dir(path,days):
+def delete_files(files,mock=False):
+    """try to delete all files"""
+
+    for f in files:
+        modified = datetime.date.fromtimestamp(os.path.getmtime(f))
+        logging.debug("deleting: %s last modified %s "%(f,modified.strftime(DATETIME_FORMAT)))
+        try:
+            if not mock:
+                os.remove(f)
+        except OSError:
+            logging.error("unable to delete %s"%f)
+#----------------------------------------------------------------------
+def delete_directory(d,mock=False):
+    """try to delete input directory"""
+    logging.debug("deleting empty dir: %s"%d)
+    try:
+        if not mock:
+            os.rmdir(d)
+    except OSError:
+        logging.error("unable to delete empty directory %s"%directory)
+
+#----------------------------------------------------------------------
+def file_older_than_threshold(f,threshold):
+    """return True if input file has modification date older than threshold"""
+    return datetime.date.fromtimestamp(os.path.getmtime(f)) < threshold
+
+#----------------------------------------------------------------------
+def clean_dir(root_dir,days,mock=False):
     """recursively walk path and delete files that have not been modified in
     less than input # of days"""
 
-    threshold = datetime.date.today()-datetime.timedelta(days=days)
+    threshold_date = datetime.date.today() - datetime.timedelta(days=days)
 
-    for directory, subdirs, files in os.walk(path):
-        for f in files:
-            fpath = os.path.join(directory,f)
-            modified = datetime.date.fromtimestamp(os.path.getmtime(fpath))
+    for cur_dir, subdirs, files in os.walk(root_dir):
 
-            if modified < threshold:
-                print "delete this file:", fpath, modified
+        file_paths = [os.path.join(cur_dir,f) for f in files]
+        to_delete = [f for f in file_paths if file_older_than_threshold(f,threshold_date)]
 
+        delete_files(to_delete,mock=mock)
+
+        cur_dir_is_empty = os.listdir(cur_dir) == []
+        if root_dir != cur_dir and cur_dir_is_empty:
+            delete_directory(cur_dir,mock=mock)
 
 
 
 
 if __name__  == "__main__":
 
-    parser = argparse.ArgumentParser(description='Walk a directory structure and delete files older (haven''t been modified) than input number of days')
 
+    parser = argparse.ArgumentParser(description='Walk a directory structure and delete files older (haven''t been modified) than input number of days')
     parser.add_argument('directory', help='top level directory to walk through', type=dir_validator)
     parser.add_argument('days', help='Delete files older (not modified) than this number of days',type=days_validator)
+    parser.add_argument('--debug', action="store_true", help="Run in debug mode: mock run where no files will be deleted.")
 
     args = parser.parse_args()
 
-    clean_dir(args.directory,args.days)
+    if args.debug:
+        DEBUG_LEVEL = logging.DEBUG
+    else:
+        DEBUG_LEVEL = logging.INFO
+
+    log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)),LOGFILENAME)
+    logging.basicConfig(filename=log_file,filemode="a",level=DEBUG_LEVEL)
+
+    logging.debug("### Start cleanbydate ###")
+    logging.debug("start %s" % datetime.datetime.now().strftime(DATETIME_FORMAT))
+
+    clean_dir(args.directory,args.days,mock=args.debug)
+
+    logging.debug("end %s" % datetime.datetime.now().strftime(DATETIME_FORMAT))
+