Skip to content

Commit

Permalink
major update
Browse files Browse the repository at this point in the history
  • Loading branch information
knowsuchagency committed Jun 27, 2017
1 parent 185b4a8 commit dfe5fb5
Show file tree
Hide file tree
Showing 11 changed files with 103 additions and 191 deletions.
1 change: 0 additions & 1 deletion ninjadog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,3 @@
__version__ = '0.2.2'

from ninjadog.ninjadog import render
from ninjadog.ext.jinja2 import jinja2_renderer
54 changes: 54 additions & 0 deletions ninjadog/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""ninjadog v0.2.2
Usage:
ninjadog string [options] <string>
ninjadog file [options] <file>
ninjadog - [options]
ninjadog -h | --help
ninjadog --version
Options:
-h --help show help and exit
-V --version show version and exit
-f --file <file> the filepath to the template
-p --pretty pretty print output
-c --context <context> json string to be passed as context
-j --with-jinja render jinja2 syntax as well as pug
-v --verbose verbose output
Render pug templates to html.
Use "-" to read from stdin i.e. echo "h1 hello" | ninjadog -
"""
from docopt import docopt
import sys

from ninjadog import render


def main():
"""Render pug template to stdout."""
args = docopt(__doc__, argv=None, version='0.2.2')

if args['--file'] and args['<file>']:
raise ValueError("Cannot combine --file and <file> arguments")

string = sys.stdin.read() if args['-'] else args['<string>']
file = args['--file'] or args['<file>']
pretty = args['--pretty']
context = args['--context']
with_jinja = args['--with-jinja']
verbose = args['--verbose']

output = render(string=string, file=file, pretty=pretty, context=context, with_jinja=with_jinja)

if verbose:
print(args, file=sys.stderr, end='\n\n')

print(output)


if __name__ == "__main__":
main()
6 changes: 2 additions & 4 deletions ninjadog/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
import typing as T
from pathlib import Path

EXTENSION_PATT: re.sre_parse.Pattern
PUG_CLI_PATH: T.Optional[Path]

EXTENSION_PATT = re.compile('(?:extends|include)\s+(.+)')
PUG_CLI_PATH = Path(sp.run(('which', 'pug'), stdout=sp.PIPE).stdout.decode('utf8').strip()) \
if sp.run(('which', 'npm'), stdout=sp.DEVNULL).returncode == 0 else None
PUG_CLI_PATH = str(Path(sp.Popen(('which', 'pug'), stdout=sp.PIPE).communicate()[0].decode('utf8').strip()).absolute()) \
if sp.Popen(('which', 'npm'), stdout=sp.DEVNULL).wait() == 0 else None

69 changes: 0 additions & 69 deletions ninjadog/ext/jinja2.py

This file was deleted.

2 changes: 1 addition & 1 deletion ninjadog/ext/pyramid/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __call__(self, value, system):
'as value: %s' % str(ex))
template = self.template_loader()
jinja2_string = template.render(system)
with_pug = render(jinja2_string, filepath=template.filename, context=system)
with_pug = render(jinja2_string, file=template.filename, context=system)
return with_pug


Expand Down
44 changes: 21 additions & 23 deletions ninjadog/ninjadog.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import subprocess as sp
import typing as T
from pathlib import Path
from tempfile import NamedTemporaryFile

from ninjadog.constants import PUG_CLI_PATH
from ninjadog.utils import jsonify
Expand All @@ -14,17 +13,17 @@


def render(string: str = '',
filepath: T.Union[Path, str] = None,
file: T.Union[Path, str] = None,
context: T.Any = None,
pretty: bool = False,
pug_cli_path: T.Union[Path, str] = None,
pug_cli_path: str = None,
with_jinja: bool = False) -> str:
"""
Render a pug template through the pug cli.
Args:
string: a string in pug syntax to be rendered
filepath: the path to a pug template
file: the path to a pug template
context: the data to be passed to the template
pretty: pretty html output
pug_cli_path: path to the pug cli
Expand All @@ -42,46 +41,45 @@ def render(string: str = '',
elif pug_cli_path is None:
pug_cli_path = PUG_CLI_PATH

# create Path object if filepath argument is given
# create Path object if file argument is given
# Path() is idempotent so this shouldn't make any difference
# if the filepath argument is of type Path
filepath = Path(filepath) if filepath else filepath
# if the file argument is of type Path
filepath = Path(str(file)) if file else file

# if filepath is given instead of a string argument,
# return render of string
if filepath and not string:
with open(filepath) as fp:
with filepath.open() as fp:
return render(fp.read(),
filepath,
context=context,
pretty=pretty,
pug_cli_path=pug_cli_path)


cmd = shlex.quote(str((Path(pug_cli_path).absolute())))
path = f'-p {shlex.quote(str(filepath))}' if filepath else ''
cmd = shlex.quote(pug_cli_path)
path = '-p {}'.format(shlex.quote(str(filepath))) if filepath else ''
pretty_print = '-P' if pretty else ''

if context is None:
context_arg = ''
elif isinstance(context, str):
context_arg = f'-O {shlex.quote(context)}'
context_arg = '-O {}'.format(shlex.quote(context))
else:
context_arg = f'-O {shlex.quote(jsonify(context))}'
context_arg = '-O {}'.format(shlex.quote(jsonify(context)))

pug_cli = sp.Popen(shlex.split('{} {} {} {}'.format(cmd, context_arg, path, pretty_print)),
stdin=sp.PIPE,
stdout=sp.PIPE,
cwd=str(filepath.parent) if filepath else None,
universal_newlines=True,
)
html, _ = pug_cli.communicate(string)

pug_cli = sp.Popen(shlex.split(f'{cmd} {context_arg} {path} {pretty_print}'),
stdin=sp.PIPE,
stdout=sp.PIPE,
cwd=filepath.parent if filepath else None,
)
pug_cli.stdin.write(string.encode('utf8'))
pug_cli.stdin.close()
pug_string = pug_cli.stdout.read().decode('utf8')

if with_jinja:
env = Environment()
env.globals = context if context else {}

return env.from_string(pug_string).render()
return env.from_string(html).render()

return pug_string
return html
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ venusian==1.1.0
WebOb==1.7.2
zope.deprecation==4.2.0
zope.interface==4.4.2
docopt==0.6.2
2 changes: 2 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ replace = version='{new_version}'
search = __version__ = '{current_version}'
replace = __version__ = '{new_version}'

[bumpversion:file:ninjadog/cli.py]

[bdist_wheel]
universal = 1

Expand Down
5 changes: 5 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,14 @@
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
],
test_suite='tests',
tests_require=test_requirements,
setup_requires=setup_requirements,
entry_points = {
'console_scripts': ['ninjadog=ninjadog.cli:main']
}
)

0 comments on commit dfe5fb5

Please sign in to comment.