common.py 42.6 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
André Anjos's avatar
André Anjos committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.cmdline module of the BEAT platform.          #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################


'''Utility functions that are useful to all sub-commands'''

import os
import glob
import fnmatch
import difflib
import collections

import logging
logger = logging.getLogger(__name__)

import six
import oset
import termcolor
import simplejson

from beat.core import dataformat
from beat.core import database
from beat.core import library
from beat.core import plotter
from beat.core import algorithm
from beat.core import toolchain
from beat.core import experiment


TYPE_GLOB = {
        'dataformat': os.path.join('*', '*', '*.json'),
        'database': os.path.join('*', '*.json'),
        'library': os.path.join('*', '*', '*.json'),
        'algorithm': os.path.join('*', '*', '*.json'),
        'plotter': os.path.join('*', '*', '*.json'),
        'toolchain': os.path.join('*', '*', '*.json'),
        'experiment': os.path.join('*', '*', '*', '*', '*.json'),
        }


TYPE_FNMATCH = {
        'dataformat': os.path.splitext(TYPE_GLOB['dataformat'])[0],
        'database': os.path.splitext(TYPE_GLOB['database'])[0],
        'library': os.path.splitext(TYPE_GLOB['library'])[0],
        'algorithm': os.path.splitext(TYPE_GLOB['algorithm'])[0],
        'plotter': os.path.splitext(TYPE_GLOB['plotter'])[0],
        'toolchain': os.path.splitext(TYPE_GLOB['toolchain'])[0],
        'experiment': os.path.splitext(TYPE_GLOB['experiment'])[0],
        }


TYPE_VALIDATOR = {
        'dataformat': dataformat.DataFormat,
        'database': database.Database,
        'library': library.Library,
        'algorithm': algorithm.Algorithm,
        'plotter': plotter.Plotter,
        'toolchain': toolchain.Toolchain,
        'experiment': experiment.Experiment,
        }

TYPE_STORAGE = {
        'dataformat': dataformat.Storage,
        'database': database.Storage,
        'library': library.Storage,
        'algorithm': algorithm.Storage,
        'plotter': plotter.Storage,
        'toolchain': toolchain.Storage,
        'experiment': experiment.Storage,
        }

TYPE_PLURAL = {
        'dataformat': 'dataformats',
        'database': 'databases',
        'library': 'libraries',
        'algorithm': 'algorithms',
        'plotter': 'plotters',
        'toolchain': 'toolchains',
        'experiment': 'experiments',
        }


def recursive_rmdir_if_empty(path, stop_at):
  """Recursively removes empty directories until a certain top directory"""

  if not os.path.exists(path):
    recursive_rmdir_if_empty(os.path.dirname(path), stop_at)
    return
  if os.path.samefile(path, stop_at): return #stop
  if not os.listdir(path): #empty
    logger.info("removing empty directory `%s'...", path)
    os.rmdir(path)
    recursive_rmdir_if_empty(os.path.dirname(path), stop_at)
  return


