Completed
Push — master ( a55149...0becad )
by Oleksandr
02:02
created

Countries   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 2
c 4
b 0
f 1
dl 0
loc 20
ccs 18
cts 18
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A filter_by_belligerent() 0 3 2
1
# -*- coding: utf-8 -*-
2
3 1
import os
4 1
import six
5
6 1
if six.PY2:
7
    from io import open
8
9 1
from candv import (
10
    Values, VerboseConstant, VerboseValueConstant, with_constant_class,
11
)
12 1
from verboselib import get_language
13
14 1
from . import SupportedLanguages
15 1
from .utils import translations
16
17
18 1
_ = translations.ugettext_lazy
19
20
21 1
class Belligerents(Values):
22 1
    none = VerboseValueConstant(0, _("neutral"))
23 1
    red = VerboseValueConstant(1, _("allies"))
24 1
    blue = VerboseValueConstant(2, _("axis"))
25 1
    green = VerboseValueConstant(3, _("green"))
26 1
    gold = VerboseValueConstant(4, _("gold"))
27 1
    purple = VerboseValueConstant(5, _("purple"))
28 1
    aqua = VerboseValueConstant(6, _("aqua"))
29 1
    maroon = VerboseValueConstant(7, _("maroon"))
30 1
    navy = VerboseValueConstant(8, _("navy"))
31 1
    emerald = VerboseValueConstant(9, _("emerald"))
32 1
    olive = VerboseValueConstant(10, _("olive"))
33 1
    magenta = VerboseValueConstant(11, _("magenta"))
34 1
    teal = VerboseValueConstant(12, _("teal"))
35 1
    orange = VerboseValueConstant(13, _("orange"))
36 1
    turquoise = VerboseValueConstant(14, _("turquoise"))
37 1
    brown = VerboseValueConstant(15, _("brown"))
38 1
    salad = VerboseValueConstant(16, _("salad"))
39
40
41 1
class Country(VerboseConstant):
42
43 1
    def __init__(self, belligerent, verbose_name=None, help_text=None):
44 1
        super(Country, self).__init__(verbose_name=verbose_name,
45
                                      help_text=help_text)
46 1
        self.belligerent = belligerent
47
48 1
    def merge_into_group(self, group):
49 1
        super(Country, self).merge_into_group(group)
50 1
        group.belligerent = self.belligerent
51
52 1
    def to_primitive(self, context=None):
53 1
        primitive = super(Country, self).to_primitive(context)
54 1
        primitive['belligerent'] = self.belligerent.to_primitive(context)
55 1
        return primitive
56
57
58 1
class Countries(with_constant_class(Country), Values):
59 1
    au = Country(Belligerents.red, _("Australia"))
60 1
    fi = Country(Belligerents.blue, _("Finland"))
61 1
    fr = Country(Belligerents.red, _("France"))
62 1
    de = Country(Belligerents.blue, _("Germany"))
63 1
    hu = Country(Belligerents.blue, _("Hungary"))
64 1
    jp = Country(Belligerents.blue, _("Japan"))
65 1
    it = Country(Belligerents.blue, _("Italy"))
66 1
    nl = Country(Belligerents.red, _("Netherlands"))
67 1
    nz = Country(Belligerents.red, _("New Zealand"))
68 1
    pl = Country(Belligerents.red, _("Poland"))
69 1
    ro = Country(Belligerents.blue, _("Romania"))
70 1
    sk = Country(Belligerents.blue, _("Slovakia"))
71 1
    su = Country(Belligerents.red, _("Soviet Union"))
72 1
    uk = Country(Belligerents.red, _("United Kingdom"))
73 1
    us = Country(Belligerents.red, _("United States"))
74
75 1
    @classmethod
76
    def filter_by_belligerent(cls, belligerent):
77 1
        return filter(lambda x: x.belligerent == belligerent, cls.constants())
78
79
80 1
class AirForce(VerboseValueConstant):
81
82 1
    def __init__(self, country, default_flight_prefix, value,
83
                 verbose_name=None, help_text=None):
