Skip to content

Commit

Permalink
Remove strict dependencies on django, pygments, markdown, jinja2
Browse files Browse the repository at this point in the history
* addresses Issue #132
* include dependent functionality only if the required package
  is available
* duplicate TemplateDoesNotExist() if django is not present
* add `NotAvailableError` for nodes which depend on non-present
  packages
* move pygments_filter test into template tests
* fix test for Pygments version 1.6
  • Loading branch information
danring committed May 9, 2013
1 parent 1bbb479 commit adc1840
Show file tree
Hide file tree
Showing 18 changed files with 138 additions and 72 deletions.
5 changes: 1 addition & 4 deletions hamlpy/__init__.py
@@ -1,4 +1 @@
try:
import templatize
except ImportError:
pass
import templatize
30 changes: 18 additions & 12 deletions hamlpy/ext.py
@@ -1,5 +1,10 @@
# coding=utf-8
import jinja2.ext
try:
import jinja2.ext
_jinja2_available = True
except ImportError, e:
_jinja2_available = False

import hamlpy
import os

Expand All @@ -23,14 +28,15 @@ def has_any_extension(file_path, extensions):
file_ext = get_file_extension(file_path)
return file_ext and extensions and file_ext in [clean_extension(e) for e in extensions]

class HamlPyExtension(jinja2.ext.Extension):

def preprocess(self, source, name, filename=None):
if name and has_any_extension(name, HAML_FILE_NAME_EXTENSIONS):
compiler = hamlpy.Compiler()
try:
return compiler.process(source)
except Exception as e:
raise jinja2.TemplateSyntaxError(e, 1, name=name, filename=filename)
else:
return source
if _jinja2_available:
class HamlPyExtension(jinja2.ext.Extension):

def preprocess(self, source, name, filename=None):
if name and has_any_extension(name, HAML_FILE_NAME_EXTENSIONS):
compiler = hamlpy.Compiler()
try:
return compiler.process(source)
except Exception as e:
raise jinja2.TemplateSyntaxError(e, 1, name=name, filename=filename)
else:
return source
27 changes: 22 additions & 5 deletions hamlpy/nodes.py
Expand Up @@ -4,11 +4,22 @@

from elements import Element

from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer

from markdown import markdown
try:
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import guess_lexer
_pygments_available = True
except ImportError, e:
_pygments_available = False

try:
from markdown import markdown
_markdown_available = True
except ImportError, e:
_markdown_available = False

class NotAvailableError(Exception):
pass

ELEMENT = '%'
ID = '#'
Expand Down Expand Up @@ -567,6 +578,9 @@ def _render(self):
class PygmentsFilterNode(FilterNode):
def _render(self):
if self.children:
if not _pygments_available:
raise NotAvailableError("Pygments is not available")

self.before = self.render_newlines()
indent_offset = len(self.children[0].spaces)
text = ''.join(''.join([c.spaces[indent_offset:], c.haml, c.render_newlines()]) for c in self.children)
Expand All @@ -577,6 +591,9 @@ def _render(self):
class MarkdownFilterNode(FilterNode):
def _render(self):
if self.children:
if not _markdown_available:
raise NotAvailableError("Markdown is not available")

self.before = self.render_newlines()[1:]
indent_offset = len(self.children[0].spaces)
text = ''.join(''.join([c.spaces[indent_offset:], c.haml, c.render_newlines()]) for c in self.children)
Expand Down
25 changes: 17 additions & 8 deletions hamlpy/template/loaders.py
@@ -1,17 +1,26 @@
import os

from django.template import TemplateDoesNotExist
from django.template.loaders import filesystem, app_directories
try:
from django.template import TemplateDoesNotExist
from django.template.loaders import filesystem, app_directories
_django_available = True
except ImportError, e:
class TemplateDoesNotExist(Exception):
pass

_django_available = False

from hamlpy import hamlpy
from hamlpy.template.utils import get_django_template_loaders


# Get options from Django settings
options_dict = {}
from django.conf import settings
if hasattr(settings, 'HAMLPY_ATTR_WRAPPER'):
options_dict.update(attr_wrapper=settings.HAMLPY_ATTR_WRAPPER)

if _django_available:
from django.conf import settings
if hasattr(settings, 'HAMLPY_ATTR_WRAPPER'):
options_dict.update(attr_wrapper=settings.HAMLPY_ATTR_WRAPPER)


def get_haml_loader(loader):
Expand Down Expand Up @@ -54,6 +63,6 @@ def _generate_template_name(self, name, extension="hamlpy"):
haml_loaders = dict((name, get_haml_loader(loader))
for (name, loader) in get_django_template_loaders())


HamlPyFilesystemLoader = get_haml_loader(filesystem)
HamlPyAppDirectoriesLoader = get_haml_loader(app_directories)
if _django_available:
HamlPyFilesystemLoader = get_haml_loader(filesystem)
HamlPyAppDirectoriesLoader = get_haml_loader(app_directories)
8 changes: 7 additions & 1 deletion hamlpy/template/utils.py
Expand Up @@ -2,11 +2,17 @@
from os import listdir
from os.path import dirname, splitext

from django.template import loaders
try:
from django.template import loaders
_django_available = True
except ImportError, e:
_django_available = False

MODULE_EXTENSIONS = tuple([suffix[0] for suffix in imp.get_suffixes()])

