Commit a4d8dcd6 authored by nimrod's avatar nimrod
Browse files

Use black formatter, added to pre-commit.

parent 97c0329c
Loading
Loading
Loading
Loading
+8 −2
Original line number Diff line number Diff line
-   repo: git://github.com/pre-commit/pre-commit-hooks
    sha: v0.8.0
repos:
-   repo: https://github.com/pre-commit/pre-commit-hooks
    sha: v1.2.3
    hooks:
    -   id: check-added-large-files
    -   id: check-yaml
    -   id: check-merge-conflict
    -   id: flake8
    -   id: check-symlinks
-   repo: https://github.com/ambv/black
    sha: 18.5b0
    hooks:
    -   id: black
        args: [--line-length=79]
+19 −22
Original line number Diff line number Diff line
@@ -2,29 +2,26 @@
from setuptools import setup, find_packages

setup(
    name='template',
    version=open('VERSION', 'r').read(),
    description='''A CLI tool for generating files from Jinja2 templates and
    environment variables.''',
    long_description=open('README.rst', 'r').read(),
    url='https://www.shore.co.il/git/template',
    author='Nimrod Adar',
    author_email='nimrod@shore.co.il',
    license='MIT',
    name="template",
    version=open("VERSION", "r").read(),
    description="""A CLI tool for generating files from Jinja2 templates and
    environment variables.""",
    long_description=open("README.rst", "r").read(),
    url="https://www.shore.co.il/git/template",
    author="Nimrod Adar",
    author_email="nimrod@shore.co.il",
    license="MIT",
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 2',
        'Intended Audience :: System Administrators',
        'Topic :: Utilities',
        "Development Status :: 4 - Beta",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 2",
        "Intended Audience :: System Administrators",
        "Topic :: Utilities",
    ],
    keywords='config configuration jinja template environment',
    keywords="config configuration jinja template environment",
    packages=find_packages(),
    install_requires=['Jinja2', 'PyYAML', 'jmespath', 'toml'],
    extras_require={
        'dev': ['tox'], },
    entry_points={
        'console_scripts': [
            'template=template:main'], },
    install_requires=["Jinja2", "PyYAML", "jmespath", "toml"],
    extras_require={"dev": ["tox"]},
    entry_points={"console_scripts": ["template=template:main"]},
)
+25 −14
Original line number Diff line number Diff line
#!/usr/bin/env python
'''Generate files from Jinja2 templates and environment variables.'''
"""Generate files from Jinja2 templates and environment variables."""

from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals,
)
from jinja2 import Environment
from os import environ
from sys import stdin, stdout
@@ -12,9 +16,10 @@ import template.filters


def render(template_string):
    """Render the template."""
    env = Environment(autoescape=True)
    # Add all functions in template.filters as Jinja filters.
    for tf in filter(lambda x: not x.startswith('_'), dir(template.filters)):
    for tf in filter(lambda x: not x.startswith("_"), dir(template.filters)):
        env.filters[tf] = template.filters.__getattribute__(tf)
    t = env.from_string(template_string)
    return t.render(environ)
@@ -22,20 +27,26 @@ def render(template_string):

def main():
    parser = ArgumentParser(
        description='''A CLI tool for generating files from Jinja2 templates
        and environment variables.''')
    parser.add_argument('filename',
                        help='Input filename',
                        type=argparse.FileType('r'),
                        nargs='?')
    parser.add_argument('-o', '--output',
                        help='Output to filename',
                        type=argparse.FileType('w'))
        description="""A CLI tool for generating files from Jinja2 templates
        and environment variables."""
    )
    parser.add_argument(
        "filename",
        help="Input filename",
        type=argparse.FileType("r"),
        nargs="?",
    )
    parser.add_argument(
        "-o",
        "--output",
        help="Output to filename",
        type=argparse.FileType("w"),
    )
    args = parser.parse_args()
    infd = args.filename if args.filename else stdin
    outfd = args.output if args.output else stdout
    print(render(infd.read()), file=outfd)


if __name__ == '__main__':
if __name__ == "__main__":
    main()
+29 −18
Original line number Diff line number Diff line
#!/usr/bin/env python
from __future__ import (absolute_import, division,
                        print_function, unicode_literals)
from __future__ import (
    absolute_import,
    division,
    print_function,
    unicode_literals,
)


def to_yaml(value):
    '''
    """
    Converts given data structure to YAML form.
    Examples:

@@ -16,13 +20,14 @@ def to_yaml(value):
    '1:\\n  a: [1, 2, 3]\\n'
    >>> to_yaml("abc")
    'abc\\n...\\n'
    '''
    """
    from yaml import safe_dump

    return safe_dump(value)


def to_json(value):
    '''
    """
    Converts given data structure to JSON form.
    Examples:

@@ -34,13 +39,14 @@ def to_json(value):
    '2'
    >>> to_json({1: {'a': [1,2,3]}})
    '{"1": {"a": [1, 2, 3]}}'
    '''
    """
    from json import dumps

    return dumps(value)


def from_json(value):
    '''
    """
    Returns native data structure from the given JSON string.
    Examples:

@@ -51,13 +57,14 @@ def from_json(value):
    True
    >>> from_json('{"1": {"a": [1, 2, 3]}}') == {'1': {'a': [1, 2, 3]}}
    True
    '''
    """
    from json import loads

    return loads(value)


def from_yaml(value):
    '''
    """
    Returns native data structure from the given YAML string.
    Examples:

@@ -67,49 +74,52 @@ def from_yaml(value):
    [1, 2, 3]
    >>> from_yaml('{"1": {"a": [1, 2, 3]}}')
    {'1': {'a': [1, 2, 3]}}
    '''
    """
    from yaml import safe_load

    return safe_load(value)


def combine(default, override):
    '''
    """
    Returns a combined dictionary of the 2 dictionaries given (with the 2nd
    overriding the 1st).
    Examples:
    >>> combine({'a': 1, 'b': 2}, {'b': 3, 'c': 4}) == {'a': 1, 'b': 3, 'c': 4}
    True
    '''
    """
    combined = default.copy()
    combined.update(override)
    return combined


def from_toml(value):
    '''
    """
    Returns a data structure from the TOML string given.
    Examples:
    >>> from_toml('[table]\\nkey = "value"\\n') == {'table': {'key': 'value'}}
    True
    '''
    """
    from toml import loads

    return loads(value)


def to_toml(value):
    '''
    """
    Returns a string of the TOML representation for the data structure given.
    Examples:
    >>> import six
    >>> to_toml({'key': [1, 2]}) == six.text_type("key = [ 1, 2,]\\n")
    True
    '''
    """
    from toml import dumps

    return dumps(value)


def jmespath(value, query):
    '''
    """
    Queries the data using the JMESPath query language.
    Examples:
    >>> import six
@@ -125,6 +135,7 @@ def jmespath(value, query):
    ...  WACities == {'WashingtonCities': 'Bellevue, Olympia, Seattle'}
    ...
    True
    '''
    """
    import jmespath

    return jmespath.search(query, value)