class Selector(object):
  '''Keeps track of versions and fork status'''

  def __init__(self, prefix):

    self.prefix = prefix #the root of the directory
    self.path = os.path.join(self.prefix, '.beat', 'selected.json')

    status = False
    if os.path.exists(self.path): status = self.load()

    if not status:
      self.__version = {
              'dataformat': dict(),
              'database': dict(),
              'algorithm': dict(),
              'library': dict(),
              'toolchain': dict(),
              'experiment': dict(),
              }
      self.__fork = {
              'dataformat': dict(),
              'database': dict(),
              'algorithm': dict(),
              'library': dict(),
              'toolchain': dict(),
              'experiment': dict(),
              }


  def __enter__(self):
    '''Implements our context manager'''
    return self


  def __exit__(self, *exc):
    '''Implements our context manager'''
    self.save()


  def fork(self, type, src, dst):
    '''Registers that object ``dst`` is a fork of object ``src``'''

    logger.info("`%s/%s' is forked from `%s/%s'", TYPE_PLURAL[type], dst,
        TYPE_PLURAL[type], src)
    self.__fork[type][dst] = src


  def forked_from(self, type, name):
    '''Returns the name of the originating source object or ``None``'''

    return self.__fork[type].get(name)

  def version(self, type, src, dst):
    '''Registers that object ``dst`` is a new version of object ``src``'''

    logger.info("`%s/%s' is a new version of `%s/%s'", TYPE_PLURAL[type], dst,
        TYPE_PLURAL[type], src)
    self.__version[type][dst] = src


  def version_of(self, type, name):
    '''Returns the name of the originating version object or ``None``'''

    return self.__version[type].get(name)


  def delete(self, type, name):
    '''Forgets about an object that was being tracked'''

    if name in self.__fork[type]: del self.__fork[type][name]
    if name in self.__version[type]: del self.__version[type][name]


  def load(self):
    '''Loads contents from file'''

    try:
      with open(self.path, 'rt') as f: data = simplejson.load(f, object_pairs_hook=collections.OrderedDict)
    except simplejson.JSONDecodeError:
      logger.warn("invalid state file at `%s' - removing and re-starting...",
              self.path)
      from beat.core.utils import safe_rmfile
      safe_rmfile(self.path)
      return False

    self.__fork = data['fork']
    self.__version = data['version']
    return True


  def save(self):
    '''Saves contents to file'''

    dirname = os.path.dirname(self.path)
    if not os.path.exists(dirname): os.makedirs(dirname)
    data = {
            'fork': self.__fork,
            'version': self.__version,
           }
    with open(self.path, 'wt') as f: simplejson.dump(data, f, indent=2)


def retrieve_remote_list(webapi, type, fields):
  '''Utility function used by commands to retrieve a remote list of objects


  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    fields (list of str): A list of fields to retrieve from the remote server


  Returns:

    list: A list of dictionaries containing the ``name``, ``short_description``
    and ``hash`` of available remote objects.

  '''

  logger.debug("retrieving remote %s list...", TYPE_PLURAL[type])

  fields = '' if not fields else '?fields=%s' % ','.join(fields)

  url = '/api/v1/%s/%s' % (TYPE_PLURAL[type], fields)

  (status_code, content) = webapi.get(url)
  if status_code is None: return None

  if status_code != six.moves.http_client.OK:
    logger.error("failed to retrieve %s list from `%s' on behalf of `%s', " \
            "reason: %s", TYPE_PLURAL[type], webapi.platform, webapi.user,
            six.moves.http_client.responses[status_code])
    return None

  return simplejson.loads(content, object_pairs_hook=collections.OrderedDict)


def make_up_remote_list(webapi, type, requirements):
  '''Creates a list of downloadable objects from user requirements.

  This function can create a list of downloadable objects from user
  requirements. User requirements may point to valid object names (in which
  case these are returned unchanged) or partial object names, which are used to
  filter available remote resources. A list of fully resolved remote names
  respecting user restrictions is returned.


  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    requirements (list of str): A list of requirements that are used to filter
      (additively) the available (remote) objects.


  Returns:

    list: A list of valid object names matching user requirements and its
      order.

  '''

  candidates = retrieve_remote_list(webapi, type, ['name'])

  if not requirements: #special case, return all possible values
    if candidates is None: return None
    return [c['name'] for c in candidates]

  #othewise, we need to separate filters from full-names
  full_requirements = fnmatch.filter(requirements, TYPE_FNMATCH[type])
  short_requirements = [k for k in requirements if k not in full_requirements]

  retval = []

  if short_requirements:
    if candidates is None: return None
    retval = oset.oset()
    for name in short_requirements:
      retval |= oset.oset([k['name'] for k in candidates if k['name'].find(name) != -1])
    retval = list(retval)
    logger.info("search strings matched %d remote object(s)", len(retval))

  # note: if you specify a full-length requirement, we don't really care if it
  # is there or not. The final command will decide if it is an error.
  return retval + full_requirements


