Skip to content

Commit

Permalink
Added the ability to build a module with old versions of libphonenumb…
Browse files Browse the repository at this point in the history
…er (#4)
  • Loading branch information
tolstislon authored May 31, 2020
1 parent 97dfeb1 commit 1af594a
Show file tree
Hide file tree
Showing 9 changed files with 113 additions and 34 deletions.
20 changes: 15 additions & 5 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ git:
stages:
- black
- flake8
- patterns
- test

jobs:
Expand All @@ -15,19 +16,27 @@ jobs:
python: "3.6"
env: BLACK=19.10b0
install: pip install black==$BLACK
script: black ./phone_gen --check
script: black phone_gen dev_tools --check
after_success: false
- stage: "flake8"
python: "3.6"
env:
- FLAKE8=3.8.1
- FLAKE8=3.8.2
- PEP8_NAMING=0.10.0
install:
- pip install flake8==$FLAKE8
- pip install pep8-naming==$PEP8_NAMING
script: flake8 ./phone_gen
script: flake8 phone_gen dev_tools
after_success: false
- stage: "patterns"
python: "3.6"
env: LIBPHONENUMBER=v8.8.8
install: pip install -U requests
script:
- python dev_tools/patterns_generator.py --tag=$LIBPHONENUMBER
- pip install -e .
- phone-gen --version
after_success: false

env:
- PHONENUMBERS="8.12.4" # last version

Expand All @@ -37,9 +46,10 @@ python:
- "3.6"
- "3.7"
- "3.8"
- "3.9-dev"
install:
- pip install phonenumbers==$PHONENUMBERS
- pip install pytest-cov==2.8.1
- pip install pytest-cov==2.9.0
- pip install pytest==5.4.2
- pip install -e .
script:
Expand Down
4 changes: 2 additions & 2 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ verify_ssl = true
[dev-packages]
requests = "==2.23.0"
pytest = "==5.4.2"
pytest-cov = "==2.8.1"
pytest-cov = "==2.9.0"
phonenumbers = "==8.12.4"
black = "==19.10b0"
flake8 = "==3.8.1"
flake8 = "==3.8.2"
pep8-naming = "==0.10.0"

[packages]
Expand Down
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Phone Gen

[![PyPI](https://img.shields.io/pypi/v/phone-gen?color=%2301a001&label=version&logo=version)](https://pypi.org/project/phone-gen/)
[![PyPI](https://img.shields.io/pypi/v/phone-gen?color=%2301a001&label=pypi&logo=version)](https://pypi.org/project/phone-gen/)
[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/phone-gen.svg)](https://pypi.org/project/phone-gen/)
[![PyPI - Implementation](https://img.shields.io/pypi/implementation/phone-gen)](https://pypi.org/project/phone-gen/)
[![Downloads](https://pepy.tech/badge/phone-gen)](https://pepy.tech/project/phone-gen)
Expand Down Expand Up @@ -111,8 +111,18 @@ Contributing
Contributions are very welcome.


##### How to build a version with libphonenumber below v8.12.3
Need Python 3.6 or more.
1. `git pull https://github.com/tolstislon/phone-gen.git`
2. `cd phone-gen`
3. `pip install requests`
4. `python dev_tools/patterns_generator.py -t {Desired Tag}`
5. `python setup.py install`


Changelog
----
* **1.3.0** Added the ability to build a module with old versions of libphonenumber
* **1.2.0** Added phone number generation by `country name` and `ISO 3166-3`
* **1.1.1** Updating patterns to libphonenumber v8.12.4
* **1.1.0** Added cli
Expand Down
79 changes: 61 additions & 18 deletions dev_tools/patterns_generator.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,40 @@
import argparse
import io
import json
import tarfile
import tempfile
import xml.etree.ElementTree as ElementTree
from datetime import datetime
from pathlib import Path
from re import findall
from re import findall, match
from typing import Dict, Generator, Tuple

import requests

RESOURCE = "https://raw.githubusercontent.com/google/libphonenumber/master/resources/PhoneNumberMetadata.xml"
argparser = argparse.ArgumentParser(
prog="pattern_generator",
add_help=True,
description="Pattern generator to phone-gen",
)
argparser.add_argument(
"-t", "--tag", dest="tag", help="libphonenumber tag", default="latest"
)

root = Path(__file__).absolute().parent.parent

TEMPLATE = """# -*- coding: utf-8 -*-
\"""
Auto-generated file {datetime} UTC
Resource: https://github.com/google/libphonenumber {version}
\"""
PATTERNS = {patterns}
"""
XML_FILE = "PhoneNumberMetadata.xml"
ARCHIVE_PATH = "libphonenumber-{version}/resources/{file}"
SOURCE_TAG = "https://github.com/google/libphonenumber/archive/{tag}.tar.gz"


class RegexCompiler:
Expand Down Expand Up @@ -65,22 +80,50 @@ def get_latest() -> str:
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,
def parsing_xml(file: Path):
with file.open("rb") as _file:
parser = Parser(_file.read().decode())
return {code: value for code, value in parser.render()}


def parsing_version(tag: str) -> str:
version = match(
r".*(?P<major>\d{1,2})\.(?P<minor>\d{1,2})\.(?P<patch>\d{1,2}).*", tag
)
if version:
return "{}.{}.{}".format(
version.group("major"), version.group("minor"), version.group("patch")
)
_file.write(temp.encode())
raise ValueError("Invalid tag: {}".format(version))


def main():
args = argparser.parse_args()
tag = get_latest() if args.tag == "latest" else args.tag
if tag:
version = parsing_version(tag)
with tempfile.TemporaryDirectory() as tmpdir:
response = requests.get(SOURCE_TAG.format(tag=tag), stream=True)
if not response.ok:
raise ValueError("Invalid tag: {}".format(tag))
with tarfile.open(fileobj=io.BytesIO(response.content)) as tar_file:
archive_path = ARCHIVE_PATH.format(version=version, file=XML_FILE)
tar_file.extract(archive_path, tmpdir)
xml_file = Path(tmpdir, archive_path)
if not xml_file.exists():
raise FileNotFoundError(xml_file.absolute())
data = parsing_xml(xml_file)
patterns_path = root.joinpath("phone_gen", "patterns.py")
with patterns_path.open("wb") as _file:
temp = TEMPLATE.format(
datetime=datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"),
patterns=json.dumps(
{"info": "libphonenumber {}".format(tag), "data": data},
indent=4,
),
version=tag,
)
_file.write(temp.encode())


if __name__ == "__main__":
Expand Down
8 changes: 5 additions & 3 deletions phone_gen/_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,6 @@ def _get_sequence(self, level: int = 0) -> Sequence:
seq.append(SequenceOR([left_operand, right_operand]))
op = ""
left_operand = None
# right_operand = None

# check for syntax errors
if op:
Expand All @@ -281,6 +280,9 @@ def __init__(self, value: str):
raise PhoneNumberNotFound('Not found country "{}"'.format(value))
self._generator = NumberGenerator(self._country["pattern"])

def __str__(self):
return "<PhoneNumber({})>".format(self.info())

def _find(self, value: str):
country = PATTERNS["data"].get(value)
if country:
Expand All @@ -304,8 +306,8 @@ def _find(self, value: str):
def _preparation(value: str) -> str:
return re.sub(r"\W", "", value).upper()

@property
def info(self) -> str:
@staticmethod
def info() -> str:
return PATTERNS["info"]

def get_code(self) -> str:
Expand Down
5 changes: 4 additions & 1 deletion phone_gen/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
description="International phone number generation",
)
parser.add_argument(
"-v", "--version", action="version", version="%(prog)s {}".format(__version__)
"-v",
"--version",
action="version",
version="%(prog)s {} ({})".format(__version__, PhoneNumber.info()),
)
parser.add_argument(
"country",
Expand Down
8 changes: 6 additions & 2 deletions phone_gen/patterns.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Auto-generated file 2020-05-21 09:13:58 UTC
# Resource: https://github.com/google/libphonenumber v8.12.4
# -*- coding: utf-8 -*-
"""
Auto-generated file 2020-05-26 13:43:30 UTC
Resource: https://github.com/google/libphonenumber v8.12.4
"""


PATTERNS = {
"info": "libphonenumber v8.12.4",
Expand Down
1 change: 1 addition & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Software Development :: Testing',
Expand Down
10 changes: 8 additions & 2 deletions tests/test_phone.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,15 @@
@pytest.mark.parametrize('count', range(15))
@pytest.mark.parametrize('country', PATTERNS['data'].keys())
def test_patterns(country, count):
number = PhoneNumber(country).get_number()
phone_number = PhoneNumber(country)
number = phone_number.get_number()
num_obj = phonenumbers.parse(number, country)
assert phonenumbers.is_valid_number_for_region(num_obj, country)


def test_info():
phone_number = PhoneNumber('gb')
assert phone_number.info.startswith('libphonenumber')
assert phone_number.info().startswith('libphonenumber')


def test_get_code():
Expand All @@ -30,3 +31,8 @@ def test_get_code():
def test_invalid_country():
with pytest.raises(PhoneNumberNotFound):
PhoneNumber('qwe')


def test_str_method():
phone_number = PhoneNumber('GB')
assert str(phone_number).startswith('<PhoneNumber(libphonenumber')

0 comments on commit 1af594a

Please sign in to comment.