Commit 74a7f851 authored by Wim Van de Meerssche's avatar Wim Van de Meerssche
Browse files

first version

parents
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
#PyCharms
.idea
#pytest caches
.pytest_cache
*/.pytest_cache
Copyright 2021 Wim Van de Meerssche
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# wvdemeer utils
A collection of functions that I find useful in various projects.
These assorted utils are all lightweight and have no dependencies.
This is all MIT license, so you are free to copy only what you need.
Overview:
- `sentry_utils.py` has `find_sentry_release_id` which is used to automatically find the sentry release.
- `urn_util.py` contains function for working with a specific type (["geni"](https://groups.geni.net/geni/wiki/GeniApiIdentifiers)) of URN.
- `validation_utils.py` has functions to validate ssh keys, emails and UUIDs
- `utils.py` contains a wide range of useful functions:
- `normalize_depenv` returns "staging" or "production"
- `datetime_now` returns "now" as a timezone aware datetime. (naive datetimes are evil!)
- `any_to_{opt_}bool` converts to bool
- `duration_string_to_seconds` parses string like "3 days" into a number of seconds
- `deep_update_dict` merges a dict into another
- `strip_null_from_json_dict` strips None and empty lists/dicts from a dict (useful to clean up json)
from setuptools import setup
import pathlib
setup(
name="wvdemeer-utils",
version="1.0.0",
description="A collection of useful functions",
long_description=(pathlib.Path(__file__).parent / "README.md").read_text(),
long_description_content_type="text/markdown",
url="https://gitlab.ilabt.imec.be/wvdemeer/wvdemeer-py-utils",
author="Wim Van de Meerssche",
author_email="wim.vandemeerssche@ugent.be",
license="MIT",
classifiers=[
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 3",
],
packages=["wvdemeer_utils"],
include_package_data=True,
install_requires=[],
python_requires='>=3.5',
# Tests with py.test: run with: python setup.py pytest
setup_requires=['pytest-runner'],
tests_require=['pytest'],
zip_safe=False,
)
import pytest
import copy
import json
from wvdemeer_utils.utils import deep_update_dict
def test_deep_update_dict_1():
orig = {
'a': 'aa',
'b': 2,
'c': 'cc',
'd': ['dd'],
}
extra = {
'a': 'aachanged',
'b': 'bb',
'd': 4,
'e': 'ee',
}
expected = {
'a': 'aachanged',
'b': 'bb',
'c': 'cc',
'd': 4,
'e': 'ee',
}
actual = copy.deepcopy(orig)
deep_update_dict(actual, extra)
# Use json so that keys are sorted (and indent to easily show differences)
actual_json = json.dumps(actual, sort_keys=True, indent=4)
expected_json = json.dumps(expected, sort_keys=True, indent=4)
print("\nactual ={}".format(actual_json))
print("expected={}".format(expected_json))
assert actual_json == expected_json
def test_deep_update_dict_2():
orig = {
'a': {
'b': {
'c1': 'c1',
'c2': 'c2',
'c3': 'c3'
}
}
}
extra = {
'a': {
'b': {
'c1': 'c1c',
'c2': 2,
'c4': 'c4'
}
}
}
expected = {
'a': {
'b': {
'c1': 'c1c',
'c2': 2,
'c3': 'c3',
'c4': 'c4'
}
}
}
actual = copy.deepcopy(orig)
deep_update_dict(actual, extra)
# Use json so that keys are sorted (and indent to easily show differences)
actual_json = json.dumps(actual, sort_keys=True, indent=4)
expected_json = json.dumps(expected, sort_keys=True, indent=4)
print("\nactual ={}".format(actual_json))
print("expected={}".format(expected_json))
assert actual_json == expected_json
def test_deep_update_dict_all():
orig = {
'a': 'aa',
'b': 1,
'c': {
'o': 'oo',
'p': 8,
'q': {
'qa': 'ok'
},
'qq': {
'qqb': 'ok'
}
},
'd': ['x', 'y', {'z' : 'zz' }]
}
extra = {
'ag': 'ggg',
'b': 2,
'c': {
'o': 'oochanged',
'pp': 88,
'q': {
'qa': 'stillok',
'qa2': 'alsook'
},
'qq': {
'qqb': {'A': 'A'},
'qqbb': {'B': 'B'}
}
},
'd': ['x', {'p': 'pp'}]
}
expected = {
'a': 'aa',
'ag': 'ggg',
'b': 2,
'c': {
'o': 'oochanged',
'pp': 88,
'p': 8,
'q': {
'qa': 'stillok',
'qa2': 'alsook'
},
'qq': {
'qqb': {'A': 'A'},
'qqbb': {'B': 'B'}
}
},
'd': ['x', {'p': 'pp'}]
}
actual = copy.deepcopy(orig)
deep_update_dict(actual, extra)
# Use json so that keys are sorted (and indent to easily show differences)
actual_json = json.dumps(actual, sort_keys=True, indent=4)
expected_json = json.dumps(expected, sort_keys=True, indent=4)
print("\nactual ={}".format(actual_json))
print("expected={}".format(expected_json))
assert actual_json == expected_json
import pytest
import copy
import datetime
from wvdemeer_utils.utils import duration_string_to_seconds, strip_null_from_json_dict, datetime_now
def test_now1():
actual = datetime_now(zulu=True, no_milliseconds=True)
assert actual.microsecond == 0
assert actual.isoformat().endswith('+00:00')
def test_now2():
actual = datetime_now(zulu=True, no_milliseconds=False)
# Very small chance microsecond happens to be exactly 0, which will make this test fail.
# Not sure how to solve that...
assert actual.microsecond != 0
assert actual.isoformat().endswith('+00:00')
# def test_now3():
# zulu_tz = datetime.timezone(datetime.timedelta(hours=0), name="UTC")
#
# actual = datetime_now(zulu=False, no_milliseconds=True)
# print('local timezone offset = {}'.format(tzlocal()._std_offset))
# if tzlocal()._std_offset == 0 or tzlocal()._dst_offset == 0:
# return # cannot test when local timezone is UTC or near it
# assert actual.microsecond == 0
# actual_str = dump_rfc3339(actual, zulu=False, no_milliseconds=False)
# print('actual_str = {}'.format(actual_str))
# assert not actual_str.endswith('Z') and not actual_str.endswith('00:00')
def test_duration_string_to_seconds_a():
assert duration_string_to_seconds('5 mins') == 5 * 60
assert duration_string_to_seconds('5 hour') == 5 * 60 * 60
assert duration_string_to_seconds('5 s') == 5
assert duration_string_to_seconds('5 days') == 5 * 60 * 60 * 24
assert duration_string_to_seconds('5 week') == 5 * 60 * 60 * 24 * 7
def test_duration_string_to_seconds_b():
assert duration_string_to_seconds('5m') == 5 * 60
assert duration_string_to_seconds('5h') == 5 * 60 * 60
assert duration_string_to_seconds('5secs') == 5
assert duration_string_to_seconds('5day') == 5 * 60 * 60 * 24
assert duration_string_to_seconds('5weeks') == 5 * 60 * 60 * 24 * 7
def test_duration_string_to_seconds_c():
assert duration_string_to_seconds('0.5 minutes') == 30
assert duration_string_to_seconds('0.25 hours') == 15 * 60
assert duration_string_to_seconds('0.125 day') == 3 * 60 * 60
assert duration_string_to_seconds('0.1 weeks') == 6 * 60 * 24 * 7
def test_duration_string_to_seconds_d():
assert duration_string_to_seconds(None) is None
assert duration_string_to_seconds('5') is None
assert duration_string_to_seconds('5x') is None
assert duration_string_to_seconds('5year') is None
assert duration_string_to_seconds('5 month') is None
STRIP_NULL_TEST_DICT = {
'testA1': 'ok',
'testA2': None,
'testA3': ['ok'],
'testA4': {'ok': 'ok'},
'testA5': [],
'testA6': {},
'nested': {
'testB1': 'ok',
'testB2': None,
'testB3': ['ok'],
'testB4': {'ok': 'ok'},
'testB5': [],
'testB6': {},
'nesteddeep': {
'testC1': 'ok',
'testC2': None,
'testC3': ['ok'],
'testC4': {'ok': 'ok'},
'testC5': [],
'testC6': {}
}
}
}
def test_strip_null_from_json_dict_a():
dict_in = STRIP_NULL_TEST_DICT
orig = copy.deepcopy(dict_in)
expected = {
'testA1': 'ok',
'testA3': ['ok'],
'testA4': {'ok': 'ok'},
'testA5': [],
'testA6': {},
'nested': {
'testB1': 'ok',
'testB3': ['ok'],
'testB4': {'ok': 'ok'},
'testB5': [],
'testB6': {},
'nesteddeep': {
'testC1': 'ok',
'testC3': ['ok'],
'testC4': {'ok': 'ok'},
'testC5': [],
'testC6': {},
}
}
}
actual = strip_null_from_json_dict(dict_in)
assert orig == dict_in, 'original should not be modified!'
assert actual == expected
def test_strip_null_from_json_dict_b():
dict_in = STRIP_NULL_TEST_DICT
orig = copy.deepcopy(dict_in)
expected = {
'testA1': 'ok',
'testA3': ['ok'],
'testA4': {'ok': 'ok'},
'testA6': {},
'nested': {
'testB1': 'ok',
'testB3': ['ok'],
'testB4': {'ok': 'ok'},
'testB6': {},
'nesteddeep': {
'testC1': 'ok',
'testC3': ['ok'],
'testC4': {'ok': 'ok'},
'testC6': {},
}
}
}
actual = strip_null_from_json_dict(dict_in, strip_empty_list=True)
assert orig == dict_in, 'original should not be modified!'
assert actual == expected
def test_strip_null_from_json_dict_c():
dict_in = STRIP_NULL_TEST_DICT
orig = copy.deepcopy(dict_in)
expected = {
'testA1': 'ok',
'testA3': ['ok'],
'testA4': {'ok': 'ok'},
'testA5': [],
'nested': {
'testB1': 'ok',
'testB3': ['ok'],
'testB4': {'ok': 'ok'},
'testB5': [],
'nesteddeep': {
'testC1': 'ok',
'testC3': ['ok'],
'testC4': {'ok': 'ok'},
'testC5': [],
}
}
}
actual = strip_null_from_json_dict(dict_in, strip_empty_dict=True)
assert orig == dict_in, 'original should not be modified!'
assert actual == expected
def test_strip_null_from_json_dict_d():
dict_in = STRIP_NULL_TEST_DICT
orig = copy.deepcopy(dict_in)
expected = {
'testA1': 'ok',
'testA3': ['ok'],
'testA4': {'ok': 'ok'},
'nested': {
'testB1': 'ok',
'testB3': ['ok'],
'testB4': {'ok': 'ok'},
'nesteddeep': {
'testC1': 'ok',
'testC3': ['ok'],
'testC4': {'ok': 'ok'},
}
}
}
actual = strip_null_from_json_dict(dict_in, strip_empty_dict=True, strip_empty_list=True)
assert orig == dict_in, 'original should not be modified!'
assert actual == expected
def test_strip_null_from_json_dict_e():
dict_in = copy.deepcopy(STRIP_NULL_TEST_DICT)
dict_in['testA7'] = {
'removeme1': None,
'removeme2': [],
'removeme3': {},
'nestedremoveme': {
'removeme1': None,
'removeme2': [],
'removeme3': {},
}
}
orig = copy.deepcopy(dict_in)
expected = {
'testA1': 'ok',
'testA3': ['ok'],
'testA4': {'ok': 'ok'},
'nested': {
'testB1': 'ok',
'testB3': ['ok'],
'testB4': {'ok': 'ok'},
'nesteddeep': {
'testC1': 'ok',
'testC3': ['ok'],
'testC4': {'ok': 'ok'},
}
}
}
actual = strip_null_from_json_dict(dict_in, strip_empty_dict=True, strip_empty_list=True)
assert orig == dict_in, 'original should not be modified!'
assert actual == expected
import logging
import re
from subprocess import PIPE, STDOUT, Popen
from typing import Optional
from pathlib import Path
def _call_git(*params: str, **kwargs) -> str:
res = ''
com = ['git']
com.extend(params)
kwargs['stdout'] = PIPE
kwargs['stderr'] = STDOUT
kwargs['universal_newlines'] = True
# Annoyingly, git doesn't seem to listen to GIT_ASKPASS and SSH_ASKPASS, and use TTY to get pass.
# Solution: from TTY: use "setsid -w <git command>"
# not from TTY: should work
with open('/dev/null', 'r') as devnull:
kwargs['stdin'] = devnull
with Popen(com, **kwargs) as proc:
for line in proc.stdout:
res += line
res_code = proc.wait()
if res_code != 0:
raise Exception('Command returned error ({}): {} (command={} )'.format(res_code, res.strip(), com))
return res.strip()
def _call_sentry_cli(*params: str, **kwargs) -> str:
res = ''
com = ['sentry-cli']
com.extend(params)
kwargs['stdout'] = PIPE
kwargs['stderr'] = STDOUT
kwargs['universal_newlines'] = True
with Popen(com, **kwargs) as proc:
for line in proc.stdout:
res += line
res_code = proc.wait()
if res_code != 0:
raise Exception('Command returned error ({}): {} (command={} )'.format(res_code, res.strip(), com))
return res.strip()
def _find_git_sha(repo_filename: str) -> Optional[str]:
source_path = Path(repo_filename).resolve()
if not source_path:
return None
source_dir = source_path.parent
if not source_dir:
return None
try:
res = _call_git("rev-parse", "HEAD", cwd=source_dir).strip()
assert re.compile(r'^([0-9a-f]+)$').match(res)
assert len(res) > 10
return res
except:
logging.error('Failed "git rev-parse head" in "{}" (will ignore)'.format(source_dir), exc_info=True)
return None
def _find_git_branch(repo_filename: str) -> Optional[str]:
source_path = Path(repo_filename).resolve()
if not source_path:
return None
source_dir = source_path.parent
if not source_dir:
return None
try:
res = _call_git("rev-parse", "--abbrev-ref", "HEAD", cwd=source_dir).strip()
assert re.compile(r'^([^ ]+)$').match(res)
assert len(res) > 3
return res
except:
logging.error('Failed "git rev-parse --abbrev-ref HEAD" in "{}" (will ignore)'.format(source_dir), exc_info=True)
return None
def find_sentry_release_id(repo_filename: str) -> Optional[str]:
try:
res = _call_sentry_cli("releases", "propose-version").strip()