Only remove contents of directory when clicking 'clear cache'
authorRyan Campbell <campbellr@gmail.com>
Sun, 30 Jan 2011 17:30:05 +0000 (10:30 -0700)
committerRyan Campbell <campbellr@gmail.com>
Mon, 31 Jan 2011 02:45:58 +0000 (19:45 -0700)
Only remove the contents of the directories, instead of the directories
themselves

package/src/mevemon.py
package/src/tests/test_util.py
package/src/util.py

index 8e116c9..f8036e4 100755 (executable)
@@ -22,7 +22,7 @@ import time
 import sys
 import logging
 import logging.handlers
-import shutil
+import util
 
 import hildon
 import gtk
@@ -288,8 +288,8 @@ class mEveMon:
     def clear_cache(self):
         """ Clears all cached data (images and eveapi cache) """
         try:
-            shutil.rmtree(IMG_CACHE_PATH)
-            shutil.rmtree(APICACHE_PATH)
+            util.clean_dir(IMG_CACHE_PATH)
+            util.clean_dir(APICACHE_PATH)
         except OSError, e:
             logging.getLogger('mevemon').exception("Failed to clear cache")
 
index 24ca9ec..e7f05a7 100644 (file)
@@ -1,5 +1,8 @@
 """ this module tests the util.py module """
 import unittest
+import tempfile
+import shutil
+import os
 
 import util
 
@@ -10,5 +13,21 @@ class TestUtil(unittest.TestCase):
         for number in NUMBERS.keys():
             self.assertEqual(util.comma(number), NUMBERS[number])
 
+    def test_clean_dir(self):
+        self._setup_files()
+        try: 
+            self.assertEqual(len(os.listdir(self.basedir)), 3)
+            util.clean_dir(self.basedir)
+            self.assertTrue(os.path.exists(self.basedir))
+            self.assertEqual(len(os.listdir(self.basedir)), 0)
+        finally:
+            if os.path.exists(self.basedir):
+                shutil.rmtree(self.basedir)
 
+    def _setup_files(self):
+        self.basedir = os.path.join(tempfile.gettempdir(), "mevemontest")
+        os.mkdir(self.basedir)
+        os.mkdir(os.path.join(self.basedir, "testdir"))
+        os.system("touch %s" % os.path.join(self.basedir, "testfile1"))
+        os.system("touch %s" % os.path.join(self.basedir, "testfile2"))
 
index 8a2c26f..7c52fec 100644 (file)
@@ -1,5 +1,7 @@
 """Random helpful functions for mevemon """
+import os
+import shutil
+
 def comma(number):
     """Converts a number in the format 1234567 to 1,234,567
     """
@@ -19,3 +21,13 @@ def comma(number):
     else:
         return ','.join(thousands) + '.' + fractional_part
 
+def clean_dir(path):
+    """ Removes the contents of a directory, but not the directory itself
+    """
+    names = os.listdir(path)
+    for name in names:
+        fullname = os.path.join(path, name)
+        if os.path.isdir(fullname):
+            shutil.rmtree(fullname)
+        else:
+            os.remove(fullname)