84 1
        super(AirForce, self).__init__(value,
85
                                       verbose_name=verbose_name,
86
                                       help_text=help_text)
87 1
        self.country = country
88
89 1
        if default_flight_prefix is not None:
90 1
            self.default_flight_prefix = str(default_flight_prefix)
91
        else:
92 1
            self.default_flight_prefix = None
93
94 1
    def merge_into_group(self, group):
95 1
        super(AirForce, self).merge_into_group(group)
96 1
        group.country = self.country
97 1
        group.default_flight_prefix = self.default_flight_prefix
98
99 1
    def to_primitive(self, context=None):
100 1
        primitive = super(AirForce, self).to_primitive(context)
101 1
        primitive.update({
102
            'country': self.country.to_primitive(context),
103
            'default_flight_prefix': self.default_flight_prefix,
104
        })
105 1
        return primitive
106
107
108 1
class AirForces(with_constant_class(AirForce), Values):
109 1
    ala = AirForce(
110
        country=Countries.fr,
111
        default_flight_prefix='fr01',
112
        value='fr',
113
        verbose_name=_("ALA"),
114
        help_text=_("Army of the Air"),
115
    )
116 1
    faf = AirForce(
117
        country=Countries.fi,
118
        default_flight_prefix='f01',
119
        value='fi',
120
        verbose_name=_("FAF"),
121
        help_text=_("Finnish Air Force"),
122
    )
123 1
    far = AirForce(
124
        country=Countries.ro,
125
        default_flight_prefix='ro01',
126
        value='ro',
127
        verbose_name=_("FAR"),
128
        help_text=_("Romanian Air Force"),
129
    )
130 1
    haf = AirForce(
131
        country=Countries.hu,
132
        default_flight_prefix='h01',
133
        value='hu',
134
        verbose_name=_("HAF"),
135
        help_text=_("Hungarian Air Force"),
136
    )
137 1
    luftwaffe = AirForce(
138
        country=Countries.de,
139
        default_flight_prefix='g01',
140
        value='de',
141
        verbose_name=_("Luftwaffe"),
142
    )
143 1
    ija = AirForce(
144
        country=Countries.jp,
145
        default_flight_prefix='ja01',
146
        value='ja',
147
        verbose_name=_("IJA"),
148
        help_text=_("Imperial Japanese Army"),
149
    )
150 1
    ijn = AirForce(
151
        country=Countries.jp,
152
        default_flight_prefix='IN_NN',
153
        value='in',
154
        verbose_name=_("IJN"),
155
        help_text=_("Imperial Japanese Navy"),
156
    )
157 1
    paf = AirForce(
158
        country=Countries.pl,
159
        default_flight_prefix='pl01',
160
        value='pl',
161
        verbose_name=_("PAF"),
162
        help_text=_("Polish Air Force"),
163
    )
164 1
    rai = AirForce(
165
        country=Countries.it,
166
        default_flight_prefix='i01',
167
        value='it',
168
        verbose_name=_("RAI"),
169
        help_text=_("Regia Aeronautica Italiana"),
170
    )
171 1
    raaf = AirForce(
172
        country=Countries.au,
173
        default_flight_prefix='RA_NN',
174
        value='ra',
175
        verbose_name=_("RAAF"),
176
        help_text=_("Royal Australian Air Force"),
177
    )
178 1
    raf = AirForce(
179
        country=Countries.uk,
180
        default_flight_prefix='gb01',
181
        value='gb',
182
        verbose_name=_("RAF"),
183
        help_text=_("Royal Air Force"),
184
    )
185 1
    rn = AirForce(
186
        country=Countries.uk,
187
        default_flight_prefix='RN_NN',
188
        value='rn',
189
        verbose_name=_("RN"),
190
        help_text=_("Royal Navy"),
191
    )
