Revision 1757c616 kamaki/cli/commands/pithos.py

b/kamaki/cli/commands/pithos.py
31 31
# interpreted as representing official policies, either expressed
32 32
# or implied, of GRNET S.A.command
33 33

  
34
from sys import stdout
35 34
from time import localtime, strftime
36 35
from os import path, makedirs, walk
37 36
from io import StringIO
......
41 40
from kamaki.cli.errors import raiseCLIError, CLISyntaxError, CLIBaseUrlError
42 41
from kamaki.cli.utils import (
43 42
    format_size, to_bytes, print_dict, print_items, pager, bold, ask_user,
44
    get_path_size, print_json, guess_mime_type)
43
    get_path_size, guess_mime_type)
45 44
from kamaki.cli.argument import FlagArgument, ValueArgument, IntArgument
46 45
from kamaki.cli.argument import KeyValueArgument, DateArgument
47 46
from kamaki.cli.argument import ProgressBarArgument
......
58 57

  
59 58
# Argument functionality
60 59

  
61
class DelimiterArgument(ValueArgument):
62
    """
63
    :value type: string
64
    :value returns: given string or /
65
    """
66

  
67
    def __init__(self, caller_obj, help='', parsed_name=None, default=None):
68
        super(DelimiterArgument, self).__init__(help, parsed_name, default)
69
        self.caller_obj = caller_obj
70

  
71
    @property
72
    def value(self):
73
        if self.caller_obj['recursive']:
74
            return '/'
75
        return getattr(self, '_value', self.default)
76

  
77
    @value.setter
78
    def value(self, newvalue):
79
        self._value = newvalue