def display_remote_list(webapi, type):
  '''Implements a generic "list --remote" command

  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest, on behalf of a pre-configured user.

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  '''


  l = retrieve_remote_list(webapi, type, ['name', 'short_description'])
  if l is None: return 1

  for o in l:
    logger.info('%s/%s', TYPE_PLURAL[type], o['name'])
    if o['short_description']: logger.extra(2*' ' + o['short_description'])

  if len(l) != 1:
    logger.extra('%d %s found', len(l), TYPE_PLURAL[type])
  else:
    logger.extra('1 %s found' % type)

  return 0


def make_up_local_list(prefix, type, requirements):
  '''Creates a list of uploadable objects from user requirements.

  This function can create a list of uploadable objects from user requirements.
  User requirements may point to valid object names (in which case these are
  returned unchanged) or partial object names, which are used to filter
  available local resources. A list of fully resolved local names respecting
  user restrictions is returned.


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    requirements (list of str): A list of requirements that are used to filter
      (additively) the available (remote) objects.


  Returns:

    list: A list of strings, each with the relative name of an object belonging
      to a certain category and in the order prescribed by the user.

  '''

  root = os.path.join(prefix, TYPE_PLURAL[type])
  l = glob.glob(os.path.join(root, TYPE_GLOB[type]))
  candidates = [os.path.splitext(os.path.relpath(o, root))[0] for o in l]

  # adds hashed path structures
  lh = glob.glob(os.path.join(root, '*', '*', TYPE_GLOB[type]))
  lh = [os.path.splitext(os.path.relpath(k, root))[0] for k in lh]
  candidates += [os.path.join(*k.split(os.sep)[2:]) for k in lh]

  if not requirements: return candidates

  use_requirements = []
  for k in requirements: #remove leading plural-name
    if k.startswith(TYPE_PLURAL[type] + os.sep):
      use_requirements.append(k.replace(TYPE_PLURAL[type] + os.sep, ''))
    else:
      use_requirements.append(k)
  requirements = use_requirements

  full_requirements = fnmatch.filter(requirements, TYPE_FNMATCH[type])
  short_requirements = [k for k in requirements if k not in full_requirements]

  retval = oset.oset()
  for name in short_requirements:
    retval |= oset.oset([k for k in candidates if k.startswith(name)])

  # note: if you specify a full-length requirement, we don't really care if it
  # is there or not. The final command will decide if it is an error.
  return list(retval) + full_requirements


def display_local_list(prefix, type):
  '''Implements the local "list" command


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  '''

  names = make_up_local_list(prefix, type, [])

  for name in names:
    logger.info("%s/%s", TYPE_PLURAL[type], name)
    try:
      storage = TYPE_STORAGE[type](prefix, name)
      contents = simplejson.loads(storage.json.load(), object_pairs_hook=collections.OrderedDict)
      if 'description' in contents:
        logger.extra(2*' ' + contents['description'])
    except simplejson.JSONDecodeError:
      logger.warn(2*' ' + '(!) invalid JSON file')

  if len(names) != 1:
    logger.extra('%d %s found', len(names), TYPE_PLURAL[type])
  else:
    logger.extra('1 %s found' % type)

  return 0


def make_webapi(c):
  '''Instantiates an usable web-api proxy using the command-line configuration

  Parameters:

    c (object): The command-line configuration object, from which this function
      will extract the ``platform``, ``user`` and ``token`` parameters.


  Returns

    WebAPI: A valid web-api proxy instance

  '''

  if c.platform.startswith('django://'):

    # returns a Django RestFramework API client that looks like our WebAPI
    from rest_framework.test import APIClient
    from rest_framework.authtoken.models import Token

    class APIClientContext(APIClient):

      def __init__(self, platform, user, token, *args, **kwargs):

        self.platform = platform
        super(APIClientContext, self).__init__(*args, **kwargs)

        self.user = user
        self.token = token

        # sets-up authorization token on all requests, if user is set
        if self.user is not None:
          token = Token.objects.get(user__username=user)
          self.credentials(HTTP_AUTHORIZATION='Token ' + token.key)

      def is_anonymous(self):
        """Tells if the user has not set credentials for the platform"""
        return self.token is None

      def __enter__(self):
        return self

      def __exit__(self, *exc):
        pass

      def _message(self, type, url, data=None):
        if data: data = simplejson.dumps(data)
        retval = getattr(super(APIClientContext, self), type)(url, data,
                content_type='application/json')
        return (retval.status_code, retval.content)

      def get(self, url, data=None):
        return self._message('get', url, data)

      def put(self, url, data=None):
        return self._message('put', url, data)

      def post(self, url, data=None):
        return self._message('post', url, data)

      def delete(self, url, data=None):
        return self._message('delete', url, data)

    return APIClientContext(c.platform, c.user, c.token)

  else:
    # sets up our own client
    from .webapi import WebAPI
    return WebAPI(c.platform, c.user, c.token)


