Project

General

Profile

1
# String manipulation
2

    
3
import codecs
4
import re
5

    
6
import util
7

    
8
##### Parsing
9

    
10
def split(sep, str_):
11
    '''Returns [] if str_ == ""'''
12
    if str_ == '': return []
13
    else: return str_.split(sep)
14

    
15
def remove_prefix(prefix, str_, removed_ref=None):
16
    if removed_ref == None: removed_ref = [False]
17
    
18
    removed_ref[0] = str_.startswith(prefix)
19
    if removed_ref[0]: return str_[len(prefix):]
20
    else: return str_
21

    
22
def remove_prefixes(prefixes, str_):
23
    for prefix in prefixes: str_ = remove_prefix(prefix, str_)
24
    return str_
25

    
26
def with_prefixes(prefixes, str_): return (p+str_ for p in prefixes)
27

    
28
def remove_suffix(suffix, str_, removed_ref=None):
29
    if removed_ref == None: removed_ref = [False]
30
    
31
    removed_ref[0] = str_.endswith(suffix)
32
    if removed_ref[0]: return str_[:-len(suffix)]
33
    else: return str_
34

    
35
def add_suffix(str_, suffix, max_len): return str_[:max_len-len(suffix)]+suffix
36

    
37
def contains_any(haystack, needles):
38
    for needle in needles:
39
        if haystack.find(needle) >= 0: return True
40
    return False
41

    
42
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
43

    
44
##### Escaping
45

    
46
def esc_for_mogrify(query):
47
    '''Escapes a query right before being passed to a mogrifying function.'''
48
    return query.replace('%', '%%')
49

    
50
##### Unicode
51

    
52
unicode_reader = codecs.getreader('utf_8')
53

    
54
def to_unicode(str_):
55
    if isinstance(str_, unicode): return str_
56
    encodings = ['utf_8', 'latin_1']
57
    for encoding in encodings:
58
        try: return unicode(str_, encoding)
59
        except UnicodeDecodeError, e: pass
60
    raise AssertionError(encoding+' is not a catch-all encoding')
61

    
62
def ustr(val):
63
    '''Like built-in str() but converts to unicode object'''
64
    if not util.is_str(val): val = str(val)
65
    return to_unicode(val)
66

    
67
def repr_no_u(value):
68
    '''Like built-in repr() but removes the "u" in `u'...'`'''
69
    return re.sub(r"^u(?=')", r'', repr(value))
70

    
71
##### Line endings
72

    
73
def extract_line_ending(line):
74
    '''@return tuple (contents, ending)'''
75
    contents = remove_suffix('\r', remove_suffix('\n', line))
76
    return (contents, line[len(contents):])
77

    
78
def remove_line_ending(line): return extract_line_ending(line)[0]
79

    
80
def ensure_newl(str_): return remove_line_ending(str_)+'\n'
81

    
82
def is_multiline(str_):
83
    newl_idx = str_.find('\n')
84
    return newl_idx >= 0 and newl_idx != len(str_)-1 # has newline before end
85

    
86
def remove_extra_newl(str_):
87
    if is_multiline(str_): return str_
88
    else: return str_.rstrip('\n')
89

    
90
def std_newl(str_): return str_.replace('\r\n', '\n').replace('\r', '\n')
91

    
92
##### Whitespace
93

    
94
def cleanup(str_): return std_newl(str_.strip())
95

    
96
def single_space(str_): return re.sub(r' {2,}', r' ', str_.strip())
97

    
98
def one_line(str_): return re.sub(r'\n *', r' ', cleanup(str_))
99

    
100
##### Control characters
101

    
102
def is_ctrl(char):
103
    '''Whether char is a (non-printable) control character'''
104
    return ord(char) < 32 and not char.isspace()
105

    
106
def strip_ctrl(str_):
107
    '''Strips (non-printable) control characters'''
108
    return ''.join(filter(lambda c: not is_ctrl(c), str_))
109

    
110
##### Formatting
111

    
112
def as_tt(str_): return '@'+str_+'@'
113

    
114
def as_code(str_, lang=None, multiline=True):
115
    '''Wraps a string in Redmine tags to syntax-highlight it.'''
116
    str_ = '\n'+str_.rstrip('\n')+'\n'
117
    if lang != None: str_ = '<code class="'+lang+'">'+str_+'</code>'
118
    if multiline: str_ = '<pre>'+str_+'</pre>'
119
    return str_
120

    
121
def as_inline_table(dict_, key_label='Output', value_label='Input', ustr=ustr):
122
    '''Wraps a dict in Redmine tags to format it as a table.'''
123
    str_ = ''
124
    def row(entry): return (': '.join(entry))+'\n'
125
    str_ += row([key_label, value_label])
126
    for entry in dict_.iteritems(): str_ += row([ustr(v) for v in entry])
127
    return '<pre>\n'+str_+'</pre>'
128

    
129
def as_table(dict_, key_label='Output', value_label='Input', ustr=ustr):
130
    '''Wraps a dict in Redmine tags to format it as a table.'''
131
    str_ = ''
132
    def row(entry): return ('|'.join(['']+entry+['']))+'\n'# '' for outer border
133
    str_ += row([key_label, value_label])
134
    for entry in dict_.iteritems(): str_ += row([as_tt(ustr(v)) for v in entry])
135
    return '\n'+str_+' ' # space protects last \n so blank line ends table
(27-27/36)