192 1
    rnlaf = AirForce(
193
        country=Countries.nl,
194
        default_flight_prefix='DU_NN',
195
        value='du',
196
        verbose_name=_("RNLAF"),
197
        help_text=_("Royal Netherlands Air Force"),
198
    )
199 1
    rnzaf = AirForce(
200
        country=Countries.nz,
201
        default_flight_prefix='RZ_NN',
202
        value='rz',
203
        verbose_name=_("RNZAF"),
204
        help_text=_("Royal New Zealand Air Force"),
205
    )
206 1
    saf = AirForce(
207
        country=Countries.sk,
208
        default_flight_prefix='sk01',
209
        value='sk',
210
        verbose_name=_("SAF"),
211
        help_text=_("Slovak Air Force"),
212
    )
213 1
    usaaf = AirForce(
214
        country=Countries.us,
215
        default_flight_prefix='usa01',
216
        value='us',
217
        verbose_name=_("USAAF"),
218
        help_text=_("United States Army Air Forces"),
219
    )
220 1
    usmc = AirForce(
221
        country=Countries.us,
222
        default_flight_prefix='UM_NN',
223
        value='um',
224
        verbose_name=_("USMC"),
225
        help_text=_("United States Marine Corps"),
226
    )
227 1
    usn = AirForce(
228
        country=Countries.us,
229
        default_flight_prefix='UN_NN',
230
        value='un',
231
        verbose_name=_("USN"),
232
        help_text=_("United States Navy"),
233
    )
234 1
    vvs_rkka = AirForce(
235
        country=Countries.su,
236
        default_flight_prefix='r01',
237
        value='ru',
238
        verbose_name=_("VVS RKKA"),
239
        help_text=_("Workers-Peasants Red Army Air Forces"),
240
    )
241 1
    none = AirForce(
242
        country=None,
243
        default_flight_prefix=None,
244
        value='nn',
245
        verbose_name=_("None"),
246
    )
247
248 1
    @classmethod
249
    def get_flight_prefixes(cls):
250 1
        result = map(lambda x: x.default_flight_prefix, cls.iterconstants())
251 1
        if six.PY3:
252 1
            result = list(result)
253 1
        return result
254
255 1
    @classmethod
256
    def get_by_flight_prefix(cls, prefix):
257 1
        for constant in cls.iterconstants():
258 1
            if constant.default_flight_prefix == prefix:
259 1
                return constant
260 1
        raise ValueError(
261
            "Air force with prefix '{0}' is not present in '{1}'"
262
            .format(prefix, cls.__name__)
263
        )
264
265 1
    @classmethod
266
    def filter_by_country(cls, country):
267 1
        return filter(lambda x: x.country == country, cls.constants())
268
269 1
    @classmethod
270
    def filter_by_belligerent(cls, belligerent):
271 1
        return filter(
272
            lambda x: x.country.belligerent == belligerent if x.country else False,
273
            cls.constants()
274
        )
275
276
277 1
def _get_data_file_path(file_name):
278 1
    root = os.path.dirname(os.path.abspath(__file__))
279 1
    return os.path.join(root, 'data', file_name)
280
281
282 1
class Regiment(object):
283
284 1
    def __init__(self, air_force, code_name):
285 1
        self.air_force = air_force
286 1
        self.code_name = str(code_name)
287
288 1
    def __getattr__(self, name):
289 1
        if name == 'verbose_name':
290 1
            getter = self._get_verbose_name
291 1
        elif name == 'help_text':
292 1
            getter = self._get_help_text
293
        else:
294 1
            raise AttributeError("%r object has no attribute %r"
295
                                 % (self.__class__, name))
296
297 1
        language = get_language()
298 1
        final_name = "{0}_{1}".format(name, language)
299
300 1
        if hasattr(self, final_name):
301
            return getattr(self, final_name)
302
303
        # Check language code is known
304 1
        default_language = SupportedLanguages.get_default().name
305 1
        if language not in SupportedLanguages:
306 1
            language = default_language
307
308
        # Try to get value for specified language or for default language
309 1
        value = getter(language)
310 1
        if not value and language != default_language:
