gridftp: handle paths beginning with `~`
[qcg-portal.git] / filex / ftp.py
index c2f3b3a..29c4598 100644 (file)
@@ -1,9 +1,9 @@
 from datetime import datetime
 from Queue import Queue, Empty
+from itertools import chain
 import os
 import re
 from threading import Event
-from urlparse import urlparse
 
 from django.utils.timezone import localtime, UTC
 from gridftp import FTPClient, Buffer, HandleAttr, OperationAttr
@@ -135,7 +135,7 @@ class FTPOperation:
         data = self.listing(url).next()
 
         if data['name'] == '.':
-            data['name'] = os.path.basename(urlparse(url).path.rstrip('/')) or u'/'
+            data['name'] = os.path.basename(os.path.normpath(url))
 
         return data
 
@@ -154,23 +154,37 @@ class FTPOperation:
 
         self.wait()
 
+    @staticmethod
+    def match_ext(archive, *extensions):
+        for ext in extensions:
+            if archive.endswith(ext):
+                return True
+        return False
+
     def compress(self, server, path, files, archive):
-        def match_ext(*extensions):
-            for ext in extensions:
-                if archive.endswith(ext):
-                    return True
-            return False
-
-        if match_ext('.tar.gz', '.tgz'):
-            cmd, args = 'tar', ['cvzf', os.path.join(path, archive), '-C', path] + files
-        elif match_ext('.tar.bz2', '.tbz'):
-            cmd, args = 'tar', ['cvjf', os.path.join(path, archive), '-C', path] + files
-        elif match_ext('.zip'):
-            cmd, args = 'zip', ['-r', os.path.join(path, archive)] + [os.path.join(path, f) for f in files]
+        if self.match_ext(archive, '.tar.gz', '.tgz'):
+            cmd, args = 'tar', ['cvzf', archive, '-C', path] + files
+        elif self.match_ext(archive, '.tar.bz2', '.tbz'):
+            cmd, args = 'tar', ['cvjf', archive, '-C', path] + files
+        elif self.match_ext(archive, '.zip'):
+            cmd, args = 'jar', (['cvMf', archive] + list(chain.from_iterable(('-C', path, f) for f in files)))
         else:
             raise ValueError('Unknown archive type: {}'.format(archive))
 
-        # FIXME handling filename with #
         self.op_attr.set_disk_stack('#'.join(["popen:argv=", cmd] + args))
 
         return self.get(server)
+
+    def extract(self, server, archive, dst):
+        if self.match_ext(archive, '.tar.gz', '.tgz'):
+            cmd, args = 'tar', ('xvzf', archive, '-C', dst)
+        elif self.match_ext(archive, '.tar.bz2', '.tbz'):
+            cmd, args = 'tar', ('xvjf', archive, '-C', dst)
+        elif self.match_ext(archive, '.zip'):
+            cmd, args = 'unzip', (archive, '-d', dst)
+        else:
+            raise ValueError('Unknown archive type: {}'.format(archive))
+
+        self.op_attr.set_disk_stack('#'.join(("popen:argv=", cmd) + args))
+
+        return self.get(server)