def check_one(prefix, type, name):
  """Implements object validation for a single, well-defined object


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    name (str): The name of the object, representing the unique relative path
      of the objects to check (e.g. ``user/integer/1``)

    klass (type): A python class that validates the object. It must accept the
      object

  """

  o = TYPE_VALIDATOR[type](prefix, name)

  if not o.valid:
    logger.info("%s/%s [invalid]", TYPE_PLURAL[type], name)
    for e in o.errors: logger.warn('  * %s', e)
    return 1

  else:
    logger.info("%s/%s [ok]", TYPE_PLURAL[type], name)
    return 0


def check(prefix, type, names):
  """Implements object validation


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (list of str): A list of strings, each representing the unique
      relative path of the objects to check. If the list is empty, then we
      check all available objects of a given type.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  names = make_up_local_list(prefix, type, names)
  return sum([check_one(prefix, type, name) for name in names])


def fetch_object(webapi, type, name, fields):
  """Retrieves a single well-known object from the server

  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    name (str): A string defining the name of the object to retrieve

    fields (list of str): A list of fields to retrieve from the remote server


  Returns:

    dict: A dictionary containg the object contents

  """

  fields = '?object_format=string&fields=%s' % ','.join(fields)
  url = '/api/v1/%s/%s/%s' % (TYPE_PLURAL[type], name, fields)

  (status_code, content) = webapi.get(url)
  if status_code is None: return None

  if status_code != six.moves.http_client.OK:
    logger.error("failed to retrieve %s from `%s' with secret token, " \
            "reason: %s", type, webapi.platform,
            six.moves.http_client.responses[status_code])
    return None

  return simplejson.loads(content, object_pairs_hook=collections.OrderedDict)


def pull(webapi, prefix, type, names, fields, force, indentation):
  """Copies objects from the server to the local prefix


  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (list of str): A list of strings, each representing the unique
      relative path of the objects to retrieve or a list of usernames from
      which to retrieve objects. If the list is empty, then we pull all
      available objects of a given type. If no user is set, then pull all
      public objects of a given type.

    fields (list of str): A list of strings, each defining one field that
      **must** be downloaded from the web-server for a given object of the
      current type and passed, unchanged to the storage ``save()`` method. For
      example, for toolchains, this value shall be ``['declaration']``. For
      algorithms, it shall be ``['declaration', 'code']``.

    force (bool): If set to ``True``, then overwrites local changes with the
      remotely retrieved copies.

    indentation (int): The indentation level, useful if this function is called
      recursively while downloading different object types. This is normally
      set to ``0`` (zero).


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

    list: A list of strings containing the names of objects successfuly
      downloaded or which were already present on the current installation (if
      the user has chosen not to ``--force`` the override), in the order of
      their download.

  """

  names = make_up_remote_list(webapi, type, names)
  if not names: return 1, []
  indent = indentation * ' '
  available = oset.oset()

  status = 0

  for name in names:
    storage = TYPE_STORAGE[type](prefix, name)
    if storage.exists() and not force: #exists locally, force not set
      logger.extra("%sskipping download of `%s/%s' (exists locally)", indent,
              TYPE_PLURAL[type], name)
      available.add(name)
      continue
    else:
      logger.info("%sretrieving `%s/%s'...", indent, TYPE_PLURAL[type], name)
      data = fetch_object(webapi, type, name, fields)
      if data is None:
        status += 1 #error
        continue
      storage.save(**data)
      available.add(name)

  return status, list(available)


def diff(webapi, prefix, type, name, fields):
  """Shows the differences between two objects, for each of the fields


  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    name (str): A string defining the name of the object to calculate
      differences from.

    fields (list of str): A list of strings, each defining one field that
      **must** be downloaded from the web-server for a given object of the
      current type.  For example, for toolchains, this value shall be
      ``['declaration']``. For algorithms, it shall be ``['declaration',
      'code']``.

  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  extension = {
          'code': '.py',
          'declaration': '.json',
          'description': '.rst',
          }

  def _eval_diff(remote, local, ext):
    '''Calculates differences between two string buffers'''
    return difflib.unified_diff(remote.split('\n'), local.split('\n'),
            os.path.join('remote', type, name + ext),
            os.path.join('local', type, name + ext))


  def _show_diff(diffs):
    '''Displays difference display between two string buffers'''

    for line in diffs:
      if line.startswith('+'): termcolor.cprint(line, 'green')
      elif line.startswith('-'): termcolor.cprint(line, 'red')
      else: print(line)


  storage = TYPE_STORAGE[type](prefix, name)
  local = storage.load() #may also return a tuple, depending on the type
  remote = fetch_object(webapi, type, name, fields)
  if remote is None: return 1
  if 'declaration' in remote and \
          not isinstance(remote['declaration'], six.string_types):
    remote['declaration'] = simplejson.dumps(remote['declaration'], indent=4)

  local = dict(zip(fields, local)) #``local`` should have the same size

  # replaces None entries with an empty string so these are comparable
  for key in local:
    local[key] = local[key] if local[key] is not None else ''

  for field in fields:
    diffs = _eval_diff(remote[field], local[field], extension[field])
    if diffs:
      logger.info("differences for `%s' of `%s/%s':", field, TYPE_PLURAL[type],
          name)
      _show_diff(diffs)
    else:
      logger.info("no differences for `%s' of `%s/%s'", field,
          TYPE_PLURAL[type], name)

  return 0


