/
__init__.py
1509 lines (1292 loc) · 50.2 KB
/
__init__.py
1
2
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
# -*- coding: utf-8 -*-
"""
Utility functions used systemwide.
"""
from __future__ import absolute_import
import binascii
import collections
import errno
import grp
import importlib
import json
import logging
import os
import random
import re
import shutil
import smtplib
import stat
import string
import sys
import tempfile
import threading
import time
from datetime import datetime
from hashlib import md5
from os.path import relpath
from xml.etree import ElementInclude, ElementTree
from xml.etree.ElementTree import ParseError
from six import binary_type, iteritems, PY3, string_types, text_type
from six.moves import email_mime_text, email_mime_multipart, xrange, zip
from six.moves.urllib import parse as urlparse
from six.moves.urllib import request as urlrequest
try:
import docutils.core as docutils_core
import docutils.writers.html4css1 as docutils_html4css1
except ImportError:
docutils_core = None
docutils_html4css1 = None
from .inflection import English, Inflector
from .path import safe_contains, safe_makedirs, safe_relpath # noqa: F401
inflector = Inflector(English)
if PY3:
def list_map(f, input):
return list(map(f, input))
else:
list_map = map
log = logging.getLogger(__name__)
_lock = threading.RLock()
CHUNK_SIZE = 65536 # 64k
DATABASE_MAX_STRING_SIZE = 32768
DATABASE_MAX_STRING_SIZE_PRETTY = '32K'
gzip_magic = '\037\213'
bz2_magic = 'BZh'
DEFAULT_ENCODING = os.environ.get('GALAXY_DEFAULT_ENCODING', 'utf-8')
NULL_CHAR = '\000'
BINARY_CHARS = [ NULL_CHAR ]
def remove_protocol_from_url( url ):
""" Supplied URL may be null, if not ensure http:// or https://
etc... is stripped off.
"""
if url is None:
return url
# We have a URL
if url.find( '://' ) > 0:
new_url = url.split( '://' )[1]
else:
new_url = url
return new_url.rstrip( '/' )
def is_binary( value, binary_chars=None ):
"""
File is binary if it contains a null-byte by default (e.g. behavior of grep, etc.).
This may fail for utf-16 files, but so would ASCII encoding.
>>> is_binary( string.printable )
False
>>> is_binary( '\\xce\\x94' )
False
>>> is_binary( '\\000' )
True
"""
if binary_chars is None:
binary_chars = BINARY_CHARS
for binary_char in binary_chars:
if binary_char in value:
return True
return False
def is_uuid( value ):
"""
This method returns True if value is a UUID, otherwise False.
>>> is_uuid( "123e4567-e89b-12d3-a456-426655440000" )
True
>>> is_uuid( "0x3242340298902834" )
False
"""
uuid_re = re.compile( "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" )
if re.match( uuid_re, str( value ) ):
return True
else:
return False
def directory_hash_id( id ):
"""
>>> directory_hash_id( 100 )
['000']
>>> directory_hash_id( "90000" )
['090']
>>> directory_hash_id("777777777")
['000', '777', '777']
>>> directory_hash_id("135ee48a-4f51-470c-ae2f-ce8bd78799e6")
['1', '3', '5']
"""
s = str( id )
l = len( s )
# Shortcut -- ids 0-999 go under ../000/
if l < 4:
return [ "000" ]
if not is_uuid(s):
# Pad with zeros until a multiple of three
padded = ( ( 3 - len( s ) % 3 ) * "0" ) + s
# Drop the last three digits -- 1000 files per directory
padded = padded[:-3]
# Break into chunks of three
return [ padded[ i * 3:(i + 1 ) * 3 ] for i in range( len( padded ) // 3 ) ]
else:
# assume it is a UUID
return list(iter(s[0:3]))
def get_charset_from_http_headers( headers, default=None ):
rval = headers.get('content-type', None )
if rval and 'charset=' in rval:
rval = rval.split('charset=')[-1].split(';')[0].strip()
if rval:
return rval
return default
def synchronized(func):
"""This wrapper will serialize access to 'func' to a single thread. Use it as a decorator."""
def caller(*params, **kparams):
_lock.acquire(True) # Wait
try:
return func(*params, **kparams)
finally:
_lock.release()
return caller
def file_iter(fname, sep=None):
"""
This generator iterates over a file and yields its lines
splitted via the C{sep} parameter. Skips empty lines and lines starting with
the C{#} character.
>>> lines = [ line for line in file_iter(__file__) ]
>>> len(lines) != 0
True
"""
for line in open(fname):
if line and line[0] != '#':
yield line.split(sep)
def file_reader( fp, chunk_size=CHUNK_SIZE ):
"""This generator yields the open fileobject in chunks (default 64k). Closes the file at the end"""
while 1:
data = fp.read(chunk_size)
if not data:
break
yield data
fp.close()
def unique_id(KEY_SIZE=128):
"""
Generates an unique id
>>> ids = [ unique_id() for i in range(1000) ]
>>> len(set(ids))
1000
"""
random_bits = text_type(random.getrandbits(KEY_SIZE)).encode("UTF-8")
return md5(random_bits).hexdigest()
def parse_xml( fname ):
"""Returns a parsed xml tree"""
# handle deprecation warning for XMLParsing a file with DOCTYPE
class DoctypeSafeCallbackTarget( ElementTree.TreeBuilder ):
def doctype( *args ):
pass
tree = ElementTree.ElementTree()
try:
root = tree.parse( fname, parser=ElementTree.XMLParser( target=DoctypeSafeCallbackTarget() ) )
except ParseError:
log.exception("Error parsing file %s", fname)
raise
ElementInclude.include( root )
return tree
def parse_xml_string(xml_string):
tree = ElementTree.fromstring(xml_string)
return tree
def xml_to_string( elem, pretty=False ):
"""Returns a string from an xml tree"""
if pretty:
elem = pretty_print_xml( elem )
try:
return ElementTree.tostring( elem )
except TypeError as e:
# we assume this is a comment
if hasattr( elem, 'text' ):
return "<!-- %s -->\n" % ( elem.text )
else:
raise e
def xml_element_compare( elem1, elem2 ):
if not isinstance( elem1, dict ):
elem1 = xml_element_to_dict( elem1 )
if not isinstance( elem2, dict ):
elem2 = xml_element_to_dict( elem2 )
return elem1 == elem2
def xml_element_list_compare( elem_list1, elem_list2 ):
return [ xml_element_to_dict( elem ) for elem in elem_list1 ] == [ xml_element_to_dict( elem ) for elem in elem_list2 ]
def xml_element_to_dict( elem ):
rval = {}
if elem.attrib:
rval[ elem.tag ] = {}
else:
rval[ elem.tag ] = None
sub_elems = list( elem )
if sub_elems:
sub_elem_dict = dict()
for sub_sub_elem_dict in map( xml_element_to_dict, sub_elems ):
for key, value in iteritems(sub_sub_elem_dict):
if key not in sub_elem_dict:
sub_elem_dict[ key ] = []
sub_elem_dict[ key ].append( value )
for key, value in iteritems(sub_elem_dict):
if len( value ) == 1:
rval[ elem.tag ][ key ] = value[0]
else:
rval[ elem.tag ][ key ] = value
if elem.attrib:
for key, value in iteritems(elem.attrib):
rval[ elem.tag ][ "@%s" % key ] = value
if elem.text:
text = elem.text.strip()
if text and sub_elems or elem.attrib:
rval[ elem.tag ][ '#text' ] = text
else:
rval[ elem.tag ] = text
return rval
def pretty_print_xml( elem, level=0 ):
pad = ' '
i = "\n" + level * pad
if len( elem ):
if not elem.text or not elem.text.strip():
elem.text = i + pad + pad
if not elem.tail or not elem.tail.strip():
elem.tail = i
for e in elem:
pretty_print_xml( e, level + 1 )
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and ( not elem.tail or not elem.tail.strip() ):
elem.tail = i + pad
return elem
def get_file_size( value, default=None ):
try:
# try built-in
return os.path.getsize( value )
except:
try:
# try built-in one name attribute
return os.path.getsize( value.name )
except:
try:
# try tell() of end of object
offset = value.tell()
value.seek( 0, 2 )
rval = value.tell()
value.seek( offset )
return rval
except:
# return default value
return default
def shrink_stream_by_size( value, size, join_by="..", left_larger=True, beginning_on_size_error=False, end_on_size_error=False ):
rval = ''
if get_file_size( value ) > size:
start = value.tell()
len_join_by = len( join_by )
min_size = len_join_by + 2
if size < min_size:
if beginning_on_size_error:
rval = value.read( size )
value.seek( start )
return rval
elif end_on_size_error:
value.seek( -size, 2 )
rval = value.read( size )
value.seek( start )
return rval
raise ValueError( 'With the provided join_by value (%s), the minimum size value is %i.' % ( join_by, min_size ) )
left_index = right_index = int( ( size - len_join_by ) / 2 )
if left_index + right_index + len_join_by < size:
if left_larger:
left_index += 1
else:
right_index += 1
rval = value.read( left_index ) + join_by
value.seek( -right_index, 2 )
rval += value.read( right_index )
else:
while True:
data = value.read( CHUNK_SIZE )
if not data:
break
rval += data
return rval
def shrink_string_by_size( value, size, join_by="..", left_larger=True, beginning_on_size_error=False, end_on_size_error=False ):
if len( value ) > size:
len_join_by = len( join_by )
min_size = len_join_by + 2
if size < min_size:
if beginning_on_size_error:
return value[:size]
elif end_on_size_error:
return value[-size:]
raise ValueError( 'With the provided join_by value (%s), the minimum size value is %i.' % ( join_by, min_size ) )
left_index = right_index = int( ( size - len_join_by ) / 2 )
if left_index + right_index + len_join_by < size:
if left_larger:
left_index += 1
else:
right_index += 1
value = "%s%s%s" % ( value[:left_index], join_by, value[-right_index:] )
return value
def pretty_print_time_interval( time=False, precise=False ):
"""
Get a datetime object or a int() Epoch timestamp and return a
pretty string like 'an hour ago', 'Yesterday', '3 months ago',
'just now', etc
credit: http://stackoverflow.com/questions/1551382/user-friendly-time-format-in-python
"""
now = datetime.now()
if type( time ) is int:
diff = now - datetime.fromtimestamp( time )
elif isinstance( time, datetime ):
diff = now - time
elif isinstance( time, string_types ):
try:
time = datetime.strptime( time, "%Y-%m-%dT%H:%M:%S.%f" )
except ValueError:
# MySQL may not support microseconds precision
time = datetime.strptime( time, "%Y-%m-%dT%H:%M:%S" )
diff = now - time
else:
diff = now - now
second_diff = diff.seconds
day_diff = diff.days
if day_diff < 0:
return ''
if precise:
if day_diff == 0:
if second_diff < 10:
return "just now"
if second_diff < 60:
return str(second_diff) + " seconds ago"
if second_diff < 120:
return "a minute ago"
if second_diff < 3600:
return str(second_diff / 60) + " minutes ago"
if second_diff < 7200:
return "an hour ago"
if second_diff < 86400:
return str(second_diff / 3600) + " hours ago"
if day_diff == 1:
return "yesterday"
if day_diff < 7:
return str( day_diff ) + " days ago"
if day_diff < 31:
return str( day_diff / 7 ) + " weeks ago"
if day_diff < 365:
return str( day_diff / 30 ) + " months ago"
return str( day_diff / 365 ) + " years ago"
else:
if day_diff == 0:
return "today"
if day_diff == 1:
return "yesterday"
if day_diff < 7:
return "less than a week"
if day_diff < 31:
return "less than a month"
if day_diff < 365:
return "less than a year"
return "a few years ago"
def pretty_print_json(json_data, is_json_string=False):
if is_json_string:
json_data = json.loads(json_data)
return json.dumps(json_data, sort_keys=True, indent=4)
# characters that are valid
valid_chars = set(string.ascii_letters + string.digits + " -=_.()/+*^,:?!")
# characters that are allowed but need to be escaped
mapped_chars = { '>': '__gt__',
'<': '__lt__',
"'": '__sq__',
'"': '__dq__',
'[': '__ob__',
']': '__cb__',
'{': '__oc__',
'}': '__cc__',
'@': '__at__',
'\n': '__cn__',
'\r': '__cr__',
'\t': '__tc__',
'#': '__pd__'}
def restore_text( text, character_map=mapped_chars ):
"""Restores sanitized text"""
if not text:
return text
for key, value in character_map.items():
text = text.replace(value, key)
return text
def sanitize_text( text, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X' ):
"""
Restricts the characters that are allowed in text; accepts both strings
and lists of strings; non-string entities will be cast to strings.
"""
if isinstance( text, list ):
return list_map( lambda x: sanitize_text( x, valid_characters=valid_characters, character_map=character_map, invalid_character=invalid_character ), text )
if not isinstance( text, string_types ):
text = smart_str( text )
return _sanitize_text_helper( text, valid_characters=valid_characters, character_map=character_map )
def _sanitize_text_helper( text, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X' ):
"""Restricts the characters that are allowed in a string"""
out = []
for c in text:
if c in valid_characters:
out.append(c)
elif c in character_map:
out.append( character_map[c] )
else:
out.append( invalid_character ) # makes debugging easier
return ''.join(out)
def sanitize_lists_to_string( values, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X' ):
if isinstance( values, list ):
rval = []
for value in values:
rval.append( sanitize_lists_to_string( value,
valid_characters=valid_characters,
character_map=character_map,
invalid_character=invalid_character ) )
values = ",".join( rval )
else:
values = sanitize_text( values, valid_characters=valid_characters, character_map=character_map, invalid_character=invalid_character )
return values
def sanitize_param( value, valid_characters=valid_chars, character_map=mapped_chars, invalid_character='X' ):
"""Clean incoming parameters (strings or lists)"""
if isinstance( value, string_types ):
return sanitize_text( value, valid_characters=valid_characters, character_map=character_map, invalid_character=invalid_character )
elif isinstance( value, list ):
return list_map( lambda x: sanitize_text( x, valid_characters=valid_characters, character_map=character_map, invalid_character=invalid_character ), value )
else:
raise Exception('Unknown parameter type (%s)' % ( type( value ) ))
valid_filename_chars = set( string.ascii_letters + string.digits + '_.' )
invalid_filenames = [ '', '.', '..' ]
def sanitize_for_filename( text, default=None ):
"""
Restricts the characters that are allowed in a filename portion; Returns default value or a unique id string if result is not a valid name.
Method is overly aggressive to minimize possible complications, but a maximum length is not considered.
"""
out = []
for c in text:
if c in valid_filename_chars:
out.append( c )
else:
out.append( '_' )
out = ''.join( out )
if out in invalid_filenames:
if default is None:
return sanitize_for_filename( str( unique_id() ) )
return default
return out
def mask_password_from_url( url ):
"""
Masks out passwords from connection urls like the database connection in galaxy.ini
>>> mask_password_from_url( 'sqlite+postgresql://user:password@localhost/' )
'sqlite+postgresql://user:********@localhost/'
>>> mask_password_from_url( 'amqp://user:amqp@localhost' )
'amqp://user:********@localhost'
>>> mask_password_from_url( 'amqp://localhost')
'amqp://localhost'
"""
split = urlparse.urlsplit(url)
if split.password:
if url.count(split.password) == 1:
url = url.replace(split.password, "********")
else:
# This can manipulate the input other than just masking password,
# so the previous string replace method is preferred when the
# password doesn't appear twice in the url
split = split._replace(netloc=split.netloc.replace("%s:%s" % (split.username, split.password), '%s:********' % split.username))
url = urlparse.urlunsplit(split)
return url
def ready_name_for_url( raw_name ):
""" General method to convert a string (i.e. object name) to a URL-ready
slug.
>>> ready_name_for_url( "My Cool Object" )
'My-Cool-Object'
>>> ready_name_for_url( "!My Cool Object!" )
'My-Cool-Object'
>>> ready_name_for_url( "Hello₩◎ґʟⅾ" )
'Hello'
"""
# Replace whitespace with '-'
slug_base = re.sub( "\s+", "-", raw_name )
# Remove all non-alphanumeric characters.
slug_base = re.sub( "[^a-zA-Z0-9\-]", "", slug_base )
# Remove trailing '-'.
if slug_base.endswith('-'):
slug_base = slug_base[:-1]
return slug_base
def which(file):
# http://stackoverflow.com/questions/5226958/which-equivalent-function-in-python
for path in os.environ["PATH"].split(":"):
if os.path.exists(path + "/" + file):
return path + "/" + file
return None
def in_directory( file, directory, local_path_module=os.path ):
"""
Return true, if the common prefix of both is equal to directory
e.g. /a/b/c/d.rst and directory is /a/b, the common prefix is /a/b.
This function isn't used exclusively for security checks, but if it is
used for such checks it is assumed that ``directory`` is a "trusted" path -
supplied by Galaxy or by the admin and ``file`` is something generated by
a tool, configuration, external web server, or user supplied input.
local_path_module is used by Pulsar to check Windows paths while running on
a POSIX-like system.
>>> base_dir = tempfile.mkdtemp()
>>> safe_dir = os.path.join(base_dir, "user")
>>> os.mkdir(safe_dir)
>>> good_file = os.path.join(safe_dir, "1")
>>> with open(good_file, "w") as f: f.write("hello")
>>> in_directory(good_file, safe_dir)
True
>>> in_directory("/other/file/is/here.txt", safe_dir)
False
>>> unsafe_link = os.path.join(safe_dir, "2")
>>> os.symlink("/other/file/bad.fasta", unsafe_link)
>>> in_directory(unsafe_link, safe_dir)
False
"""
if local_path_module != os.path:
_safe_contains = importlib.import_module('galaxy.util.path.%s' % local_path_module.__name__).safe_contains
else:
_safe_contains = safe_contains
return _safe_contains(directory, file)
def merge_sorted_iterables( operator, *iterables ):
"""
>>> operator = lambda x: x
>>> list( merge_sorted_iterables( operator, [1,2,3], [4,5] ) )
[1, 2, 3, 4, 5]
>>> list( merge_sorted_iterables( operator, [4, 5], [1,2,3] ) )
[1, 2, 3, 4, 5]
>>> list( merge_sorted_iterables( operator, [1, 4, 5], [2], [3] ) )
[1, 2, 3, 4, 5]
"""
first_iterable = iterables[ 0 ]
if len( iterables ) == 1:
for el in first_iterable:
yield el
else:
for el in __merge_two_sorted_iterables(
operator,
iter( first_iterable ),
merge_sorted_iterables( operator, *iterables[ 1: ] )
):
yield el
def __merge_two_sorted_iterables( operator, iterable1, iterable2 ):
unset = object()
continue_merge = True
next_1 = unset
next_2 = unset
while continue_merge:
try:
if next_1 is unset:
next_1 = next( iterable1 )
if next_2 is unset:
next_2 = next( iterable2 )
if operator( next_2 ) < operator( next_1 ):
yield next_2
next_2 = unset
else:
yield next_1
next_1 = unset
except StopIteration:
continue_merge = False
if next_1 is not unset:
yield next_1
if next_2 is not unset:
yield next_2
for el in iterable1:
yield el
for el in iterable2:
yield el
class Params( object ):
"""
Stores and 'sanitizes' parameters. Alphanumeric characters and the
non-alphanumeric ones that are deemed safe are let to pass through (see L{valid_chars}).
Some non-safe characters are escaped to safe forms for example C{>} becomes C{__lt__}
(see L{mapped_chars}). All other characters are replaced with C{X}.
Operates on string or list values only (HTTP parameters).
>>> values = { 'status':'on', 'symbols':[ 'alpha', '<>', '$rm&#!' ] }
>>> par = Params(values)
>>> par.status
'on'
>>> par.value == None # missing attributes return None
True
>>> par.get('price', 0)
0
>>> par.symbols # replaces unknown symbols with X
['alpha', '__lt____gt__', 'XrmX__pd__!']
>>> sorted(par.flatten()) # flattening to a list
[('status', 'on'), ('symbols', 'XrmX__pd__!'), ('symbols', '__lt____gt__'), ('symbols', 'alpha')]
"""
# is NEVER_SANITIZE required now that sanitizing for tool parameters can be controlled on a per parameter basis and occurs via InputValueWrappers?
NEVER_SANITIZE = ['file_data', 'url_paste', 'URL', 'filesystem_paths']
def __init__( self, params, sanitize=True ):
if sanitize:
for key, value in params.items():
# sanitize check both ungrouped and grouped parameters by
# name. Anything relying on NEVER_SANITIZE should be
# changed to not require this and NEVER_SANITIZE should be
# removed.
if (value is not None and
key not in self.NEVER_SANITIZE and
True not in [ key.endswith( "|%s" % nonsanitize_parameter ) for
nonsanitize_parameter in self.NEVER_SANITIZE ]):
self.__dict__[ key ] = sanitize_param( value )
else:
self.__dict__[ key ] = value
else:
self.__dict__.update(params)
def flatten(self):
"""
Creates a tuple list from a dict with a tuple/value pair for every value that is a list
"""
flat = []
for key, value in self.__dict__.items():
if isinstance(value, list):
for v in value:
flat.append( (key, v) )
else:
flat.append( (key, value) )
return flat
def __getattr__(self, name):
"""This is here to ensure that we get None for non existing parameters"""
return None
def get(self, key, default):
return self.__dict__.get(key, default)
def __str__(self):
return '%s' % self.__dict__
def __len__(self):
return len(self.__dict__)
def __iter__(self):
return iter(self.__dict__)
def update(self, values):
self.__dict__.update(values)
def rst_to_html( s ):
"""Convert a blob of reStructuredText to HTML"""
log = logging.getLogger( "docutils" )
if docutils_core is None:
raise Exception("Attempted to use rst_to_html but docutils unavailable.")
class FakeStream( object ):
def write( self, str ):
if len( str ) > 0 and not str.isspace():
log.warning( str )
settings_overrides = {
"embed_stylesheet": False,
"template": os.path.join(os.path.dirname(__file__), "docutils_template.txt"),
"warning_stream": FakeStream(),
"doctitle_xform": False, # without option, very different rendering depending on
# number of sections in help content.
}
return unicodify( docutils_core.publish_string( s,
writer=docutils_html4css1.Writer(),
settings_overrides=settings_overrides ) )
def xml_text(root, name=None):
"""Returns the text inside an element"""
if name is not None:
# Try attribute first
val = root.get(name)
if val:
return val
# Then try as element
elem = root.find(name)
else:
elem = root
if elem is not None and elem.text:
text = ''.join(elem.text.splitlines())
return text.strip()
# No luck, return empty string
return ''
# asbool implementation pulled from PasteDeploy
truthy = frozenset(['true', 'yes', 'on', 'y', 't', '1'])
falsy = frozenset(['false', 'no', 'off', 'n', 'f', '0'])
def asbool(obj):
if isinstance(obj, string_types):
obj = obj.strip().lower()
if obj in truthy:
return True
elif obj in falsy:
return False
else:
raise ValueError("String is not true/false: %r" % obj)
return bool(obj)
def string_as_bool( string ):
if str( string ).lower() in ( 'true', 'yes', 'on', '1' ):
return True
else:
return False
def string_as_bool_or_none( string ):
"""
Returns True, None or False based on the argument:
True if passed True, 'True', 'Yes', or 'On'
None if passed None or 'None'
False otherwise
Note: string comparison is case-insensitive so lowecase versions of those
function equivalently.
"""
string = str( string ).lower()
if string in ( 'true', 'yes', 'on' ):
return True
elif string == 'none':
return None
else:
return False
def listify( item, do_strip=False ):
"""
Make a single item a single item list, or return a list if passed a
list. Passing a None returns an empty list.
"""
if not item:
return []
elif isinstance( item, list ):
return item
elif isinstance( item, string_types ) and item.count( ',' ):
if do_strip:
return [token.strip() for token in item.split( ',' )]
else:
return item.split( ',' )
else:
return [ item ]
def commaify(amount):
orig = amount
new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', amount)
if orig == new:
return new
else:
return commaify(new)
def roundify(amount, sfs=2):
"""
Take a number in string form and truncate to 'sfs' significant figures.
"""
if len(amount) <= sfs:
return amount
else:
return amount[0:sfs] + '0' * (len(amount) - sfs)
def unicodify(value, encoding=DEFAULT_ENCODING, error='replace', default=None):
"""
Returns a unicode string or None.
"""
if value is None:
return None
try:
if not isinstance(value, string_types) and not isinstance(value, binary_type):
# In Python 2, value is not an instance of basestring
# In Python 3, value is not an instance of bytes or str
value = str(value)
# Now in Python 2, value is an instance of basestring, but may be not unicode
# Now in Python 3, value is an instance of bytes or str
if not isinstance(value, text_type):
value = text_type(value, encoding, error)
except Exception:
log.exception("value %s could not be coerced to unicode" % value)
return default
return value
def smart_str(s, encoding=DEFAULT_ENCODING, strings_only=False, errors='strict'):
u"""
Returns a bytestring version of 's', encoded as specified in 'encoding'.
If strings_only is True, don't convert (some) non-string-like objects.
Adapted from an older, simpler version of django.utils.encoding.smart_str.
>>> assert smart_str(None) == b'None'
>>> assert smart_str(None, strings_only=True) is None
>>> assert smart_str(3) == b'3'
>>> assert smart_str(3, strings_only=True) == 3
>>> assert smart_str(b'a bytes string') == b'a bytes string'
>>> assert smart_str(u'a simple unicode string') == b'a simple unicode string'
>>> assert smart_str(u'à strange ünicode ڃtring') == b'\\xc3\\xa0 strange \\xc3\\xbcnicode \\xda\\x83tring'
>>> assert smart_str(b'\\xc3\\xa0n \\xc3\\xabncoded utf-8 string', encoding='latin-1') == b'\\xe0n \\xebncoded utf-8 string'
"""
if strings_only and isinstance(s, (type(None), int)):
return s
if not isinstance(s, string_types) and not isinstance(s, binary_type):
# In Python 2, s is not an instance of basestring
# In Python 3, s is not an instance of bytes or str
s = str(s)
if not isinstance(s, binary_type):
return s.encode(encoding, errors)
elif s and encoding != DEFAULT_ENCODING:
return s.decode(DEFAULT_ENCODING, errors).encode(encoding, errors)
else:
return s
def object_to_string( obj ):
return binascii.hexlify( obj )
def string_to_object( s ):
return binascii.unhexlify( s )
class ParamsWithSpecs( collections.defaultdict ):
"""
"""
def __init__( self, specs=None, params=None ):
self.specs = specs or dict()
self.params = params or dict()
for name, value in self.params.items():
if name not in self.specs:
self._param_unknown_error( name )
if 'map' in self.specs[ name ]:
try:
self.params[ name ] = self.specs[ name ][ 'map' ]( value )
except Exception:
self._param_map_error( name, value )
if 'valid' in self.specs[ name ]:
if not self.specs[ name ][ 'valid' ]( value ):
self._param_vaildation_error( name, value )
self.update( self.params )
def __missing__( self, name ):
return self.specs[ name ][ 'default' ]
def __getattr__( self, name ):
return self[ name ]
def _param_unknown_error( self, name ):
raise NotImplementedError()
def _param_map_error( self, name, value ):
raise NotImplementedError()
def _param_vaildation_error( self, name, value ):
raise NotImplementedError()
def compare_urls( url1, url2, compare_scheme=True, compare_hostname=True, compare_path=True ):
url1 = urlparse.urlparse( url1 )
url2 = urlparse.urlparse( url2 )
if compare_scheme and url1.scheme and url2.scheme and url1.scheme != url2.scheme:
return False
if compare_hostname and url1.hostname and url2.hostname and url1.hostname != url2.hostname:
return False
if compare_path and url1.path and url2.path and url1.path != url2.path:
return False
return True
def read_dbnames(filename):
""" Read build names from file """
class DBNames( list ):