Completed
Push — master ( 5165c9...e52419 )
by Asif
45s
created

crudbuilder.capword()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 6
rs 9.4285
1
import re
2
import string
3
import imp
4
5
from crudbuilder.exceptions import CrudModuleNotExit
6
7
try:
8
    # Django versions >= 1.9
9
    from django.utils.module_loading import import_module
10
except ImportError:
11
    # Django versions < 1.9
12
    from django.utils.importlib import import_module
13
14
15
__all__ = ['plural', 'mixedToUnder', 'capword', 'lowerword', 'underToMixed']
16
17
# http://code.activestate.com/recipes/82102-smart-pluralisation-english/
18
19
20
def plural(text):
21
    """
22
        >>> plural('activity')
23
        'activities'
24
    """
25
    aberrant = {
26
        'knife': 'knives',
27
        'self': 'selves',
28
        'elf': 'elves',
29
        'life': 'lives',
30
        'hoof': 'hooves',
31
        'leaf': 'leaves',
32
        'echo': 'echoes',
33
        'embargo': 'embargoes',
34
        'hero': 'heroes',
35
        'potato': 'potatoes',
36
        'tomato': 'tomatoes',
37
        'torpedo': 'torpedoes',
38
        'veto': 'vetoes',
39
        'child': 'children',
40
        'woman': 'women',
41
        'man': 'men',
42
        'person': 'people',
43
        'goose': 'geese',
44
        'mouse': 'mice',
45
        'barracks': 'barracks',
46
        'deer': 'deer',
47
        'nucleus': 'nuclei',
48
        'syllabus': 'syllabi',
49
        'focus': 'foci',
50
        'fungus': 'fungi',
51
        'cactus': 'cacti',
52
        'phenomenon': 'phenomena',
53
        'index': 'indices',
54
        'appendix': 'appendices',
55
        'criterion': 'criteria',
56
57
58
    }
59
60
    if text in aberrant:
61
        result = '%s' % aberrant[text]
62
    else:
63
        postfix = 's'
64
        if len(text) > 2:
65
            vowels = 'aeiou'
66
            if text[-2:] in ('ch', 'sh'):
67
                postfix = 'es'
68
            elif text[-1:] == 'y':
69
                if (text[-2:-1] in vowels) or (text[0] in string.uppercase):
70
                    postfix = 's'
71
                else:
72
                    postfix = 'ies'
73
                    text = text[:-1]
74
            elif text[-2:] == 'is':
75
                postfix = 'es'
76
                text = text[:-2]
77
            elif text[-1:] in ('s', 'z', 'x'):
78
                postfix = 'es'
79
80
        result = '%s%s' % (text, postfix)
81
    return result
82
83
84
# Text utilities
85
#
86
_mixedToUnderRE = re.compile(r'[A-Z]+')
87
88
89
def mixedToUnder(s):
90
    """
91
    Sample:
92
        >>> mixedToUnder("FooBarBaz")
93
        'foo_bar_baz'
94
95
    Special case for ID:
96
        >>> mixedToUnder("FooBarID")
97
        'foo_bar_id'
98
    """
99
    if s.endswith('ID'):
100
        return mixedToUnder(s[:-2] + "_id")
101
    trans = _mixedToUnderRE.sub(mixedToUnderSub, s)
102
    if trans.startswith('_'):
103
        trans = trans[1:]
104
    return trans
105
106
107
def mixedToUnderSub(match):
108
    m = match.group(0).lower()
109
    if len(m) > 1:
110
        return '_%s_%s' % (m[:-1], m[-1])
111
    else:
112
        return '_%s' % m
113
114
115
def capword(s):
116
    """
117
    >>> capword('foo')
118
    'Foo'
119
    """
120
    return s[0].upper() + s[1:]
121
122
123
def lowerword(s):
124
    """
125
    >>> lowerword('Hello')
126
    'hello'
127
    """
128
    return s[0].lower() + s[1:]
129
130
_underToMixedRE = re.compile('_.')
131
132
133
def underToMixed(name):
134
    """
135
    >>> underToMixed('some_large_model_name_perhaps')
136
    'someLargeModelNamePerhaps'
137
138
    >>> underToMixed('exception_for_id')
139
    'exceptionForID'
140
    """
141
    if name.endswith('_id'):
142
        return underToMixed(name[:-3] + "ID")
143
    return _underToMixedRE.sub(lambda m: m.group(0)[1].upper(),
144
                               name)
145
146
147
def model_class_form(name):
148
    """
149
    >>> model_class_form('foo_bar_baz')
150
    'FooBarBaz'
151
    """
152
    return capword(underToMixed(name))
153
154
155
def underToAllCaps(value):
156
    """
157
    >>> underToAllCaps('foo_bar_baz')
158
    'Foo Bar Baz'
159
    """
160
    return ' '.join(map(lambda x: x.title(), value.split('_')))
161
162
163
def import_crud(app):
164
    '''
165
    Import moderator module and register all models it contains with moderation
166
    '''
167
168
    try:
169
        app_path = import_module(app).__path__
170
    except AttributeError:
171
        return None
172
173
    try:
174
        imp.find_module('crud', app_path)
175
    except ImportError:
176
        return None
177
178
    module = import_module("%s.crud" % app)
179
180
    return module
181
182
183
def auto_discover():
184
    '''
185
    Auto register all apps that have module moderator with moderation
186
    '''
187
    from django.conf import settings
188
189
    for app in settings.INSTALLED_APPS:
190
        import_crud(app)
191
192
193
if __name__ == '__main__':
194
    print plural('activity')
195