def create(prefix, type, names):
  """Creates an empty object of a certain type under the given name


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (str): A string defining the names of the objects to create.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  status = 0

  for name in names:

    storage = TYPE_STORAGE[type](prefix, name)

    if storage.exists():
      logger.error("`%s/%s' already exists - will *not* overwrite",
          TYPE_PLURAL[type], name)
      status += 1

    obj = TYPE_VALIDATOR[type](prefix, data=None) #the default object
    storage = TYPE_STORAGE[type](prefix, name)
    obj.write(storage)

  return status


def copy(prefix, type, src, dst):
  """Creates a new object by copying another object of the same type.

  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    src (str): A string defining the name of the object to fork a new version
      from.

    dst (str): A string defining the name of the object to fork to.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  src_storage = TYPE_STORAGE[type](prefix, src)
  if not src_storage.exists():
    logger.error("source `%s/%s' does not exist", TYPE_PLURAL[type], src)
    return 1

  dst_storage = TYPE_STORAGE[type](prefix, dst)
  if dst_storage.exists():
    logger.error("destination `%s/%s' already exists", TYPE_PLURAL[type], dst)
    return 1

  dst_storage.save(*src_storage.load())

  return 0


def new_version(prefix, type, src):
  """Creates a new object by copying another object of the same type.

  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    src (str): A string defining the name of the object to fork a new version
      from.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  with Selector(prefix) as selector:
    src_storage = TYPE_STORAGE[type](prefix, src)
    dst = os.sep.join(src.split(os.sep)[:-1] + [''])
    dst += str(int(src_storage.version) + 1)
    dst_storage = TYPE_STORAGE[type](prefix, dst)

    if dst_storage.exists():
      logger.info("A representation for %s `%s' already exists - not " \
          "overwriting", type, dst)
    else:
      status = copy(prefix, type, src, dst)
      if status != 0: return status #error

    selector.version(type, src, dst)
    return 0


def fork(prefix, type, src, dst):
  """Creates a new object by forking another object of the same type.


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    src (str): A string defining the name of the object to fork from.

    dst (str): A string defining the name of the object to fork to.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  with Selector(prefix) as selector:
    dst_storage = TYPE_STORAGE[type](prefix, dst)

    if dst_storage.exists():
      logger.info("A representation for %s `%s' already exists - not " \
          "overwriting", type, dst)
    else:
      status = copy(prefix, type, src, dst)
      if status != 0: return status #error

    selector.fork(type, src, dst) #mark forking status
    return 0


