Skip to content

Commit

Permalink
First commit.
Browse files Browse the repository at this point in the history
  • Loading branch information
DustinMoriarty committed Nov 25, 2020
0 parents commit 87fd4b5
Show file tree
Hide file tree
Showing 12 changed files with 944 additions and 0 deletions.
138 changes: 138 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# 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/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# JetBrains
.idea/

# vim
*.swp

# build
.dist
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 DustinMoriarty

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.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# config-injector
A simple json configuration dependency injector framework.
Empty file added config_injector/__init__.py
Empty file.
2 changes: 2 additions & 0 deletions config_injector/config/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import config_injector.config.exc
from config_injector.config.config import Config, config
112 changes: 112 additions & 0 deletions config_injector/config/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
from abc import ABC
from typing import (Any, Callable, Dict, List, SupportsFloat, SupportsInt,
Text, Tuple, Union)

from config_injector.config.exc import (DoesNotSupportBuild,
InvalidConfigValue, KeyNotInConfig,
TypeNotDefined)
from config_injector.config.utils import get_type

JsonTypes = Union[Dict, List, bool, SupportsInt, SupportsFloat, Text]
ComponentCallable = Union[Any, Tuple[Any]]


class SupportsBuild(ABC):
def __build__(self, **kwargs: Dict):
...


def build(f: SupportsBuild, config: Dict) -> Any:
try:
return f.__build__(**config)
except AttributeError as e:
if not hasattr(f, "__build__"):
raise DoesNotSupportBuild(f"{f} does not support build.", e)
else:
raise e


class Config(SupportsBuild):
def __init__(self, callback: Callable, **arg_callables: ComponentCallable):
"""
A configurable component containing hints for json parsing.
:param callback: The function to call. The function should return an object.
:param arg_callables: The callables for the arguments to the callback with matching
argument names. These callables can be overloaded by providing a tuple.
"""
self.callback = callback
self.arg_callables = arg_callables

def __call__(self, *args, **kwargs) -> Any:
return self.callback(*args, **kwargs)

@property
def __name__(self):
if hasattr(self.callback, "__name__"):
return self.callback.__name__
else:
raise AttributeError(f"{self.callback} has no attribute {__name__}")

def get_arg_type(self, arg_name, arg):
_arg_tp = self.arg_callables[arg_name]
try:
type_map = {get_type(x): x for x in _arg_tp}
except TypeError:
type_map = None
if type_map:
# Handle "oneOf" types defined with a type property.
try:
type_name = arg.pop("type")
except KeyError:
raise KeyNotInConfig(
f"Config key type not found in configuration arguments for {arg_name}"
)
except TypeError:
raise InvalidConfigValue(f"Config value for {arg_name} is invalid.")
try:
arg_tp = type_map[type_name]
except KeyError:
raise TypeNotDefined(
f"Configuration type {type_name} not defined for {arg_name}"
)
else:
arg_tp = _arg_tp
return arg_tp

def __build__(self, **kwargs: JsonTypes) -> Any:
"""
Cast data from parsed json prior to calling the callback.
:param kwargs: Key word arguments consisting of only json types.
:return:
"""
kwargs_cast = {}
for arg_name, arg in kwargs.items():
arg_tp = self.get_arg_type(arg_name, arg)
if arg_name in self.arg_callables:
if hasattr(arg, "items") and hasattr(arg_tp, "__build__"):
arg_cast = build(arg_tp, arg)
else:
arg_cast = arg_tp(arg)
else:
arg_cast = arg
kwargs_cast[arg_name] = arg_cast
return self(**kwargs_cast)


def config(**arg_callables: ComponentCallable) -> Callable[[], Config]:
"""
Decorator for functions with hints for json decoding.
:param key: The key to use for the configuration.
:param kwargs: The type for each argument in the function f.
:return:
"""

def wrapper(f) -> Config:
_key = get_type(f)
component = Config(f, **arg_callables)
return component

return wrapper
30 changes: 30 additions & 0 deletions config_injector/config/exc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
class ConfigError(Exception):
...


class ComponentNotFound(ConfigError):
...


class KeyNotInConfig(ConfigError):
...


class InvalidConfigKey(ConfigError):
...


class TypeNotDefined(ConfigError):
...


class AppMergeCollisions(ConfigError):
...


class InvalidConfigValue(ConfigError):
...


class DoesNotSupportBuild(ConfigError):
...
5 changes: 5 additions & 0 deletions config_injector/config/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from typing import Callable


def get_type(f: Callable):
return f.__name__
Loading

0 comments on commit 87fd4b5

Please sign in to comment.