def get_django_template_loaders():
if not _django_available:
return []
return [(loader.__name__.rsplit('.',1)[1], loader)
for loader in get_submodules(loaders)
if hasattr(loader, 'Loader')]
Expand Down
10 changes: 8 additions & 2 deletions hamlpy/templatize.py
Expand Up @@ -3,7 +3,12 @@
before the translation utility extracts tags from it.
"""

from django.utils.translation import trans_real
try:
from django.utils.translation import trans_real
_django_available = True
except ImportError, e:
_django_available = False

import hamlpy


Expand All @@ -15,5 +20,6 @@ def templatize(src, origin=None):

return templatize

trans_real.templatize = decorate_templatize(trans_real.templatize)
if _django_available:
trans_real.templatize = decorate_templatize(trans_real.templatize)

21 changes: 0 additions & 21 deletions hamlpy/test/hamlpy_test.py
Expand Up @@ -295,27 +295,6 @@ def test_xml_namespaces(self):
result = hamlParser.process(haml)
eq_(html, result)

def test_pygments_filter(self):
haml = '''
:highlight
print "hi"
if x:
print "y":
else:
print "z":
'''
html = '\n<div class="highlight"><pre><span class="n">print</span> &quot;<span class="n">hi</span>&quot;' \
+ '\n\n<span class="k">if</span> <span class="n">x</span><span class="p">:</span>' \
+ '\n <span class="n">print</span> &quot;<span class="n">y</span>&quot;<span class="p">:</span>' \
+ '\n<span class="k">else</span><span class="p">:</span>' \
+ '\n <span class="n">print</span> &quot;<span class="n">z</span>&quot;<span class="p">:</span>' \
+ '\n</pre></div>\n'

hamlParser = hamlpy.Compiler()
result = hamlParser.process(haml)
eq_(html, result)

def test_attr_wrapper(self):
haml = """
%html{'xmlns':'http://www.w3.org/1999/xhtml', 'xml:lang':'en', 'lang':'en'}
Expand Down
10 changes: 6 additions & 4 deletions hamlpy/test/loader_test.py
@@ -1,12 +1,14 @@
import unittest
import sys

from django.template.base import TemplateDoesNotExist
from django.conf import settings
try:
from django.conf import settings

settings.configure(DEBUG=True, TEMPLATE_DEBUG=True)
settings.configure(DEBUG=True, TEMPLATE_DEBUG=True)
except ImportError, e:
pass

from hamlpy.template.loaders import get_haml_loader
from hamlpy.template.loaders import get_haml_loader, TemplateDoesNotExist

class DummyLoader(object):
"""
Expand Down
17 changes: 17 additions & 0 deletions hamlpy/test/template_compare_test.py
Expand Up @@ -41,6 +41,23 @@ def test_nested_django_tags(self):
def test_filters(self):
self._compare_test_files('filters')

def test_filters_markdown(self):
try:
import markdown
self._compare_test_files('filtersMarkdown')
except ImportError:
pass

def test_filters_pygments(self):
try:
import pygments
if pygments.__version__ == '1.6':
self._compare_test_files('filtersPygments16')
else:
self._compare_test_files('filtersPygments')
except ImportError:
pass

def test_nested_if_else_blocks(self):
self._compare_test_files('nestedIfElseBlocks')

Expand Down
7 changes: 0 additions & 7 deletions hamlpy/test/templates/filters.hamlpy
Expand Up @@ -16,10 +16,3 @@
a=1
for i in range(5):
print a+i
:markdown
hello
no paragraph

New paragraph

test
5 changes: 0 additions & 5 deletions hamlpy/test/templates/filters.html
Expand Up @@ -24,8 +24,3 @@
3
4
5
<p>hello
no paragraph</p>
<p>New paragraph</p>
<pre><code>test
</code></pre>
7 changes: 7 additions & 0 deletions hamlpy/test/templates/filtersMarkdown.hamlpy
@@ -0,0 +1,7 @@
:markdown
hello
no paragraph

New paragraph

test
5 changes: 5 additions & 0 deletions hamlpy/test/templates/filtersMarkdown.html
@@ -0,0 +1,5 @@
<p>hello
no paragraph</p>
<p>New paragraph</p>
<pre><code>test
</code></pre>
7 changes: 7 additions & 0 deletions hamlpy/test/templates/filtersPygments.hamlpy
@@ -0,0 +1,7 @@
:highlight
print "hi"

if x:
print "y":
else:
print "z":
8 changes: 8 additions & 0 deletions hamlpy/test/templates/filtersPygments.html
@@ -0,0 +1,8 @@

<div class="highlight"><pre><span class="n">print</span> &quot;<span class="n">hi</span>&quot;

<span class="k">if</span> <span class="n">x</span><span class="p">:</span>
<span class="n">print</span> &quot;<span class="n">y</span>&quot;<span class="p">:</span>
<span class="k">else</span><span class="p">:</span>
<span class="n">print</span> &quot;<span class="n">z</span>&quot;<span class="p">:</span>
</pre></div>
7 changes: 7 additions & 0 deletions hamlpy/test/templates/filtersPygments16.hamlpy
@@ -0,0 +1,7 @@
:highlight
print "hi"

if x:
print "y":
else:
print "z":
8 changes: 8 additions & 0 deletions hamlpy/test/templates/filtersPygments16.html
@@ -0,0 +1,8 @@

<div class="highlight"><pre><span class="n">print</span> <span class="s">&quot;hi&quot;</span>

<span class="k">if</span> <span class="n">x</span><span class="o">:</span>
<span class="n">print</span> <span class="s">&quot;y&quot;</span><span class="o">:</span>
<span class="nl">else:</span>
<span class="n">print</span> <span class="s">&quot;z&quot;</span><span class="o">:</span>
</pre></div>
3 changes: 0 additions & 3 deletions setup.py
Expand Up @@ -12,9 +12,6 @@
url = 'http://github.com/jessemiller/HamlPy',
license = 'MIT',
install_requires = [
'django',
'pygments',
'markdown'
],
entry_points = {
'console_scripts' : ['hamlpy = hamlpy.hamlpy:convert_files',
Expand Down

0 comments on commit adc1840

Please sign in to comment.