def delete_local(prefix, type, names):
  """Deletes a local object of a given type

  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (list of str): A list of strings, each representing the unique
      relative path of the objects to retrieve or a list of usernames from
      which to delete.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  status = 0

  for name in names:

    storage = TYPE_STORAGE[type](prefix, name)
    if not storage.exists():
      logger.error("`%s/%s' does not exist", TYPE_PLURAL[type], name)
      status += 1

    with Selector(prefix) as selector:
      selector.delete(type, name) #unset forking status and others

    storage.remove()

  return status


def delete_remote(webapi, type, names):
  """Deletes a remote object of a given type

  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (list of str): A list of strings, each representing the unique
      relative path of the objects to retrieve or a list of usernames from
      which to delete.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  status = 0

  for name in names:

    logger.debug("deleting %s/%s...", TYPE_PLURAL[type], name)

    url = '/api/v1/%s/%s/' % (TYPE_PLURAL[type], name)

    (status_code, content) = webapi.delete(url)
    if status_code is None:
      status += 1
      continue

    if status_code != six.moves.http_client.NO_CONTENT:
      logger.error("failed to delete `%s' from `%s' on behalf of `%s', " \
              "reason: %s", type, webapi.platform, webapi.user,
              six.moves.http_client.responses[status_code])
      status += 1

  return status


def status(webapi, prefix, type):
  """Flags objects which have changed


  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

    list: A list of objects that have local modifications and should be pushed
      remotely, eventually.

  """

  remote = retrieve_remote_list(webapi, type,
          ['name', 'hash', 'description', 'creation_date'])
  if remote is None: return 1, []
  remote = collections.OrderedDict([(k['name'], k) for k in remote])

  local = make_up_local_list(prefix, type, [])
  retval = collections.OrderedDict()

  logger.extra('legend: [+] definition; [d] docs; [*] both; [l] only local; [r] only remote')

  for key in remote:
    if key in local:

      storage = TYPE_STORAGE[type](prefix, key)
      contents = storage.hash() != remote[key]['hash']
      local_doc = storage.doc.load() if storage.doc.exists() else ''
      doc = local_doc != remote[key]['description']

      if contents:
        if doc:
          symbol = '*' #both contents and doc changed
        else:
          symbol = '+' #only contents changed
      else:
        if doc:
          symbol = 'd' #only docs changed
        else:
          symbol = ''  #no changes

      if symbol:
        logger.info('[%s] %s/%s (@%s)', symbol, TYPE_PLURAL[type], key,
                remote[key]['creation_date'])
      else:
        logger.extra('    %s/%s', TYPE_PLURAL[type], key)

      retval[key] = symbol

  # whatever is not listed remotely
  for key in set(local) - set(remote.keys()):
    logger.info('[l] %s/%s', TYPE_PLURAL[type], key)
    retval[key] = 'l'

  # whatever is not listed locally
  for key in set(remote.keys()) - set(local):
    logger.extra('[r] %s/%s (@%s)', TYPE_PLURAL[type], key,
        remote[key]['creation_date'])

  return 0, retval


