Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
tolstislon committed May 18, 2020
1 parent 8a2d34d commit 82b6e5e
Show file tree
Hide file tree
Showing 11 changed files with 1,290 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,10 @@ dmypy.json

# Pyre type checker
.pyre/

# Pycharm
.idea/

# Other
Pipfile.lock
phone_gen/__version__.py
20 changes: 20 additions & 0 deletions Pipfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true

[dev-packages]
requests = "==2.23.0"
pytest = "==5.4.2"
pytest-cov = "==2.8.1"
phonenumbers = "==8.12.3"
black = "==19.10b0"
mypy = "==0.770"
flake8 = "==3.8.1"
pep8-naming = "==0.10.0"

[packages]
phone-gen = {editable = true,path = "."}

[requires]
python_version = "3.8"
80 changes: 80 additions & 0 deletions dev_tools/patterns_generator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import json
import xml.etree.ElementTree as ElementTree
from datetime import datetime
from pathlib import Path
from re import findall
from typing import Dict, Generator, Tuple

import requests

RESOURCE = 'https://raw.githubusercontent.com/google/libphonenumber/master/resources/PhoneNumberMetadata.xml'

TEMPLATE = """# Auto-generated file {datetime} UTC
# Resource: https://github.com/google/libphonenumber {version}
PATTERNS = {patterns}
"""


class RegexCompiler:

def __init__(self, pattern: str):
pattern = pattern.replace('\n', '').replace(' ', '').replace('?:', '')
pattern = pattern.replace(r'\d', r'[\d]').replace(',', ':')
self.pattern = '({})'.format(pattern)

def _group(self, group: str) -> str:
groups = findall(r'\((.*)\)', group)
if groups:
for i in groups:
group.replace(group, self._group(i))
return '|'.join('({})'.format(i) for i in group.split('|'))

def compile(self) -> str:
return self.pattern.replace(self.pattern, self._group(self.pattern))


class Parser:

def __init__(self, source: str):
self.root = ElementTree.fromstring(source)
self.line_tag = 'fixedLine'
self.pattern_tag = 'nationalNumberPattern'

def render(self) -> Generator[Tuple[str, Dict[str, str]], None, None]:
for territory in self.root.iter('territory'):
attrs = territory.attrib
code = attrs.get('id', '1')
if code.isdigit():
continue
value = {'code': attrs.get('countryCode', '')}
for fixed_line in territory.iter(self.line_tag):
for national_number_pattern in fixed_line.iter(self.pattern_tag):
value['pattern'] = RegexCompiler(national_number_pattern.text).compile()
yield code, value


def get_latest() -> str:
response = requests.get('https://github.com/google/libphonenumber/releases/latest')
return response.url.split('/')[-1]


def main():
response = requests.get(RESOURCE)
parser = Parser(response.text)
data = {code: value for code, value in parser.render()}
root_path = Path(__file__).absolute().parent.parent
file = root_path.joinpath('phone_gen', 'patterns.py')
version = get_latest()
with file.open('wb') as _file:
temp = TEMPLATE.format(
datetime=datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'),
patterns=json.dumps({'info': 'libphonenumber {}'.format(version), 'data': data}, indent=4),
version=version
)
_file.write(temp.encode())


if __name__ == '__main__':
main()
8 changes: 8 additions & 0 deletions phone_gen/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from .generator import PhoneNumber

try:
from .__version__ import version as __version__
except ImportError: # pragma: no cover
__version__ = "unknown"

__all__ = ["PhoneNumber", "__version__"]
Loading

0 comments on commit 82b6e5e

Please sign in to comment.