Skip to content

Commit

Permalink
Formatted with black
Browse files Browse the repository at this point in the history
  • Loading branch information
mattrobenolt committed Aug 27, 2018
1 parent 703ba5f commit d7cc507
Show file tree
Hide file tree
Showing 4 changed files with 106 additions and 88 deletions.
4 changes: 2 additions & 2 deletions jinja2cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
License: BSD, see LICENSE for more details.
"""

__author__ = 'Matt Robenolt'
__version__ = '0.7.0.dev0'
__author__ = "Matt Robenolt"
__version__ = "0.7.0.dev0"

from .cli import main # NOQA
144 changes: 83 additions & 61 deletions jinja2cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,15 +69,17 @@ def get_available_formats():
yield fmt
except InvalidDataFormat:
pass
yield 'auto'
yield "auto"


def _load_json():
try:
import json

return json.loads, ValueError, MalformedJSON
except ImportError:
import simplejson

return simplejson.loads, simplejson.decoder.JSONDecodeError, MalformedJSON


Expand All @@ -98,7 +100,7 @@ def as_dict(self):
d = dict(self._sections)
for k in d:
d[k] = dict(self._defaults, **d[k])
d[k].pop('__name__', None)
d[k].pop("__name__", None)
return d

p = MyConfigParser()
Expand All @@ -110,6 +112,7 @@ def as_dict(self):

def _load_yaml():
import yaml

return yaml.load, yaml.YAMLError, MalformedYAML


Expand All @@ -129,8 +132,8 @@ def _parse_qs(data):
for k, v in urlparse.parse_qs(data).items():
v = map(lambda x: x.strip(), v)
v = v[0] if len(v) == 1 else v
if '.' in k:
pieces = k.split('.')
if "." in k:
pieces = k.split(".")
cur = dict_
for idx, piece in enumerate(pieces):
if piece not in cur:
Expand All @@ -141,17 +144,20 @@ def _parse_qs(data):
else:
dict_[k] = v
return dict_

return _parse_qs, Exception, MalformedQuerystring


def _load_toml():
import toml

return toml.loads, Exception, MalformedToml


def _load_xml():
import xml
import xmltodict

return xmltodict.parse, xml.parsers.expat.ExpatError, MalformedXML


Expand All @@ -164,25 +170,26 @@ def _parse_env(data):
for line in data.splitlines():
line = line.lstrip()
# ignore empty or commented lines
if not line or line[:1] == '#':
if not line or line[:1] == "#":
continue
k, v = line.split('=', 1)
k, v = line.split("=", 1)
dict_[k] = v
return dict_

return _parse_env, Exception, MalformedEnv


# Global list of available format parsers on your system
# mapped to the callable/Exception to parse a string into a dict
formats = {
'json': _load_json,
'ini': _load_ini,
'yaml': _load_yaml,
'yml': _load_yaml,
'querystring': _load_querystring,
'toml': _load_toml,
'xml': _load_xml,
'env': _load_env,
"json": _load_json,
"ini": _load_ini,
"yaml": _load_yaml,
"yml": _load_yaml,
"querystring": _load_querystring,
"toml": _load_toml,
"xml": _load_xml,
"env": _load_env,
}


Expand All @@ -202,39 +209,41 @@ def render(template_path, data, extensions, strict=False):
)
if strict:
from jinja2 import StrictUndefined

env.undefined = StrictUndefined

# Add environ global
env.globals['environ'] = os.environ.get
env.globals["environ"] = os.environ.get

output = env.get_template(os.path.basename(template_path)).render(data)
return output.encode('utf-8')
return output.encode("utf-8")


def is_fd_alive(fd):
if os.name == 'nt':
if os.name == "nt":
return not os.isatty(fd.fileno())
import select

return bool(select.select([fd], [], [], 0)[0])


def cli(opts, args):
format = opts.format
if args[1] == '-':
if args[1] == "-":
if is_fd_alive(sys.stdin):
data = sys.stdin.read()
else:
data = ''
if format == 'auto':
data = ""
if format == "auto":
# default to yaml first if available since yaml
# is a superset of json
if 'yaml' in formats:
format = 'yaml'
if "yaml" in formats:
format = "yaml"
else:
format = 'json'
format = "json"
else:
path = os.path.join(os.getcwd(), os.path.expanduser(args[1]))
if format == 'auto':
if format == "auto":
ext = os.path.splitext(path)[1][1:]
if ext in formats:
format = ext
Expand All @@ -250,26 +259,26 @@ def cli(opts, args):
try:
fn, except_exc, raise_exc = get_format(format)
except InvalidDataFormat:
if format in ('yml', 'yaml'):
raise InvalidDataFormat('%s: install pyyaml to fix' % format)
if format == 'toml':
raise InvalidDataFormat('toml: install toml to fix')
if format == 'xml':
raise InvalidDataFormat('xml: install xmltodict to fix')
if format in ("yml", "yaml"):
raise InvalidDataFormat("%s: install pyyaml to fix" % format)
if format == "toml":
raise InvalidDataFormat("toml: install toml to fix")
if format == "xml":
raise InvalidDataFormat("xml: install xmltodict to fix")
raise
try:
data = fn(data) or {}
except except_exc:
raise raise_exc(u'%s ...' % data[:60])
raise raise_exc(u"%s ..." % data[:60])
else:
data = {}

extensions = []
for ext in opts.extensions:
# Allow shorthand and assume if it's not a module
# path, it's probably trying to use builtin from jinja2
if '.' not in ext:
ext = 'jinja2.ext.' + ext
if "." not in ext:
ext = "jinja2.ext." + ext
extensions.append(ext)

data.update(parse_kv_string(opts.D or []))
Expand All @@ -280,26 +289,27 @@ def cli(opts, args):
if section in data:
data = data[section]
else:
sys.stderr.write('ERROR: unknown section. Exiting.')
sys.stderr.write("ERROR: unknown section. Exiting.")
return 1

output = render(template_path, data, extensions, opts.strict)

if isinstance(output, text_type):
output = output.encode('utf-8')
output = output.encode("utf-8")
sys.stdout.write(output)
return 0


def parse_kv_string(pairs):
return dict(pair.split('=', 1) for pair in pairs)
return dict(pair.split("=", 1) for pair in pairs)


class LazyHelpOption(Option):
"An Option class that resolves help from a callable"

def __setattr__(self, attr, value):
if attr == 'help':
attr = '_help'
if attr == "help":
attr = "_help"
self.__dict__[attr] = value

@property
Expand All @@ -316,31 +326,43 @@ def main():
parser = OptionParser(
option_class=LazyHelpOption,
usage="usage: %prog [options] <input template> <input data>",
version="jinja2-cli v%s\n - Jinja2 v%s" % (
__version__, jinja2.__version__),
version="jinja2-cli v%s\n - Jinja2 v%s" % (__version__, jinja2.__version__),
)
parser.add_option(
'--format',
help=lambda: 'format of input variables: %s' % ', '.join(
sorted(list(get_available_formats()))
),
dest='format', action='store', default='auto')
"--format",
help=lambda: "format of input variables: %s"
% ", ".join(sorted(list(get_available_formats()))),
dest="format",
action="store",
default="auto",
)
parser.add_option(
'-e', '--extension',
help='extra jinja2 extensions to load',
dest='extensions', action='append', default=['do', 'with_', 'autoescape', 'loopcontrols'])
"-e",
"--extension",
help="extra jinja2 extensions to load",
dest="extensions",
action="append",
default=["do", "with_", "autoescape", "loopcontrols"],
)
parser.add_option(
'-D',
help='Define template variable in the form of key=value',
action='append', metavar='key=value')
"-D",
help="Define template variable in the form of key=value",
action="append",
metavar="key=value",
)
parser.add_option(
'-s', '--section',
help='Use only this section from the configuration',
dest='section', action='store')
"-s",
"--section",
help="Use only this section from the configuration",
dest="section",
action="store",
)
parser.add_option(
'--strict',
help='Disallow undefined variables to be used within the template',
dest='strict', action='store_true')
"--strict",
help="Disallow undefined variables to be used within the template",
dest="strict",
action="store_true",
)
opts, args = parser.parse_args()

# Dedupe list
Expand All @@ -350,19 +372,19 @@ def main():
parser.print_help()
sys.exit(1)

if args[0] == 'help':
if args[0] == "help":
parser.print_help()
sys.exit(1)

# Without the second argv, assume they want to read from stdin
if len(args) == 1:
args.append('-')
args.append("-")

if opts.format not in formats and opts.format != 'auto':
if opts.format not in formats and opts.format != "auto":
raise InvalidDataFormat(opts.format)

sys.exit(cli(opts, args))


if __name__ == '__main__':
if __name__ == "__main__":
main()
42 changes: 19 additions & 23 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,34 @@

from setuptools import setup, find_packages

install_requires = ['jinja2']
tests_requires = ['pytest', 'flake8<3']
install_requires = ["jinja2"]
tests_requires = ["pytest", "flake8<3"]

setup(
name='jinja2-cli',
version='0.7.0.dev0',
author='Matt Robenolt',
author_email='[email protected]',
url='https://github.com/mattrobenolt/jinja2-cli',
description='A CLI interface to Jinja2',
name="jinja2-cli",
version="0.7.0.dev0",
author="Matt Robenolt",
author_email="[email protected]",
url="https://github.com/mattrobenolt/jinja2-cli",
description="A CLI interface to Jinja2",
long_description=__doc__,
packages=find_packages(exclude=['tests']),
packages=find_packages(exclude=["tests"]),
zip_safe=False,
license='BSD',
license="BSD",
install_requires=install_requires,
extras_require={
'yaml': install_requires + ['pyyaml'],
'toml': install_requires + ['toml'],
'xml': install_requires + ['xmltodict'],
'tests': install_requires + tests_requires,
"yaml": install_requires + ["pyyaml"],
"toml": install_requires + ["toml"],
"xml": install_requires + ["xmltodict"],
"tests": install_requires + tests_requires,
},
tests_require=tests_requires,
include_package_data=True,
entry_points={
'console_scripts': [
'jinja2 = jinja2cli:main',
]
},
entry_points={"console_scripts": ["jinja2 = jinja2cli:main"]},
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Topic :: Software Development'
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"Operating System :: OS Independent",
"Topic :: Software Development",
],
)
4 changes: 2 additions & 2 deletions tests/test_jinja2cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def test_relative_path():

output = cli.render(path, {"title": "Test"}, [])
if isinstance(output, cli.binary_type):
output = output.decode('utf-8')
output = output.decode("utf-8")
assert output == "Test"


Expand All @@ -20,5 +20,5 @@ def test_absolute_path():

output = cli.render(path, {"title": "Test"}, [])
if isinstance(output, cli.binary_type):
output = output.decode('utf-8')
output = output.decode("utf-8")
assert output == "Test"

0 comments on commit d7cc507

Please sign in to comment.