def push(webapi, prefix, type, names, fields, mappings, force, dry_run,
        indentation):
  """Copies objects to the server from the local prefix


  Parameters:

    webapi (object): An instance of our WebAPI class, prepared to access the
      BEAT server of interest

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (list of str): A list of strings, each representing the unique
      relative path of the objects to push or a filtering criteria for local
      objects. If the list is empty, then we push all available objects of a
      given type, which have changes. If no user is set, then an error is
      raised.

    fields (list of str): A list of strings, each defining one field that
      **must** be uploaded to the web-server for a given object of the current
      type. For example, for toolchains, this value shall be ``['declaration',
      'description']``. For algorithms, it shall be ``['declaration', 'code',
      'description']``.

    mappings (dict): A dictionary containing mappings from the stock field
      names to equivalents which are expected by our web interface. This field
      is required by experiments only.

    force (bool): If set to ``True``, then push local changes even if no change
      is detected on the local copy.

    dry_run (bool): If set to ``True``, then only prints what it would do
      instead of doing it.

    indentation (int): The indentation level, useful if this function is called
      recursively while downloading different object types. This is normally
      set to ``0`` (zero).


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

    list: A list of strings containing the names of objects successfuly
      uploaded or which were already present on the remote server (if
      the user has chosen not to ``--force`` the override), in the order of
      their upload.

  """

  if webapi.is_anonymous():
    logger.error('cannot anonymously push objects, set your access token')
    return 1

  retval, candidates = status(webapi, prefix, type)
  if retval: return retval

  if names: #apply filtering conditions
    full_requirements = fnmatch.filter(names, TYPE_FNMATCH[type])
    short_requirements = [k for k in names if k not in full_requirements]

    # check full-length requirements
    filtered = collections.OrderedDict()
    for k in full_requirements:
      if k not in candidates:
        logger.error('%s/%s is not available locally', TYPE_PLURAL[type], k)
        return 1
      filtered[k] = candidates[k]

    # check short requirements
    for k in short_requirements:
      for c in candidates:
        if c.startswith(k): filtered[c] = candidates[c]

    candidates = filtered

  if not force: #filter again, if no local changes
    candidates = collections.OrderedDict([(k, v) for k, v in candidates.items() if v])

  if not candidates:
    logger.warn('No new candidates for upload were found')
    return 0

  # flush all final candidates
  for k, v in candidates.items():

    splits = k.split('/')
    if webapi.user is None and len(splits) >= 3: #excludes databases
      # set-up user using the object's leading path
      webapi.user = k.split('/')[0]
      logger.debug("The command-line option for the user was not set, " \
          "so I'm overriding it with the object's leading path (`%s')",
          webapi.user)

    logger.info('pushing %s/%s [%s]', TYPE_PLURAL[type], k, v)
    storage = TYPE_STORAGE[type](prefix, k)
    data = storage.load() #returns a named tuple
    message = {}
    for f in fields:
      if hasattr(data, f): message[f] = getattr(data, f)
      elif hasattr(storage, f): message[f] = getattr(storage, f)
    if 'description' in message and not message['description']:
      del message['description']

    # apply message mappings
    for key, value in mappings.items():
      message[value] = message[key]
      del message[key]

    # fills-in fork status
    with Selector(prefix) as selector:
      fork = selector.forked_from(type, k)
      if fork: message['fork_of'] = fork
      version = selector.version_of(type, k)
      if version: message['previous_version'] = version

    if dry_run: continue #don't send the data

    # if the user was set on the commandline, use it
    if webapi.user is None:
      url = '/api/v1/%s/' % (TYPE_PLURAL[type],)
    else:
      url = '/api/v1/%s/%s/' % (TYPE_PLURAL[type], webapi.user)

    # sends the data
    if v == 'l': #POST (new object)

      (status_code, response) = webapi.post(url, data=message)

      if status_code != six.moves.http_client.CREATED:
        if response:
          logger.error("Failed to create %s on the server, reason: %s",
                  type, response)
        elif status_code is not None:
          logger.error("Failed to create %s on the server, reason: %s",
                  type, six.moves.http_client.responses[status_code])
        return 1
      else:
        logger.info("Successfuly created `%s'", k)

    else: #PUT (update)

      (status_code, response) = webapi.put(url, data=message)

      if status_code != six.moves.http_client.NO_CONTENT:
        if response:
          logger.error("Failed to modify %s on the server, reason: %s",
                  type, response)
        elif status_code is not None:
          logger.error("Failed to modify %s on the server, reason: %s",
                  type, six.moves.http_client.responses[status_code])
        return 1
      else:
        logger.info("Successfuly updated `%s'", k)

  return 0