311 1
            value = getter(default_language)
312
313
        # Add missing attribute to the object
314 1
        setattr(self, final_name, value)
315 1
        return value
316
317 1
    def _get_verbose_name(self, language):
318 1
        file_name = "regShort_{0}.properties".format(language)
319 1
        return self._get_text(file_name)
320
321 1
    def _get_help_text(self, language):
322 1
        file_name = "regInfo_{0}.properties".format(language)
323 1
        return self._get_text(file_name)
324
325 1
    def _get_text(self, file_name):
326 1
        file_path = _get_data_file_path(file_name)
327
328 1
        with open(file_path, mode='r', encoding='cp1251') as f:
329 1
            for line in f:
330 1
                if line.startswith(self.code_name):
331 1
                    start = len(self.code_name)
332 1
                    result = line[start:].strip()
333 1
                    if six.PY3:
334 1
                        result = bytes(result, 'ascii')
335 1
                    return result.decode('unicode-escape')
336 1
        return ''
337
338 1
    def to_primitive(self, context=None):
339
        """
340
        Add for consistency with constants.
341
        """
342 1
        return {
343
            'air_force': self.air_force.to_primitive(context),
344
            'code_name': self.code_name,
345
            'verbose_name': six.text_type(self.verbose_name),
346
            'help_text': six.text_type(self.help_text),
347
        }
348
349
    def __repr__(self):
350
        return "<Regiment '{:}'>".format(self.code_name)
351
352
353 1
class Regiments(object):
354
355 1
    _cache = {}
356 1
    _file_name = 'regiments.ini'
357
358 1
    def __new__(cls):
359 1
        raise TypeError("'{0}' may not be instantiated".format(cls.__name__))
360
361 1 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
362
    def get_by_code_name(cls, code_name):
363 1
        if code_name in cls._cache:
364 1
            return cls._cache[code_name]
365
366 1
        flight_prefixes = AirForces.get_flight_prefixes()
367 1
        last_flight_prefix = None
368 1
        found = False
369
370 1
        file_path = _get_data_file_path(cls._file_name)
371 1
        with open(file_path, mode='r', encoding='cp1251') as f:
372 1
            for line in f:
373 1
                line = line.strip()
374 1
                if not line:
375 1
                    continue
376 1
                if line in flight_prefixes:
377 1
                    last_flight_prefix = line
378 1
                    continue
379 1
                if line == code_name:
380 1
                    found = True
381 1
                    break
382
383 1
        if found and last_flight_prefix:
384 1
            air_force = AirForces.get_by_flight_prefix(last_flight_prefix)
385 1
            regiment = Regiment(air_force, code_name)
386 1
            cls._cache[code_name] = regiment
387 1
            return regiment
388
389 1
        raise ValueError("Regiment with code name '{0}' is unknown"
390
                         .format(code_name))
391
392 1 View Code Duplication
    @classmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
393
    def filter_by_air_force(cls, air_force):
394 1
        result = []
395
396 1
        flight_prefixes = AirForces.get_flight_prefixes()
397 1
        found = False
398
399 1
        file_path = _get_data_file_path(cls._file_name)
400 1
        with open(file_path, mode='r', encoding='cp1251') as f:
401 1
            for line in f:
402 1
                line = line.strip()
403
404 1
                if not line:
405 1
                    continue
406
407 1
                if line == air_force.default_flight_prefix:
408
                    # Flag that proper section was found.
409 1
                    found = True
410 1
                    continue
411
412 1
                if found:
413 1
                    if (
414
                        line in flight_prefixes
415
                        or (line.startswith('[') and line.endswith(']'))
416
                    ):
417
                        # Next section was found. Fullstop.
418 1
                        break
419
420 1
                    if line in cls._cache:
421 1
                        regiment = cls._cache[line]
422
                    else:
423 1
                        regiment = Regiment(air_force, line)
424 1
                        cls._cache[line] = regiment
425
426 1
                    result.append(regiment)
427
428
        return result
429