Merge branch 'master' of https://code.grnet.gr/git/pithos
[pithos] / tools / store
index 61a3041..4eee33f 100755 (executable)
@@ -37,8 +37,9 @@ from getpass import getuser
 from optparse import OptionParser
 from os import environ
 from sys import argv, exit, stdin, stdout
-from pithos.lib.client import Pithos_Client, Fault
 from datetime import datetime
+from lib.client import Pithos_Client, Fault
+from lib.util import get_user, get_auth, get_server, get_api
 
 import json
 import logging
@@ -47,10 +48,6 @@ import re
 import time as _time
 import os
 
-#DEFAULT_HOST = 'pithos.dev.grnet.gr'
-DEFAULT_HOST = '127.0.0.1:8000'
-DEFAULT_API = 'v1'
-
 _cli_commands = {}
 
 def cli_command(*args):
@@ -70,15 +67,15 @@ class Command(object):
     def __init__(self, name, argv):
         parser = OptionParser('%%prog %s [options] %s' % (name, self.syntax))
         parser.add_option('--host', dest='host', metavar='HOST',
-                          default=_get_server(), help='use server HOST')
+                          default=get_server(), help='use server HOST')
         parser.add_option('--user', dest='user', metavar='USERNAME',
-                          default=_get_user(),
+                          default=get_user(),
                           help='use account USERNAME')
         parser.add_option('--token', dest='token', metavar='AUTH',
-                          default=_get_auth(),
+                          default=get_auth(),
                           help='use account AUTH')
         parser.add_option('--api', dest='api', metavar='API',
-                          default=DEFAULT_API, help='use api API')
+                          default=get_api(), help='use api API')
         parser.add_option('-v', action='store_true', dest='verbose',
                           default=False, help='use verbose output')
         parser.add_option('-d', action='store_true', dest='debug',
@@ -310,6 +307,8 @@ class GetObject(Command):
         if self.versionlist:
             if 'detail' in args.keys():
                 args.pop('detail')
+            args.pop('format')
+            self.detail = True
             data = self.client.retrieve_object_versionlist(container, object, **args)
         elif self.version:
             data = self.client.retrieve_object_version(container, object,
@@ -319,7 +318,6 @@ class GetObject(Command):
         
         f = self.file and open(self.file, 'w') or stdout
         if self.detail:
-            data = json.loads(data)
             if self.versionlist:
                 print_versions(data, f=f)
             else:
@@ -358,7 +356,7 @@ class PutObject(Command):
         #parser.add_option('-S', action='store',
         #                  dest='segment_size', default=False,
         #                  help='use for large file support')
-        parser.add_option('--manifest', action='store_true',
+        parser.add_option('--manifest', action='store',
                           dest='x_object_manifest', default=None,
                           help='upload a manifestation file')
         parser.add_option('--content-type', action='store',
@@ -401,9 +399,13 @@ class PutObject(Command):
             self.client.create_object_using_chunks(container, object, f,
                                                     meta=meta, **args)
         elif self.use_hashes:
-            format = 'json' if detail else 'text'
-            self.client.create_object_by_hashmap(container, object, f, format,
-                                 meta=meta, **args)
+            data = f.read()
+            if data is object:
+                hashmap = json.loads()
+                self.client.create_object_by_hashmap(container, object, hashmap,
+                                                 meta=meta, **args)
+            else:
+                print "Expected object"
         elif self.x_object_manifest:
             self.client.create_manifestation(container, object, self.x_object_manifest)
         elif not f:
@@ -425,6 +427,9 @@ class CopyObject(Command):
         parser.add_option('--public', action='store_true',
                           dest='public', default=False,
                           help='make object publicly accessible')
+        parser.add_option('--content-type', action='store',
+                          dest='content_type', default=None,
+                          help='change object\'s content type')
     
     def execute(self, src, dst, *args):
         src_container, sep, src_object = src.partition('/')
@@ -440,8 +445,10 @@ class CopyObject(Command):
             dst_container = src_container
             dst_object = dst
         
+        args = {'content_type':self.content_type} if self.content_type else {}
         self.client.copy_object(src_container, src_object, dst_container,
-                                dst_object, meta, self.public, self.version, **meta)
+                                dst_object, meta, self.public, self.version,
+                                **args)
 
 @cli_command('set')
 class SetMeta(Command):
@@ -503,6 +510,9 @@ class UpdateObject(Command):
         parser.add_option('--public', action='store_true',
                           dest='x_object_public', default=False,
                           help='make object publicly accessible')
+        parser.add_option('--replace', action='store_true',
+                          dest='replace', default=False,
+                          help='override metadata')
     
     def execute(self, path, *args):
         if path.find('=') != -1:
@@ -518,7 +528,7 @@ class UpdateObject(Command):
             self.x_object_sharing = ''
         
         attrs = ['content_encoding', 'content_disposition', 'x_object_sharing',
-                 'x_object_public']
+                 'x_object_public', 'replace']
         args = self._build_args(attrs)
         
         container, sep, object = path.partition('/')
@@ -531,8 +541,7 @@ class UpdateObject(Command):
             self.client.update_object_using_chunks(container, object, f,
                                                     meta=meta, **args)
         else:
-            data = f.read() if f else None
-            self.client.update_object(container, object, data, meta=meta, **args)
+            self.client.update_object(container, object, f, meta=meta, **args)
         if f:
             f.close()
 
@@ -548,6 +557,9 @@ class MoveObject(Command):
         parser.add_option('--public', action='store_true',
                           dest='public', default=False,
                           help='make object publicly accessible')
+        parser.add_option('--content-type', action='store',
+                          dest='content_type', default=None,
+                          help='change object\'s content type')
     
     def execute(self, src, dst, *args):
         src_container, sep, src_object = src.partition('/')
@@ -562,28 +574,9 @@ class MoveObject(Command):
             key, sep, val = arg.partition('=')
             meta[key] = val
         
+        args = {'content_type':self.content_type} if self.content_type else {}
         self.client.move_object(src_container, src_object, dst_container,
-                                dst_object, meta, self.public, self.version)
-
-@cli_command('remove')
-class TrashObject(Command):
-    syntax = '<container>/<object>'
-    description = 'trash an object'
-    
-    def execute(self, src):
-        src_container, sep, src_object = src.partition('/')
-        
-        self.client.trash_object(src_container, src_object)
-
-@cli_command('restore')
-class RestoreObject(Command):
-    syntax = '<container>/<object>'
-    description = 'restore a trashed object'
-    
-    def execute(self, src):
-        src_container, sep, src_object = src.partition('/')
-        
-        self.client.restore_object(src_container, src_object)
+                                dst_object, meta, self.public, self.version, **args)
 
 @cli_command('unset')
 class UnsetObject(Command):
@@ -672,6 +665,28 @@ class UnpublishObject(Command):
         
         self.client.unpublish_object(src_container, src_object)
 
+@cli_command('sharing')
+class SharingObject(Command):
+    syntax = 'list users sharing objects with the user'
+    description = 'list user accounts sharing objects with the user'
+    
+    def add_options(self, parser):
+        parser.add_option('-l', action='store_true', dest='detail',
+                          default=False, help='show detailed output')
+        parser.add_option('-n', action='store', type='int', dest='limit',
+                          default=10000, help='show limited output')
+        parser.add_option('--marker', action='store', type='str',
+                          dest='marker', default=None,
+                          help='show output greater then marker')
+        
+    
+    def execute(self):
+        attrs = ['limit', 'marker']
+        args = self._build_args(attrs)
+        args['format'] = 'json' if self.detail else 'text'
+        
+        print_list(self.client.list_shared_by_others(**args))
+
 def print_usage():
     cmd = Command('', [])
     parser = cmd.parser
@@ -686,9 +701,9 @@ def print_usage():
     print '\nCommands:\n' + '\n'.join(sorted(commands))
 
 def print_dict(d, header='name', f=stdout, detail=True):
-    header = header in d and header or 'subdir'
+    header = header if header in d else 'subdir'
     if header and header in d:
-        f.write('%s\n' %d.pop(header))
+        f.write('%s\n' %d.pop(header).encode('utf8'))
     if detail:
         patterns = ['^x_(account|container|object)_meta_(\w+)$']
         patterns.append(patterns[0].replace('_', '-'))
@@ -717,24 +732,6 @@ def print_versions(data, f=stdout):
     for id, t in data['versions']:
         f.write('%s @ %s\n' % (str(id).rjust(30), datetime.fromtimestamp(t)))
 
-def _get_user():
-        try:
-            return os.environ['PITHOS_USER']
-        except KeyError:
-            return getuser()
-
-def _get_auth():
-        try:
-            return os.environ['PITHOS_AUTH']
-        except KeyError:
-            return '0000'
-
-def _get_server():
-    try:
-        return os.environ['PITHOS_SERVER']
-    except KeyError:
-        return DEFAULT_HOST
-
 def main():
     try:
         name = argv[1]
@@ -745,15 +742,14 @@ def main():
     
     cmd = cls(name, argv[2:])
     
-    cmd.execute(*cmd.args)
-    #try:
-    #    cmd.execute(*cmd.args)
-    #except TypeError, e:
-    #    cmd.parser.print_help()
-    #    exit(1)
-    #except Fault, f:
-    #    status = f.status and '%s ' % f.status or ''
-    #    print '%s%s' % (status, f.data)
+    try:
+        cmd.execute(*cmd.args)
+    except TypeError, e:
+        cmd.parser.print_help()
+        exit(1)
+    except Fault, f:
+        status = f.status and '%s ' % f.status or ''
+        print '%s%s' % (status, f.data)
 
 if __name__ == '__main__':
     main()