def dot_diagram(prefix, type, names, path, formats):
  """Dumps DOT (Graphviz) diagrams of the given toolchains/experiments


  Parameters:

    prefix (str): A string representing the root of the path in which the user
      objects are stored

    type (str): One of ``database``, ``dataformat``, ``algorithm``,
      ``toolchain`` or ``experiment``.

    names (list of str): A list of strings, each representing the unique
      relative path of the objects to push or a filtering criteria for local
      objects. If the list is empty, then we push all available objects of a
      given type, which have changes. If no user is set, then an error is
      raised.

    path (str): The directory to use for dumping the drawings. The filenames
      assigned correspond to the full object name. If not set, the default is
      to write on the current directory.

    formats (list of str): A list of formats to dump. If not set or set to an
      empty value, then dump dot/graphviz and png formats.


  Returns:

    int: Indicating the exit status of the command, to be reported back to the
      calling process. This value should be zero if everything works OK,
      otherwise, different than zero (POSIX compliance).

  """

  if not formats: formats = ['dot', 'png']

  path = path or os.curdir
  if not os.path.exists(path):
    logger.info("creating directory `%s'...", path)
    os.makedirs(path)

  names = make_up_local_list(prefix, type, names)

  for name in names:

    obj = TYPE_VALIDATOR[type](prefix, name)

    if not hasattr(obj, 'dot_diagram'):
      logger.error("%s do not support DOT/Graphviz diagram output",
          TYPE_PLURAL[type])
      return 1

    if not obj.valid:
      logger.warn("%s/%s is not valid - skipping it", TYPE_PLURAL[type], name)
      continue

    try:
      diagram = obj.dot_diagram()
    except Exception as e:
      logger.warn("%s/%s cannot be drawn: %s - skipping it", TYPE_PLURAL[type],
          name, e)
      continue

    destfile = os.path.join(path, '%s' % TYPE_PLURAL[type], obj.name)

    for k in formats:
      if k == 'dot':
        logger.info("%s/%s -> %s.%s", TYPE_PLURAL[type], name, destfile, k)
        diagram.save(destfile + '.dot')
      else:
        logger.info("%s/%s -> %s.%s", TYPE_PLURAL[type], name, destfile, k)
        diagram.format = k
        diagram.render(destfile, cleanup=True)

  return 0


def stringify(value):
  '''Creates a string representation of a baseformat represented as a dict

  The input variable ``value`` is modified in-place.

  Parameters:

    value (dict): A dictionary representing the baseformat object, obtained as
      with :py:meth:`beat.core.baseformat.baseformat.as_dict`, that represents
      the object one seeks to represent in string format.


  Returns

    dict: Modifies the input variable ``value`` in-place, but also returns it.

  '''

  if isinstance(value, list):
    if len(value) > 10:
      if isinstance(value[0], dict) or isinstance(value[0], list):
        return map(stringify, value[0:4]) + ['...'] + \
                map(stringify, value[-4:]) + \
                ['BEAT_LIST_SIZE(%d elements)BEAT_LIST_SIZE' % len(value)]

      reduced = 'BEAT_LIST_DELIMITER['
      for v in value[0:4]: reduced += str(v) + ', '
      reduced += '...'
      for v in value[-4:]: reduced += ', ' + str(v)
      reduced += ' (%d elements)]BEAT_LIST_DELIMITER' % len(value)
      return reduced
    elif (len(value) > 0) and \
            (isinstance(value[0], list) or isinstance(value[0], dict)):
      return map(stringify, value)

  elif isinstance(value, dict):
    for name, value2 in value.items():
      value[name] = stringify(value2)

  return value