cleanup
[mediagoblin.git] / mediagoblin / storage / filestorage.py
index 22d6eb5a60ee9d27f05e40688778f891451101cd..3d6e0753e7798898e10c9cdf30fa314cc60c8176 100644 (file)
@@ -1,5 +1,5 @@
 # GNU MediaGoblin -- federated, autonomous media hosting
-# Copyright (C) 2011 MediaGoblin contributors.  See AUTHORS.
+# Copyright (C) 2011, 2012 MediaGoblin contributors.  See AUTHORS.
 #
 # This program is free software: you can redistribute it and/or modify
 # it under the terms of the GNU Affero General Public License as published by
@@ -20,6 +20,7 @@ from mediagoblin.storage import (
     NoWebServing)
 
 import os
+import shutil
 import urlparse
 
 
@@ -61,10 +62,32 @@ class BasicFileStorage(StorageInterface):
         return open(self._resolve_filepath(filepath), mode)
 
     def delete_file(self, filepath):
-        # TODO: Also delete unused directories if empty (safely, with
-        # checks to avoid race conditions).
+        """Delete file at filepath
+
+        Raises OSError in case filepath is a directory."""
+        #TODO: log error
         os.remove(self._resolve_filepath(filepath))
 
+    def delete_dir(self, dirpath, recursive=False):
+        """returns True on succes, False on failure"""
+
+        dirpath = self._resolve_filepath(dirpath)
+
+        # Shortcut the default and simple case of nonempty=F, recursive=F
+        if recursive:
+            try:
+                shutil.rmtree(dirpath)
+            except OSError as e:
+                #TODO: log something here
+                return False
+        else: # recursively delete everything
+            try:
+                os.rmdir(dirpath)
+            except OSError as e:
+                #TODO: log something here
+                return False
+        return True
+
     def file_url(self, filepath):
         if not self.base_url:
             raise NoWebServing(
@@ -76,3 +99,15 @@ class BasicFileStorage(StorageInterface):
 
     def get_local_path(self, filepath):
         return self._resolve_filepath(filepath)
+
+    def copy_local_to_storage(self, filename, filepath):
+        """
+        Copy this file from locally to the storage system.
+        """
+        # Make directories if necessary
+        if len(filepath) > 1:
+            directory = self._resolve_filepath(filepath[:-1])
+            if not os.path.exists(directory):
+                os.makedirs(directory)
+        # This uses chunked copying of 16kb buffers (Py2.7):
+        shutil.copy(filename, self.get_local_path(filepath))