80

  
81 60

  
82 61
class SharingArgument(ValueArgument):
83 62
    """Set sharing (read and/or write) groups
......
362 341
        enum=FlagArgument('Enumerate results', '--enumerate')
363 342
    )
364 343

  
365
    def print_objects(self, object_list, out=stdout):
366
        if self['json_output']:
367
            print_json(object_list, out=out)
368
            return
369
        out = StringIO() if self['more'] else stdout
344
    def print_objects(self, object_list):
370 345
        for index, obj in enumerate(object_list):
371 346
            if self['exact_match'] and self.path and not (
372 347
                    obj['name'] == self.path or 'content_type' in obj):
......
384 359
                size = format_size(obj['bytes'])
385 360
                pretty_obj['bytes'] = '%s (%s)' % (obj['bytes'], size)
386 361
            oname = obj['name'] if self['more'] else bold(obj['name'])
387
            prfx = ('%s%s. ' % (empty_space, index)) if self['enum'] else ''
362
            prfx = (
363
                '%s%s. ' % (empty_space, index)) if self['enum'] else ''
388 364
            if self['detail']:
389
                out.writelines(u'%s%s\n' % (prfx, oname))
390
                print_dict(pretty_obj, exclude=('name'), out=out)
391
                out.writelines(u'\n')
365
                self._out.writelines(u'%s%s\n' % (prfx, oname))
366
                print_dict(pretty_obj, exclude=('name'), out=self._out)
367
                self._out.writelines(u'\n')
392 368
            else:
393 369
                oname = u'%s%9s %s' % (prfx, size, oname)
394 370
                oname += u'/' if isDir else u''
395
                out.writelines(oname + u'\n')
396
        if self['more']:
397
            pager(out.getvalue())
371
                self._out.writelines(oname + u'\n')
398 372

  
399
    def print_containers(self, container_list, out=stdout):
400
        if self['json_output']:
401
            print_json(container_list, out=out)
402
            return
403
        out = StringIO() if self['more'] else stdout
373
    def print_containers(self, container_list):
404 374
        for index, container in enumerate(container_list):
405 375
            if 'bytes' in container:
406 376
                size = format_size(container['bytes'])
......
409 379
                self['more']) else bold(container['name'])
410 380
            cname = u'%s%s' % (prfx, _cname)
411 381
            if self['detail']:
412
                out.writelines(cname + u'\n')
382
                self._out.writelines(cname + u'\n')
413 383
                pretty_c = container.copy()
414 384
                if 'bytes' in container:
415 385
                    pretty_c['bytes'] = '%s (%s)' % (container['bytes'], size)
416
                print_dict(pretty_c, exclude=('name'), out=out)
417
                out.writelines(u'\n')
386
                print_dict(pretty_c, exclude=('name'), out=self._out)
387
                self._out.writelines(u'\n')
418 388
            else:
419 389
                if 'count' in container and 'bytes' in container:
420
                    out.writelines(u'%s (%s, %s objects)\n' % (
390
                    self._out.writelines(u'%s (%s, %s objects)\n' % (
421 391
                        cname, size, container['count']))
422 392
                else:
423
                    out.writelines(cname + '\n')
424
        if self['more']:
425
            pager(out.getvalue())
393
                    self._out.writelines(cname + '\n')
426 394

  
427 395
    @errors.generic.all
428 396
    @errors.pithos.connection
429 397
    @errors.pithos.object_path
430 398
    @errors.pithos.container
431 399
    def _run(self):
400
        files, prnt = None, None
432 401
        if self.container is None:
433 402
            r = self.client.account_get(
434 403
                limit=False if self['more'] else self['limit'],
......
437 406
                if_unmodified_since=self['if_unmodified_since'],
438 407
                until=self['until'],
439 408
                show_only_shared=self['shared'])
440
            files = self._filter_by_name(r.json)
441
            self._print(files, self.print_containers)
409
            files, prnt = self._filter_by_name(r.json), self.print_containers
442 410
        else:
443 411
            prefix = (self.path and not self['name']) or self['name_pref']
444 412
            r = self.client.container_get(
......
452 420
                until=self['until'],
453 421
                meta=self['meta'],
454 422
                show_only_shared=self['shared'])
455
            files = self._filter_by_name(r.json)
456
            self._print(files, self.print_objects)
423
            files, prnt = self._filter_by_name(r.json), self.print_objects
424
        if self['more']:
425
            outbu, self._out = self._out, StringIO()
426
        try:
427
            if self['json_output']:
428
                self._print(files)
429
            else:
430
                prnt(files)
431
        finally:
432
            if self['more']:
433
                pager(self._out.getvalue())
434
                self._out = outbu
457 435

  
458 436
    def main(self, container____path__=None):
459 437
        super(self.__class__, self)._run(container____path__)
......
1216 1194
    def _run(self):
1217 1195
        self.client.download_object(
1218 1196
            self.path,
1219
            stdout,
1197
            self._out,
1220 1198
            range_str=self['range'],
1221 1199
            version=self['object_version'],
1222 1200
            if_match=self['if_match'],
......
1399 1377
            from threading import activeCount, enumerate as activethreads
1400 1378
            timeout = 0.5
1401 1379
            while activeCount() > 1:
1402
                stdout.write('\nCancel %s threads: ' % (activeCount() - 1))
1403
                stdout.flush()
1380
                self._out.write('\nCancel %s threads: ' % (activeCount() - 1))
1381
                self._out.flush()
1404 1382
                for thread in activethreads():
1405 1383
                    try:
1406 1384
                        thread.join(timeout)
1407
                        stdout.write('.' if thread.isAlive() else '*')
1385
                        self._out.write('.' if thread.isAlive() else '*')
1408 1386
                    except RuntimeError:
1409 1387
                        continue
1410 1388
                    finally:
1411
                        stdout.flush()
1389
                        self._out.flush()
1412 1390
                        timeout += 0.1
1413 1391
            print('\nDownload canceled by user')
1414 1392
            if local_path is not None:
......
1484 1462
        yes=FlagArgument('Do not prompt for permission', '--yes'),
1485 1463
        recursive=FlagArgument(
1486 1464
            'empty dir or container and delete (if dir)',
1487
            ('-R', '--recursive'))
1465
            ('-R', '--recursive')),
1466
        delimiter=ValueArgument(
1467
            'delete objects prefixed with <object><delimiter>', '--delimiter')
1488 1468
    )
1489 1469

  
1490
    def __init__(self, arguments={}, auth_base=None, cloud=None):
1491
        super(self.__class__, self).__init__(arguments,  auth_base, cloud)
1492
        self['delimiter'] = DelimiterArgument(
1493
            self,
1494
            parsed_name='--delimiter',
1495
            help='delete objects prefixed with <object><delimiter>')
1496

  
1497 1470
    @errors.generic.all
1498 1471
    @errors.pithos.connection
1499 1472
    @errors.pithos.container
......
1504 1477
                    'Delete %s:%s ?' % (self.container, self.path)):
1505 1478
                self._optional_output(self.client.del_object(
1506 1479
                    self.path,
1507
                    until=self['until'], delimiter=self['delimiter']))
1480
                    until=self['until'],
1481
                    delimiter='/' if self['recursive'] else self['delimiter']))
1508 1482
            else:
1509 1483
                print('Aborted')
1510 1484
        elif self.container:
......
1514 1488
                ask_msg = 'Delete container'
1515 1489
            if self['yes'] or ask_user('%s %s ?' % (ask_msg, self.container)):
1516 1490
                self._optional_output(self.client.del_container(
1517
                    until=self['until'], delimiter=self['delimiter']))
1491
                    until=self['until'],
1492
                    delimiter='/' if self['recursive'] else self['delimiter']))
1518 1493
            else:
1519 1494
                print('Aborted')
1520 1495
        else:
......
1613 1588
    """
1614 1589

  
1615 1590

  
1616
def print_permissions(permissions_dict, out=stdout):
1591
def print_permissions(permissions_dict, out):
1617 1592
    expected_keys = ('read', 'write')
1618 1593
    if set(permissions_dict).issubset(expected_keys):
1619 1594
        print_dict(permissions_dict, out=out)
......
2069 2044
        self._run()
2070 2045

  
2071 2046

  
2072
def version_print(versions, out=stdout):
2047
def version_print(versions, out):
2073 2048
    print_items(
2074 2049
        [dict(id=vitem[0], created=strftime(
2075 2050
            '%d-%m-%Y %H:%M:%S',

Also available in: Unified diff