verboselib.helpers.to_locale()   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 22
rs 9.9
c 0
b 0
f 0
cc 4
nop 1
1
from ._utils import export
2
3
4
@export
5
def to_locale(language):
6
  """
7
  Turn a language name (en-us) into a locale name (en_US).
8
9
  Extracted `from Django <https://github.com/django/django/blob/e74b3d724e5ddfef96d1d66bd1c58e7aae26fc85/django/utils/translation/__init__.py#L274-L287>`_.
10
11
  """
12
  language, _, country = language.lower().partition("-")
13
  if not country:
14
    return language
15
16
  # A language with > 2 characters after the dash only has its first
17
  # character after the dash capitalized; e.g. sr-latn becomes sr_Latn.
18
  # A language with 2 characters after the dash has both characters
19
  # capitalized; e.g. en-us becomes en_US.
20
  country, _, tail = country.partition("-")
21
  country = country.title() if len(country) > 2 else country.upper()
22
  if tail:
23
    country += "-" + tail
24
25
  return language + "_" + country
26
27
28
@export
29
def to_language(locale):
30
  """
31
  Turn a locale name (en_US) into a language name (en-us).
32
33
  Extracted `from Django <https://github.com/django/django/blob/e74b3d724e5ddfef96d1d66bd1c58e7aae26fc85/django/utils/translation/__init__.py#L265-L271>`_.
34
35
  """
36
  p = locale.find("_")
37
  if p >= 0:
38
    return locale[:p].lower() + "-" + locale[p + 1:].lower()
39
  else:
40
    return locale.lower()
41