Dataset Viewer (First 5GB)
Auto-converted to Parquet
repo
string
commit
string
message
string
diff
string
adieu/django-mediagenerator
e9502dcd52f97ebc157dead13f0849cf59e1b503
Added handlebars.js filter
diff --git a/mediagenerator/filters/handlebars.py b/mediagenerator/filters/handlebars.py new file mode 100644 index 0000000..bfb686f --- /dev/null +++ b/mediagenerator/filters/handlebars.py @@ -0,0 +1,97 @@ +from django.conf import settings +from django.utils.encoding import smart_str + +from mediagenerator.generators.bundles.base import Filter +from mediagenerator.utils import get_media_dirs, find_file + +import os, sys +from hashlib import sha1 +from subprocess import Popen, PIPE + +class HandlebarsFilter(Filter): + def __init__(self, **kwargs): + self.config(kwargs, name=kwargs["name"], path=(), template_name=kwargs.get("template_name")) + if isinstance(self.path, basestring): + self.path = (self.path,) + + # we need to be able to mutate self.path + self.path = list(self.path) + + super(HandlebarsFilter, self).__init__(**kwargs) + + media_dirs = [directory for directory in get_media_dirs() + if os.path.exists(directory)] + self.path += tuple(media_dirs) + + # search from template directories first + from django.template.loaders.app_directories import app_template_dirs + self.path = list(app_template_dirs) + self.path + + self._compiled = None + self._compiled_hash = None + self._dependencies = {} + + + @classmethod + def from_default(cls, name): + return {'name': name} + + def get_output(self, variation): + self._regenerate(debug=False) + yield self._compiled + + def get_dev_output(self, name, variation): + self._regenerate(debug=True) + return self._compiled + + def get_dev_output_names(self, variation): + self._regenerate(debug=True) + yield self.name + '.js', self._compiled_hash + + + def _regenerate(self, debug=False): + file_path = self._find_file(self.name) + self._compiled = self._compile(file_path, debug=debug) + self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() + + def _compile(self, path, debug=False): + # check if already compiled + if hasattr(self, "mtime") and self.mtime == os.path.getmtime(path): + return self._compiled + + # compile with handlebars + try: + shell = sys.platform == 'win32' + + relative_path = self._get_relative_path(path) + + cmd = Popen(['handlebars', relative_path], + stdin=PIPE, stdout=PIPE, stderr=PIPE, + shell=shell, universal_newlines=True, + cwd=settings.PROJECT_ROOT) + output, error = cmd.communicate() + + self.mtime = os.path.getmtime(path) + + assert cmd.wait() == 0, ('handlebars returned errors:\n%s\n%s' % (error, output)) + return output.decode('utf-8') + except Exception, e: + raise ValueError("Failed to run handlebars.js compiler for this " + "file. Please confirm that the \"handlebars\" application is " + "on your path and that you can run it from your own command " + "line.\n" + "Error was: %s" % e) + + + def _find_file(self, name): + return find_file(name, media_dirs=self.path) + + + def _get_relative_path(self, abs_path): + """Given an absolute path, return a path relative to the + project root. + 'subdir/foo' + + """ + relative_path = os.path.relpath(abs_path, settings.PROJECT_ROOT) + return relative_path diff --git a/mediagenerator/generators/bundles/settings.py b/mediagenerator/generators/bundles/settings.py index 1b9209b..85a6a07 100644 --- a/mediagenerator/generators/bundles/settings.py +++ b/mediagenerator/generators/bundles/settings.py @@ -1,26 +1,27 @@ from django.conf import settings DEFAULT_MEDIA_FILTERS = getattr(settings, 'DEFAULT_MEDIA_FILTERS', { 'ccss': 'mediagenerator.filters.clever.CleverCSS', 'coffee': 'mediagenerator.filters.coffeescript.CoffeeScript', + 'handlebars': 'mediagenerator.filters.handlebars.HandlebarsFilter', 'css': 'mediagenerator.filters.cssurl.CSSURLFileFilter', 'html': 'mediagenerator.filters.template.Template', 'py': 'mediagenerator.filters.pyjs_filter.Pyjs', 'pyva': 'mediagenerator.filters.pyvascript_filter.PyvaScript', 'sass': 'mediagenerator.filters.sass.Sass', 'scss': 'mediagenerator.filters.sass.Sass', 'less': 'mediagenerator.filters.less.Less', }) ROOT_MEDIA_FILTERS = getattr(settings, 'ROOT_MEDIA_FILTERS', {}) # These are applied in addition to ROOT_MEDIA_FILTERS. # The separation is done because we don't want users to # always specify the default filters when they merely want # to configure YUICompressor or Closure. BASE_ROOT_MEDIA_FILTERS = getattr(settings, 'BASE_ROOT_MEDIA_FILTERS', { '*': 'mediagenerator.filters.concat.Concat', 'css': 'mediagenerator.filters.cssurl.CSSURL', }) MEDIA_BUNDLES = getattr(settings, 'MEDIA_BUNDLES', ())
adieu/django-mediagenerator
495da73f305a2a0e79a28d251b5b93caea06656d
Add UglifyJS as a filter.
diff --git a/mediagenerator/filters/uglifier.py b/mediagenerator/filters/uglifier.py new file mode 100644 index 0000000..4906f1b --- /dev/null +++ b/mediagenerator/filters/uglifier.py @@ -0,0 +1,33 @@ +from django.conf import settings +from django.utils.encoding import smart_str +from mediagenerator.generators.bundles.base import Filter + +class Uglifier(Filter): + def __init__(self, **kwargs): + super(Uglifier, self).__init__(**kwargs) + assert self.filetype == 'js', ( + 'Uglifier only supports compilation to js. ' + 'The parent filter expects "%s".' % self.filetype) + + def get_output(self, variation): + # We import this here, so App Engine Helper users don't get import + # errors. + from subprocess import Popen, PIPE + for input in self.get_input(variation): + args = ['uglifyjs'] + try: + args = args + settings.UGLIFIER_OPTIONS + except AttributeError: + pass + try: + cmd = Popen(args, + stdin=PIPE, stdout=PIPE, stderr=PIPE, + universal_newlines=True) + output, error = cmd.communicate(smart_str(input)) + assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error + yield output.decode('utf-8') + except Exception, e: + raise ValueError("Failed to run UglifyJs. " + "Please make sure you have Node.js and UglifyJS installed " + "and that it's in your PATH.\n" + "Error was: %s" % e)
adieu/django-mediagenerator
f7ecb8fd5cf7dfd2c0ea8f0c6a7c5c5a8dbada5b
don't overdo it
diff --git a/README.rst b/README.rst index 98e29a2..845a445 100644 --- a/README.rst +++ b/README.rst @@ -1,24 +1,24 @@ -Improve your user experience with amazingly fast page loads by combining, +Improve your user experience with fast page loads by combining, compressing, and versioning your JavaScript & CSS files and images. django-mediagenerator_ eliminates unnecessary HTTP requests and maximizes cache usage. Supports App Engine, Sass_, HTML5 offline manifests, Jinja2_, Python/pyjs_, CoffeeScript_, and much more. Visit the `project site`_ for more information. Most important changes in version 1.11 ============================================================= * Added LESS support * Fixed an incompatibility with App Engine 1.6.0 on Python 2.7 See `CHANGELOG.rst`_ for the complete changelog. .. _django-mediagenerator: http://www.allbuttonspressed.com/projects/django-mediagenerator .. _project site: django-mediagenerator_ .. _Sass: http://sass-lang.com/ .. _pyjs: http://pyjs.org/ .. _CoffeeScript: http://coffeescript.org/ .. _Jinja2: http://jinja.pocoo.org/ .. _CHANGELOG.rst: https://bitbucket.org/wkornewald/django-mediagenerator/src/tip/CHANGELOG.rst
adieu/django-mediagenerator
67977e2f2b0d5b8281eac40a632a138eddc520a9
bumped version to 1.11
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 51a8343..f55316f 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,156 +1,162 @@ Changelog ============================================================= +Version 1.11 +------------------------------------------------------------- + +* Added LESS support +* Fixed an incompatibility with App Engine 1.6.0 on Python 2.7 + Version 1.10.4 ------------------------------------------------------------- * Fixed remapping of CSS url()s that contain a "?" * Fixed serving of unicode content by media middleware Version 1.10.3 ------------------------------------------------------------- * Fixed lots of unicode issues Version 1.10.2 ------------------------------------------------------------- **Upgrade notes:** If you've specified a custom ``SASS_FRAMEWORKS`` in your ``settings.py`` you now also have to list ``compass`` and ``blueprint`` in that setting. * All Compass/Sass frameworks (including ``compass`` and ``blueprint``) now have to be listed explictily in the ``SASS_FRAMEWORKS`` setting. Version 1.10.1 ------------------------------------------------------------- * Added workaround for Windows bug in Sass 3.1. Backslash characters aren't handled correctly for "-I" import path parameters. Version 1.10 ------------------------------------------------------------- * Added Compass support to Sass filter. You now have to install both Compass and Sass. Import Sass/Compass frameworks via ``manage.py importsassframeworks``. * Fixed CoffeeScript support on OSX * Fixed support for non-ascii chars in input files * Added "Content-Length" response header for files served in dev mode (needed for Flash). Thanks to "sayane" for the patch. * Fixed typo which resulted in broken support for ``.html`` assets. Thanks to "pendletongp" for the patch. * Now showing instructive error message when Sass can't be found * Use correct output path for ``_generated_media_names.py`` even when ``manage.py generatemedia`` is not started from the project root. Thanks to "pendletongp" for the patch. * Added support for overriding the ``_generated_media_names`` module's import path and file system location (only needed for non-standard project structures). Version 1.9.2 ------------------------------------------------------------- * Added missing ``base.manifest`` template and ``base_project`` to zip package Version 1.9.1 ------------------------------------------------------------- * Fixed relative imports in Sass filter Version 1.9 ------------------------------------------------------------- * Added CoffeeScript support (use ``.coffee`` extension). Contributed by Andrew Allen. * Added caching for CoffeeScript compilation results * In cache manifests the ``NETWORK`` section now contains "``*``" by default * By default ``.woff`` files are now copied, too * Fixed first-time media generation when ``MEDIA_DEV_MODE=False`` * Fixed i18n filter in development mode. Contributed by Simon Payne. * Fixed support for "/" in bundle names in dev mode (always worked fine in production) * Changed ``DEV_MEDIA_URL`` fallback from ``STATICFILES_URL`` to ``STATIC_URL`` (has been changed in Django trunk) Version 1.8 ------------------------------------------------------------- * HTML5 manifest now uses a regex to match included/excluded files * Added support for scss files * Fixed Sass ``@import`` tracking for partials Version 1.7 ------------------------------------------------------------- * Large performance improvements, in particular on App Engine dev_appserver Version 1.6.1 ------------------------------------------------------------- * Fixed support for Django 1.1 which imports ``mediagenerator.templatetags.media`` as ``django.templatetags.media`` and thus breaks relative imports Version 1.6 ------------------------------------------------------------- **Upgrade notes:** The installation got simplified. Please remove the media code from your urls.py. The ``MediaMiddleware`` now takes care of everything. * Added support for CSS data URIs. Doesn't yet generate MHTML for IE6/7 support. * Added support for pre-bundling i18n JavaScript translations, so you don't need to use Django's slower AJAX view. With this filter translations are part of your generated JS bundle. * Added support for CleverCSS * Simplified installation process. The media view got completely replaced by ``MediaMiddleware``. * Fixed support for output variations (needed by i18n filter to generate the same JS file in different variations for each language) Version 1.5.1 ------------------------------------------------------------- **Upgrade notes:** There's a conflict with ``STATICFILES_URL`` in Django trunk (1.3). Use ``DEV_MEDIA_URL`` instead from now on. * ``DEV_MEDIA_URL`` should be used instead of ``MEDIA_URL`` and ``STATICFILES_URL``, though the other two are still valid for backwards-compatibility Version 1.5 ------------------------------------------------------------- This is another staticfiles-compatibility release which is intended to allow for writing reusable open-source apps. **Upgrade notes:** The CSS URL rewriting scheme has changed. Previously, ``url()`` statements in CSS files were treated similar to "absolute" URLs where the root is ``STATICFILES_URL`` (or ``MEDIA_URL``). This scheme was used because it was consistent with URLs in Sass. Now URLs are treated as relative to the CSS file. So, if the file ``css/style.css`` wants to link to ``img/icon.png`` the URL now has to be ``url(../img/icon.png)``. Previously it was ``url(img/icon.png)``. One way to upgrade to the staticfiles-compatible scheme is to modify your existing URLs. If you don't want to change your CSS files there is an alternative, but it's not staticfiles-compatible. Add the following to your settings: ``REWRITE_CSS_URLS_RELATIVE_TO_SOURCE = False`` **Important:** Sass files still use the old scheme (``url(img/icon.png)``) because this is **much** easier to understand and allows for more reusable code, especially when you ``@import`` other Sass modules and those link to images. * Made CSS URL rewriting system compatible with ``django.contrib.staticfiles`` * Added support for CSS URLs that contain a hash (e.g.: ``url('webfont.svg#webfontmAfNlbV6')``). Thanks to Karl Bowden for the patch! * Filter backends now have an additional ``self.bundle`` attribute which contains the final bundle name * Fixed an incompatibility with Django 1.1 and 1.0 (``django.utils.itercompat.product`` isn't available in those releases) * Fixed ``MediaMiddleware``, so it doesn't cache error responses Version 1.4 ------------------------------------------------------------- This is a compatibility release which prepares for the new staticfiles feature in Django 1.3. **Upgrade notes:** Place your app media in a "static" folder instead of a "media" folder. Use ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) instead of ``MEDIA_URL`` from now on. * App media is now searched in "static" folders instead of "media". For now, you can still use "media" folders, but this might be deprecated in the future (for the sake of having just one standard for reusable apps). * ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) should be used instead of ``MEDIA_URL`` because the meaning of that variable has changed in Django 1.3. * ``DEV_MEDIA_URL`` falls back to ``STATICFILES_URL`` and ``GLOBAL_MEDIA_DIRS`` falls back to ``STATICFILES_DIRS`` if undefined (you should still use the former, respectively; this is just for convenience) Version 1.3.1 ------------------------------------------------------------- * Improved handling of media variations. This also fixes a bug with using CSS media types in production mode Version 1.3 ------------------------------------------------------------- * Added support for setting media type for CSS. E.g.: ``{% include_media 'bundle.css' media='print' %}`` Version 1.2.1 ------------------------------------------------------------- * Fixed caching problems on runserver when using i18n and ``LocaleMiddleware`` Version 1.2 ------------------------------------------------------------- **Upgrade notes:** Please add ``'mediagenerator.middleware.MediaMiddleware'`` as the **first** middleware in your settings.py. * Got rid of unnecessary HTTP roundtrips when ``USE_ETAGS = True`` * Added Django template filter (by default only used for .html files), contributed by Matt Bierner * Added media_url() filter which provides access to generated URLs from JS * CopyFiles backend can now ignore files matching certain regex patterns Version 1.1 ------------------------------------------------------------- * Added Closure compiler backend * Added HTML5 cache manifest file backend * Fixed Sass support on Linux * Updated pyjs filter to latest pyjs repo version * "swf" and "ico" files are now copied, too, by default diff --git a/README.rst b/README.rst index 2f0d6ab..98e29a2 100644 --- a/README.rst +++ b/README.rst @@ -1,25 +1,24 @@ Improve your user experience with amazingly fast page loads by combining, compressing, and versioning your JavaScript & CSS files and images. django-mediagenerator_ eliminates unnecessary HTTP requests and maximizes cache usage. Supports App Engine, Sass_, HTML5 offline manifests, Jinja2_, Python/pyjs_, CoffeeScript_, and much more. Visit the `project site`_ for more information. -Most important changes in version 1.10.4 +Most important changes in version 1.11 ============================================================= -* Fixed remapping of CSS url()s that contain a "?" -* Fixed serving of unicode content by media middleware - +* Added LESS support +* Fixed an incompatibility with App Engine 1.6.0 on Python 2.7 See `CHANGELOG.rst`_ for the complete changelog. .. _django-mediagenerator: http://www.allbuttonspressed.com/projects/django-mediagenerator .. _project site: django-mediagenerator_ .. _Sass: http://sass-lang.com/ .. _pyjs: http://pyjs.org/ .. _CoffeeScript: http://coffeescript.org/ .. _Jinja2: http://jinja.pocoo.org/ .. _CHANGELOG.rst: https://bitbucket.org/wkornewald/django-mediagenerator/src/tip/CHANGELOG.rst diff --git a/setup.py b/setup.py index ac59b73..15e49ad 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ from setuptools import setup, find_packages DESCRIPTION = 'Asset manager for Django' LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() except: pass setup(name='django-mediagenerator', - version='1.10.4', + version='1.11', packages=find_packages(exclude=('tests', 'tests.*', 'base_project', 'base_project.*')), package_data={'mediagenerator.filters': ['pyjslibs/*.py', '*.rb'], 'mediagenerator': ['templates/mediagenerator/manifest/*']}, author='Waldemar Kornewald', author_email='[email protected]', url='http://www.allbuttonspressed.com/projects/django-mediagenerator', description=DESCRIPTION, long_description=LONG_DESCRIPTION, platforms=['any'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], )
adieu/django-mediagenerator
b58fb270da1a9fe00d2f4fcee5a17feba1718891
added lesscss support. thanks a lot to Wilfred Hughes for the patch!
diff --git a/mediagenerator/filters/less.py b/mediagenerator/filters/less.py new file mode 100644 index 0000000..4c10f3c --- /dev/null +++ b/mediagenerator/filters/less.py @@ -0,0 +1,196 @@ +from django.utils.encoding import smart_str +from django.conf import settings +from hashlib import sha1 +from mediagenerator.generators.bundles.base import Filter +from mediagenerator.utils import find_file, read_text_file, get_media_dirs +from subprocess import Popen, PIPE +import os +import sys +import re +import posixpath + + +_RE_FLAGS = re.MULTILINE | re.UNICODE +multi_line_comment_re = re.compile(r'/\*.*?\*/', _RE_FLAGS | re.DOTALL) +one_line_comment_re = re.compile(r'//.*', _RE_FLAGS) +import_re = re.compile(r'''@import\s* # import keyword + ["'] # opening quote + (.+?) # the module name + ["'] # closing quote + \s*; # statement terminator + ''', + _RE_FLAGS | re.VERBOSE) + +if not hasattr(os.path, 'relpath'): + # backport os.path.relpath from Python 2.6 + # Copyright (c) 2001-2010 Python Software Foundation; All Rights Reserved + + # Return the longest prefix of all list elements. + def commonprefix(m): + "Given a list of pathnames, returns the longest common leading component" + if not m: return '' + s1 = min(m) + s2 = max(m) + for i, c in enumerate(s1): + if c != s2[i]: + return s1[:i] + return s1 + + def relpath(path, start=os.path.curdir): + """Return a relative version of a path""" + + if not path: + raise ValueError("no path specified") + + start_list = [x for x in os.path.abspath(start).split(os.path.sep) if x] + path_list = [x for x in os.path.abspath(path).split(os.path.sep) if x] + + # Work out how much of the filepath is shared by start and path. + i = len(commonprefix([start_list, path_list])) + + rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:] + if not rel_list: + return os.path.curdir + return os.path.join(*rel_list) + + os.path.relpath = relpath + + +class Less(Filter): + takes_input = False + + def __init__(self, **kwargs): + self.config(kwargs, path=(), main_module=None) + if isinstance(self.path, basestring): + self.path = (self.path,) + + # we need to be able to mutate self.path, + self.path = list(self.path) + + super(Less, self).__init__(**kwargs) + + assert self.filetype == 'css', ( + 'Less only supports compilation to CSS. ' + 'The parent filter expects "%s".' % self.filetype) + assert self.main_module, \ + 'You must provide a main module' + + # lessc can't cope with nonexistent directories, so filter them + media_dirs = [directory for directory in get_media_dirs() + if os.path.exists(directory)] + self.path += tuple(media_dirs) + + self._compiled = None + self._compiled_hash = None + self._dependencies = {} + + @classmethod + def from_default(cls, name): + return {'main_module': name} + + def get_output(self, variation): + self._regenerate(debug=False) + yield self._compiled + + def get_dev_output(self, name, variation): + assert name == self.main_module + '.css' + self._regenerate(debug=True) + return self._compiled + + def get_dev_output_names(self, variation): + self._regenerate(debug=True) + yield self.main_module + '.css', self._compiled_hash + + def _regenerate(self, debug=False): + if self._dependencies: + for name, mtime in self._dependencies.items(): + path = self._find_file(name) + if not path or os.path.getmtime(path) != mtime: + # Just recompile everything + self._dependencies = {} + break + else: + # No changes + return + + modules = [self.main_module] + # get all the transitive dependencies of this module + while True: + if not modules: + break + + module_name = modules.pop() + path = self._find_file(module_name) + assert path, 'Could not find the Less module %s' % module_name + mtime = os.path.getmtime(path) + self._dependencies[module_name] = mtime + + source = read_text_file(path) + dependencies = self._get_dependencies(source) + + for name in dependencies: + # Try relative import, first + transformed = posixpath.join(posixpath.dirname(module_name), name) + path = self._find_file(transformed) + if path: + name = transformed + else: + path = self._find_file(name) + assert path, ('The Less module %s could not find the ' + 'dependency %s' % (module_name, name)) + if name not in self._dependencies: + modules.append(name) + + main_module_path = self._find_file(self.main_module) + self._compiled = self._compile(main_module_path, debug=debug) + self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() + + def _compile(self, path, debug=False): + try: + relative_paths = [self._get_relative_path(directory) + for directory in self.path] + + shell = sys.platform == 'win32' + + cmd = Popen(['lessc', + '--include-path=%s' % ':'.join(relative_paths), + path], + stdin=PIPE, stdout=PIPE, stderr=PIPE, + shell=shell, universal_newlines=True, + cwd=settings.PROJECT_ROOT) + output, error = cmd.communicate() + + # some lessc errors output to stdout, so we put both in the assertion message + assert cmd.wait() == 0, ('Less command returned bad ' + 'result:\n%s\n%s' % (error, output)) + return output.decode('utf-8') + except Exception, e: + raise ValueError("Failed to run Less compiler for this " + "file. Please confirm that the \"lessc\" application is " + "on your path and that you can run it from your own command " + "line.\n" + "Error was: %s" % e) + + def _get_dependencies(self, source): + clean_source = multi_line_comment_re.sub('\n', source) + clean_source = one_line_comment_re.sub('', clean_source) + + return [name for name in import_re.findall(clean_source) + if not name.endswith('.css')] + + def _find_file(self, name): + if not name.endswith('.less'): + name = name + '.less' + + return find_file(name, media_dirs=self.path) + + def _get_relative_path(self, abs_path): + """Given an absolute path, return a path relative to the + project root. + + >>> self._get_relative_path('/home/bob/bobs_project/subdir/foo') + 'subdir/foo' + + """ + relative_path = os.path.relpath(abs_path, settings.PROJECT_ROOT) + return relative_path diff --git a/mediagenerator/generators/bundles/settings.py b/mediagenerator/generators/bundles/settings.py index 679fa0b..1b9209b 100644 --- a/mediagenerator/generators/bundles/settings.py +++ b/mediagenerator/generators/bundles/settings.py @@ -1,25 +1,26 @@ from django.conf import settings DEFAULT_MEDIA_FILTERS = getattr(settings, 'DEFAULT_MEDIA_FILTERS', { 'ccss': 'mediagenerator.filters.clever.CleverCSS', 'coffee': 'mediagenerator.filters.coffeescript.CoffeeScript', 'css': 'mediagenerator.filters.cssurl.CSSURLFileFilter', 'html': 'mediagenerator.filters.template.Template', 'py': 'mediagenerator.filters.pyjs_filter.Pyjs', 'pyva': 'mediagenerator.filters.pyvascript_filter.PyvaScript', 'sass': 'mediagenerator.filters.sass.Sass', 'scss': 'mediagenerator.filters.sass.Sass', + 'less': 'mediagenerator.filters.less.Less', }) ROOT_MEDIA_FILTERS = getattr(settings, 'ROOT_MEDIA_FILTERS', {}) # These are applied in addition to ROOT_MEDIA_FILTERS. # The separation is done because we don't want users to # always specify the default filters when they merely want # to configure YUICompressor or Closure. BASE_ROOT_MEDIA_FILTERS = getattr(settings, 'BASE_ROOT_MEDIA_FILTERS', { '*': 'mediagenerator.filters.concat.Concat', 'css': 'mediagenerator.filters.cssurl.CSSURL', }) MEDIA_BUNDLES = getattr(settings, 'MEDIA_BUNDLES', ())
adieu/django-mediagenerator
bdbbce9482d246e9bbe02f4901ade3af65244d71
fixed __main__ detection on GAE/Python 2.7
diff --git a/mediagenerator/settings.py b/mediagenerator/settings.py index d6ffb55..fbdd187 100644 --- a/mediagenerator/settings.py +++ b/mediagenerator/settings.py @@ -1,38 +1,40 @@ from django.conf import settings from django.utils.encoding import force_unicode import os -import __main__ +import sys + +__main__ = sys.modules.get('__main__') _map_file_path = '_generated_media_names.py' _media_dir = '_generated_media' # __main__ is not guaranteed to have the __file__ attribute if hasattr(__main__, '__file__'): _root = os.path.dirname(__main__.__file__) _map_file_path = os.path.join(_root, _map_file_path) _media_dir = os.path.join(_root, _media_dir) GENERATED_MEDIA_DIR = os.path.abspath( getattr(settings, 'GENERATED_MEDIA_DIR', _media_dir)) GENERATED_MEDIA_NAMES_MODULE = getattr(settings, 'GENERATED_MEDIA_NAMES_MODULE', '_generated_media_names') GENERATED_MEDIA_NAMES_FILE = os.path.abspath( getattr(settings, 'GENERATED_MEDIA_NAMES_FILE', _map_file_path)) DEV_MEDIA_URL = getattr(settings, 'DEV_MEDIA_URL', getattr(settings, 'STATIC_URL', settings.MEDIA_URL)) PRODUCTION_MEDIA_URL = getattr(settings, 'PRODUCTION_MEDIA_URL', DEV_MEDIA_URL) MEDIA_GENERATORS = getattr(settings, 'MEDIA_GENERATORS', ( 'mediagenerator.generators.copyfiles.CopyFiles', 'mediagenerator.generators.bundles.Bundles', 'mediagenerator.generators.manifest.Manifest', )) _global_media_dirs = getattr(settings, 'GLOBAL_MEDIA_DIRS', getattr(settings, 'STATICFILES_DIRS', ())) GLOBAL_MEDIA_DIRS = [os.path.normcase(os.path.normpath(force_unicode(path))) for path in _global_media_dirs] IGNORE_APP_MEDIA_DIRS = getattr(settings, 'IGNORE_APP_MEDIA_DIRS', ('django.contrib.admin',)) MEDIA_DEV_MODE = getattr(settings, 'MEDIA_DEV_MODE', settings.DEBUG)
adieu/django-mediagenerator
85f1a4a4dd8cd9c59e2141da7c6b3576b42a4926
forgot to mention a change
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 6801909..51a8343 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,155 +1,156 @@ Changelog ============================================================= Version 1.10.4 ------------------------------------------------------------- +* Fixed remapping of CSS url()s that contain a "?" * Fixed serving of unicode content by media middleware Version 1.10.3 ------------------------------------------------------------- * Fixed lots of unicode issues Version 1.10.2 ------------------------------------------------------------- **Upgrade notes:** If you've specified a custom ``SASS_FRAMEWORKS`` in your ``settings.py`` you now also have to list ``compass`` and ``blueprint`` in that setting. * All Compass/Sass frameworks (including ``compass`` and ``blueprint``) now have to be listed explictily in the ``SASS_FRAMEWORKS`` setting. Version 1.10.1 ------------------------------------------------------------- * Added workaround for Windows bug in Sass 3.1. Backslash characters aren't handled correctly for "-I" import path parameters. Version 1.10 ------------------------------------------------------------- * Added Compass support to Sass filter. You now have to install both Compass and Sass. Import Sass/Compass frameworks via ``manage.py importsassframeworks``. * Fixed CoffeeScript support on OSX * Fixed support for non-ascii chars in input files * Added "Content-Length" response header for files served in dev mode (needed for Flash). Thanks to "sayane" for the patch. * Fixed typo which resulted in broken support for ``.html`` assets. Thanks to "pendletongp" for the patch. * Now showing instructive error message when Sass can't be found * Use correct output path for ``_generated_media_names.py`` even when ``manage.py generatemedia`` is not started from the project root. Thanks to "pendletongp" for the patch. * Added support for overriding the ``_generated_media_names`` module's import path and file system location (only needed for non-standard project structures). Version 1.9.2 ------------------------------------------------------------- * Added missing ``base.manifest`` template and ``base_project`` to zip package Version 1.9.1 ------------------------------------------------------------- * Fixed relative imports in Sass filter Version 1.9 ------------------------------------------------------------- * Added CoffeeScript support (use ``.coffee`` extension). Contributed by Andrew Allen. * Added caching for CoffeeScript compilation results * In cache manifests the ``NETWORK`` section now contains "``*``" by default * By default ``.woff`` files are now copied, too * Fixed first-time media generation when ``MEDIA_DEV_MODE=False`` * Fixed i18n filter in development mode. Contributed by Simon Payne. * Fixed support for "/" in bundle names in dev mode (always worked fine in production) * Changed ``DEV_MEDIA_URL`` fallback from ``STATICFILES_URL`` to ``STATIC_URL`` (has been changed in Django trunk) Version 1.8 ------------------------------------------------------------- * HTML5 manifest now uses a regex to match included/excluded files * Added support for scss files * Fixed Sass ``@import`` tracking for partials Version 1.7 ------------------------------------------------------------- * Large performance improvements, in particular on App Engine dev_appserver Version 1.6.1 ------------------------------------------------------------- * Fixed support for Django 1.1 which imports ``mediagenerator.templatetags.media`` as ``django.templatetags.media`` and thus breaks relative imports Version 1.6 ------------------------------------------------------------- **Upgrade notes:** The installation got simplified. Please remove the media code from your urls.py. The ``MediaMiddleware`` now takes care of everything. * Added support for CSS data URIs. Doesn't yet generate MHTML for IE6/7 support. * Added support for pre-bundling i18n JavaScript translations, so you don't need to use Django's slower AJAX view. With this filter translations are part of your generated JS bundle. * Added support for CleverCSS * Simplified installation process. The media view got completely replaced by ``MediaMiddleware``. * Fixed support for output variations (needed by i18n filter to generate the same JS file in different variations for each language) Version 1.5.1 ------------------------------------------------------------- **Upgrade notes:** There's a conflict with ``STATICFILES_URL`` in Django trunk (1.3). Use ``DEV_MEDIA_URL`` instead from now on. * ``DEV_MEDIA_URL`` should be used instead of ``MEDIA_URL`` and ``STATICFILES_URL``, though the other two are still valid for backwards-compatibility Version 1.5 ------------------------------------------------------------- This is another staticfiles-compatibility release which is intended to allow for writing reusable open-source apps. **Upgrade notes:** The CSS URL rewriting scheme has changed. Previously, ``url()`` statements in CSS files were treated similar to "absolute" URLs where the root is ``STATICFILES_URL`` (or ``MEDIA_URL``). This scheme was used because it was consistent with URLs in Sass. Now URLs are treated as relative to the CSS file. So, if the file ``css/style.css`` wants to link to ``img/icon.png`` the URL now has to be ``url(../img/icon.png)``. Previously it was ``url(img/icon.png)``. One way to upgrade to the staticfiles-compatible scheme is to modify your existing URLs. If you don't want to change your CSS files there is an alternative, but it's not staticfiles-compatible. Add the following to your settings: ``REWRITE_CSS_URLS_RELATIVE_TO_SOURCE = False`` **Important:** Sass files still use the old scheme (``url(img/icon.png)``) because this is **much** easier to understand and allows for more reusable code, especially when you ``@import`` other Sass modules and those link to images. * Made CSS URL rewriting system compatible with ``django.contrib.staticfiles`` * Added support for CSS URLs that contain a hash (e.g.: ``url('webfont.svg#webfontmAfNlbV6')``). Thanks to Karl Bowden for the patch! * Filter backends now have an additional ``self.bundle`` attribute which contains the final bundle name * Fixed an incompatibility with Django 1.1 and 1.0 (``django.utils.itercompat.product`` isn't available in those releases) * Fixed ``MediaMiddleware``, so it doesn't cache error responses Version 1.4 ------------------------------------------------------------- This is a compatibility release which prepares for the new staticfiles feature in Django 1.3. **Upgrade notes:** Place your app media in a "static" folder instead of a "media" folder. Use ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) instead of ``MEDIA_URL`` from now on. * App media is now searched in "static" folders instead of "media". For now, you can still use "media" folders, but this might be deprecated in the future (for the sake of having just one standard for reusable apps). * ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) should be used instead of ``MEDIA_URL`` because the meaning of that variable has changed in Django 1.3. * ``DEV_MEDIA_URL`` falls back to ``STATICFILES_URL`` and ``GLOBAL_MEDIA_DIRS`` falls back to ``STATICFILES_DIRS`` if undefined (you should still use the former, respectively; this is just for convenience) Version 1.3.1 ------------------------------------------------------------- * Improved handling of media variations. This also fixes a bug with using CSS media types in production mode Version 1.3 ------------------------------------------------------------- * Added support for setting media type for CSS. E.g.: ``{% include_media 'bundle.css' media='print' %}`` Version 1.2.1 ------------------------------------------------------------- * Fixed caching problems on runserver when using i18n and ``LocaleMiddleware`` Version 1.2 ------------------------------------------------------------- **Upgrade notes:** Please add ``'mediagenerator.middleware.MediaMiddleware'`` as the **first** middleware in your settings.py. * Got rid of unnecessary HTTP roundtrips when ``USE_ETAGS = True`` * Added Django template filter (by default only used for .html files), contributed by Matt Bierner * Added media_url() filter which provides access to generated URLs from JS * CopyFiles backend can now ignore files matching certain regex patterns Version 1.1 ------------------------------------------------------------- * Added Closure compiler backend * Added HTML5 cache manifest file backend * Fixed Sass support on Linux * Updated pyjs filter to latest pyjs repo version * "swf" and "ico" files are now copied, too, by default diff --git a/README.rst b/README.rst index ae47d80..2f0d6ab 100644 --- a/README.rst +++ b/README.rst @@ -1,24 +1,25 @@ Improve your user experience with amazingly fast page loads by combining, compressing, and versioning your JavaScript & CSS files and images. django-mediagenerator_ eliminates unnecessary HTTP requests and maximizes cache usage. Supports App Engine, Sass_, HTML5 offline manifests, Jinja2_, Python/pyjs_, CoffeeScript_, and much more. Visit the `project site`_ for more information. Most important changes in version 1.10.4 ============================================================= +* Fixed remapping of CSS url()s that contain a "?" * Fixed serving of unicode content by media middleware See `CHANGELOG.rst`_ for the complete changelog. .. _django-mediagenerator: http://www.allbuttonspressed.com/projects/django-mediagenerator .. _project site: django-mediagenerator_ .. _Sass: http://sass-lang.com/ .. _pyjs: http://pyjs.org/ .. _CoffeeScript: http://coffeescript.org/ .. _Jinja2: http://jinja.pocoo.org/ .. _CHANGELOG.rst: https://bitbucket.org/wkornewald/django-mediagenerator/src/tip/CHANGELOG.rst
adieu/django-mediagenerator
108fa31f52a12cc41b803c2366ea1b7fd616545b
improved an error message and bumped version
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 7098eb5..6801909 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,150 +1,155 @@ Changelog ============================================================= +Version 1.10.4 +------------------------------------------------------------- + +* Fixed serving of unicode content by media middleware + Version 1.10.3 ------------------------------------------------------------- * Fixed lots of unicode issues Version 1.10.2 ------------------------------------------------------------- **Upgrade notes:** If you've specified a custom ``SASS_FRAMEWORKS`` in your ``settings.py`` you now also have to list ``compass`` and ``blueprint`` in that setting. * All Compass/Sass frameworks (including ``compass`` and ``blueprint``) now have to be listed explictily in the ``SASS_FRAMEWORKS`` setting. Version 1.10.1 ------------------------------------------------------------- * Added workaround for Windows bug in Sass 3.1. Backslash characters aren't handled correctly for "-I" import path parameters. Version 1.10 ------------------------------------------------------------- * Added Compass support to Sass filter. You now have to install both Compass and Sass. Import Sass/Compass frameworks via ``manage.py importsassframeworks``. * Fixed CoffeeScript support on OSX * Fixed support for non-ascii chars in input files * Added "Content-Length" response header for files served in dev mode (needed for Flash). Thanks to "sayane" for the patch. * Fixed typo which resulted in broken support for ``.html`` assets. Thanks to "pendletongp" for the patch. * Now showing instructive error message when Sass can't be found * Use correct output path for ``_generated_media_names.py`` even when ``manage.py generatemedia`` is not started from the project root. Thanks to "pendletongp" for the patch. * Added support for overriding the ``_generated_media_names`` module's import path and file system location (only needed for non-standard project structures). Version 1.9.2 ------------------------------------------------------------- * Added missing ``base.manifest`` template and ``base_project`` to zip package Version 1.9.1 ------------------------------------------------------------- * Fixed relative imports in Sass filter Version 1.9 ------------------------------------------------------------- * Added CoffeeScript support (use ``.coffee`` extension). Contributed by Andrew Allen. * Added caching for CoffeeScript compilation results * In cache manifests the ``NETWORK`` section now contains "``*``" by default * By default ``.woff`` files are now copied, too * Fixed first-time media generation when ``MEDIA_DEV_MODE=False`` * Fixed i18n filter in development mode. Contributed by Simon Payne. * Fixed support for "/" in bundle names in dev mode (always worked fine in production) * Changed ``DEV_MEDIA_URL`` fallback from ``STATICFILES_URL`` to ``STATIC_URL`` (has been changed in Django trunk) Version 1.8 ------------------------------------------------------------- * HTML5 manifest now uses a regex to match included/excluded files * Added support for scss files * Fixed Sass ``@import`` tracking for partials Version 1.7 ------------------------------------------------------------- * Large performance improvements, in particular on App Engine dev_appserver Version 1.6.1 ------------------------------------------------------------- * Fixed support for Django 1.1 which imports ``mediagenerator.templatetags.media`` as ``django.templatetags.media`` and thus breaks relative imports Version 1.6 ------------------------------------------------------------- **Upgrade notes:** The installation got simplified. Please remove the media code from your urls.py. The ``MediaMiddleware`` now takes care of everything. * Added support for CSS data URIs. Doesn't yet generate MHTML for IE6/7 support. * Added support for pre-bundling i18n JavaScript translations, so you don't need to use Django's slower AJAX view. With this filter translations are part of your generated JS bundle. * Added support for CleverCSS * Simplified installation process. The media view got completely replaced by ``MediaMiddleware``. * Fixed support for output variations (needed by i18n filter to generate the same JS file in different variations for each language) Version 1.5.1 ------------------------------------------------------------- **Upgrade notes:** There's a conflict with ``STATICFILES_URL`` in Django trunk (1.3). Use ``DEV_MEDIA_URL`` instead from now on. * ``DEV_MEDIA_URL`` should be used instead of ``MEDIA_URL`` and ``STATICFILES_URL``, though the other two are still valid for backwards-compatibility Version 1.5 ------------------------------------------------------------- This is another staticfiles-compatibility release which is intended to allow for writing reusable open-source apps. **Upgrade notes:** The CSS URL rewriting scheme has changed. Previously, ``url()`` statements in CSS files were treated similar to "absolute" URLs where the root is ``STATICFILES_URL`` (or ``MEDIA_URL``). This scheme was used because it was consistent with URLs in Sass. Now URLs are treated as relative to the CSS file. So, if the file ``css/style.css`` wants to link to ``img/icon.png`` the URL now has to be ``url(../img/icon.png)``. Previously it was ``url(img/icon.png)``. One way to upgrade to the staticfiles-compatible scheme is to modify your existing URLs. If you don't want to change your CSS files there is an alternative, but it's not staticfiles-compatible. Add the following to your settings: ``REWRITE_CSS_URLS_RELATIVE_TO_SOURCE = False`` **Important:** Sass files still use the old scheme (``url(img/icon.png)``) because this is **much** easier to understand and allows for more reusable code, especially when you ``@import`` other Sass modules and those link to images. * Made CSS URL rewriting system compatible with ``django.contrib.staticfiles`` * Added support for CSS URLs that contain a hash (e.g.: ``url('webfont.svg#webfontmAfNlbV6')``). Thanks to Karl Bowden for the patch! * Filter backends now have an additional ``self.bundle`` attribute which contains the final bundle name * Fixed an incompatibility with Django 1.1 and 1.0 (``django.utils.itercompat.product`` isn't available in those releases) * Fixed ``MediaMiddleware``, so it doesn't cache error responses Version 1.4 ------------------------------------------------------------- This is a compatibility release which prepares for the new staticfiles feature in Django 1.3. **Upgrade notes:** Place your app media in a "static" folder instead of a "media" folder. Use ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) instead of ``MEDIA_URL`` from now on. * App media is now searched in "static" folders instead of "media". For now, you can still use "media" folders, but this might be deprecated in the future (for the sake of having just one standard for reusable apps). * ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) should be used instead of ``MEDIA_URL`` because the meaning of that variable has changed in Django 1.3. * ``DEV_MEDIA_URL`` falls back to ``STATICFILES_URL`` and ``GLOBAL_MEDIA_DIRS`` falls back to ``STATICFILES_DIRS`` if undefined (you should still use the former, respectively; this is just for convenience) Version 1.3.1 ------------------------------------------------------------- * Improved handling of media variations. This also fixes a bug with using CSS media types in production mode Version 1.3 ------------------------------------------------------------- * Added support for setting media type for CSS. E.g.: ``{% include_media 'bundle.css' media='print' %}`` Version 1.2.1 ------------------------------------------------------------- * Fixed caching problems on runserver when using i18n and ``LocaleMiddleware`` Version 1.2 ------------------------------------------------------------- **Upgrade notes:** Please add ``'mediagenerator.middleware.MediaMiddleware'`` as the **first** middleware in your settings.py. * Got rid of unnecessary HTTP roundtrips when ``USE_ETAGS = True`` * Added Django template filter (by default only used for .html files), contributed by Matt Bierner * Added media_url() filter which provides access to generated URLs from JS * CopyFiles backend can now ignore files matching certain regex patterns Version 1.1 ------------------------------------------------------------- * Added Closure compiler backend * Added HTML5 cache manifest file backend * Fixed Sass support on Linux * Updated pyjs filter to latest pyjs repo version * "swf" and "ico" files are now copied, too, by default diff --git a/README.rst b/README.rst index 2b9c524..ae47d80 100644 --- a/README.rst +++ b/README.rst @@ -1,23 +1,24 @@ Improve your user experience with amazingly fast page loads by combining, compressing, and versioning your JavaScript & CSS files and images. django-mediagenerator_ eliminates unnecessary HTTP requests and maximizes cache usage. Supports App Engine, Sass_, HTML5 offline manifests, Jinja2_, Python/pyjs_, CoffeeScript_, and much more. Visit the `project site`_ for more information. -Most important changes in version 1.10.3 +Most important changes in version 1.10.4 ============================================================= -* Fixed lots of unicode issues +* Fixed serving of unicode content by media middleware + See `CHANGELOG.rst`_ for the complete changelog. .. _django-mediagenerator: http://www.allbuttonspressed.com/projects/django-mediagenerator .. _project site: django-mediagenerator_ .. _Sass: http://sass-lang.com/ .. _pyjs: http://pyjs.org/ .. _CoffeeScript: http://coffeescript.org/ .. _Jinja2: http://jinja.pocoo.org/ .. _CHANGELOG.rst: https://bitbucket.org/wkornewald/django-mediagenerator/src/tip/CHANGELOG.rst diff --git a/mediagenerator/middleware.py b/mediagenerator/middleware.py index 40b178f..d8b50c9 100644 --- a/mediagenerator/middleware.py +++ b/mediagenerator/middleware.py @@ -1,61 +1,62 @@ from .settings import DEV_MEDIA_URL, MEDIA_DEV_MODE # Only load other dependencies if they're needed if MEDIA_DEV_MODE: from .utils import _refresh_dev_names, _backend_mapping from django.http import HttpResponse, Http404 from django.utils.cache import patch_cache_control from django.utils.http import http_date import time TEXT_MIME_TYPES = ( 'application/x-javascript', 'application/xhtml+xml', 'application/xml', ) class MediaMiddleware(object): """ Middleware for serving and browser-side caching of media files. This MUST be your *first* entry in MIDDLEWARE_CLASSES. Otherwise, some other middleware might add ETags or otherwise manipulate the caching headers which would result in the browser doing unnecessary HTTP roundtrips for unchanged media. """ MAX_AGE = 60 * 60 * 24 * 365 def process_request(self, request): if not MEDIA_DEV_MODE: return # We refresh the dev names only once for the whole request, so all # media_url() calls are cached. _refresh_dev_names() if not request.path.startswith(DEV_MEDIA_URL): return filename = request.path[len(DEV_MEDIA_URL):] try: backend = _backend_mapping[filename] except KeyError: - raise Http404('No such media file "%s"' % filename) + raise Http404('The mediagenerator could not find the media file "%s"' + % filename) content, mimetype = backend.get_dev_output(filename) if not mimetype: mimetype = 'application/octet-stream' if isinstance(content, unicode): content = content.encode('utf-8') if mimetype.startswith('text/') or mimetype in TEXT_MIME_TYPES: mimetype += '; charset=utf-8' response = HttpResponse(content, content_type=mimetype) response['Content-Length'] = len(content) # Cache manifest files MUST NEVER be cached or you'll be unable to update # your cached app!!! if response['Content-Type'] != 'text/cache-manifest' and \ response.status_code == 200: patch_cache_control(response, public=True, max_age=self.MAX_AGE) response['Expires'] = http_date(time.time() + self.MAX_AGE) return response diff --git a/setup.py b/setup.py index e0c7282..ac59b73 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ from setuptools import setup, find_packages DESCRIPTION = 'Asset manager for Django' LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() except: pass setup(name='django-mediagenerator', - version='1.10.3', + version='1.10.4', packages=find_packages(exclude=('tests', 'tests.*', 'base_project', 'base_project.*')), package_data={'mediagenerator.filters': ['pyjslibs/*.py', '*.rb'], 'mediagenerator': ['templates/mediagenerator/manifest/*']}, author='Waldemar Kornewald', author_email='[email protected]', url='http://www.allbuttonspressed.com/projects/django-mediagenerator', description=DESCRIPTION, long_description=LONG_DESCRIPTION, platforms=['any'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], )
adieu/django-mediagenerator
8c9932da0083c430adac4ed30ddd4c04d86a1aa9
added default mimetype
diff --git a/mediagenerator/middleware.py b/mediagenerator/middleware.py index 71a4496..40b178f 100644 --- a/mediagenerator/middleware.py +++ b/mediagenerator/middleware.py @@ -1,59 +1,61 @@ from .settings import DEV_MEDIA_URL, MEDIA_DEV_MODE # Only load other dependencies if they're needed if MEDIA_DEV_MODE: from .utils import _refresh_dev_names, _backend_mapping from django.http import HttpResponse, Http404 from django.utils.cache import patch_cache_control from django.utils.http import http_date import time TEXT_MIME_TYPES = ( 'application/x-javascript', 'application/xhtml+xml', 'application/xml', ) class MediaMiddleware(object): """ Middleware for serving and browser-side caching of media files. This MUST be your *first* entry in MIDDLEWARE_CLASSES. Otherwise, some other middleware might add ETags or otherwise manipulate the caching headers which would result in the browser doing unnecessary HTTP roundtrips for unchanged media. """ MAX_AGE = 60 * 60 * 24 * 365 def process_request(self, request): if not MEDIA_DEV_MODE: return # We refresh the dev names only once for the whole request, so all # media_url() calls are cached. _refresh_dev_names() if not request.path.startswith(DEV_MEDIA_URL): return filename = request.path[len(DEV_MEDIA_URL):] try: backend = _backend_mapping[filename] except KeyError: raise Http404('No such media file "%s"' % filename) content, mimetype = backend.get_dev_output(filename) + if not mimetype: + mimetype = 'application/octet-stream' if isinstance(content, unicode): content = content.encode('utf-8') if mimetype.startswith('text/') or mimetype in TEXT_MIME_TYPES: mimetype += '; charset=utf-8' response = HttpResponse(content, content_type=mimetype) response['Content-Length'] = len(content) # Cache manifest files MUST NEVER be cached or you'll be unable to update # your cached app!!! if response['Content-Type'] != 'text/cache-manifest' and \ response.status_code == 200: patch_cache_control(response, public=True, max_age=self.MAX_AGE) response['Expires'] = http_date(time.time() + self.MAX_AGE) return response
adieu/django-mediagenerator
cefcf83d8ebaf62142574a8917a2d56e4ffb5ccc
also use utf-8 when serving a few application/ mime types like JS, XML, XHTML
diff --git a/mediagenerator/middleware.py b/mediagenerator/middleware.py index 9df7252..71a4496 100644 --- a/mediagenerator/middleware.py +++ b/mediagenerator/middleware.py @@ -1,53 +1,59 @@ from .settings import DEV_MEDIA_URL, MEDIA_DEV_MODE # Only load other dependencies if they're needed if MEDIA_DEV_MODE: from .utils import _refresh_dev_names, _backend_mapping from django.http import HttpResponse, Http404 from django.utils.cache import patch_cache_control from django.utils.http import http_date import time +TEXT_MIME_TYPES = ( + 'application/x-javascript', + 'application/xhtml+xml', + 'application/xml', +) + class MediaMiddleware(object): """ Middleware for serving and browser-side caching of media files. This MUST be your *first* entry in MIDDLEWARE_CLASSES. Otherwise, some other middleware might add ETags or otherwise manipulate the caching headers which would result in the browser doing unnecessary HTTP roundtrips for unchanged media. """ MAX_AGE = 60 * 60 * 24 * 365 def process_request(self, request): if not MEDIA_DEV_MODE: return # We refresh the dev names only once for the whole request, so all # media_url() calls are cached. _refresh_dev_names() if not request.path.startswith(DEV_MEDIA_URL): return filename = request.path[len(DEV_MEDIA_URL):] try: backend = _backend_mapping[filename] except KeyError: raise Http404('No such media file "%s"' % filename) content, mimetype = backend.get_dev_output(filename) if isinstance(content, unicode): content = content.encode('utf-8') - if mimetype.startswith('text/'): + if mimetype.startswith('text/') or mimetype in TEXT_MIME_TYPES: mimetype += '; charset=utf-8' response = HttpResponse(content, content_type=mimetype) response['Content-Length'] = len(content) # Cache manifest files MUST NEVER be cached or you'll be unable to update # your cached app!!! if response['Content-Type'] != 'text/cache-manifest' and \ response.status_code == 200: patch_cache_control(response, public=True, max_age=self.MAX_AGE) response['Expires'] = http_date(time.time() + self.MAX_AGE) return response
adieu/django-mediagenerator
3ff38dcf91d0aaaef6dd1455d9bd029381677647
fixed handling of query parameters in CSS url()s
diff --git a/mediagenerator/filters/cssurl.py b/mediagenerator/filters/cssurl.py index fed4f17..d59f45a 100644 --- a/mediagenerator/filters/cssurl.py +++ b/mediagenerator/filters/cssurl.py @@ -1,84 +1,98 @@ from base64 import b64encode from django.conf import settings from mediagenerator.generators.bundles.base import Filter, FileFilter from mediagenerator.utils import media_url, prepare_patterns, find_file from mimetypes import guess_type import logging import os import posixpath import re url_re = re.compile(r'url\s*\(["\']?([\w\.][^:]*?)["\']?\)', re.UNICODE) # Whether to rewrite CSS URLs, at all REWRITE_CSS_URLS = getattr(settings, 'REWRITE_CSS_URLS', True) # Whether to rewrite CSS URLs relative to the respective source file # or whether to use "absolute" URL rewriting (i.e., relative URLs are # considered absolute with regards to STATICFILES_URL) REWRITE_CSS_URLS_RELATIVE_TO_SOURCE = getattr(settings, 'REWRITE_CSS_URLS_RELATIVE_TO_SOURCE', True) GENERATE_DATA_URIS = getattr(settings, 'GENERATE_DATA_URIS', False) MAX_DATA_URI_FILE_SIZE = getattr(settings, 'MAX_DATA_URI_FILE_SIZE', 12 * 1024) IGNORE_PATTERN = prepare_patterns(getattr(settings, 'IGNORE_DATA_URI_PATTERNS', (r'.*\.htc',)), 'IGNORE_DATA_URI_PATTERNS') class URLRewriter(object): def __init__(self, base_path='./'): if not base_path: base_path = './' self.base_path = base_path def rewrite_urls(self, content): if not REWRITE_CSS_URLS: return content return url_re.sub(self.fixurls, content) def fixurls(self, match): url = match.group(1) + hashid = '' if '#' in url: url, hashid = url.split('#', 1) hashid = '#' + hashid + + url_query = None + if '?' in url: + url, url_query = url.split('?', 1) + if ':' not in url and not url.startswith('/'): rebased_url = posixpath.join(self.base_path, url) rebased_url = posixpath.normpath(rebased_url) try: if GENERATE_DATA_URIS: path = find_file(rebased_url) if os.path.getsize(path) <= MAX_DATA_URI_FILE_SIZE and \ not IGNORE_PATTERN.match(rebased_url): data = b64encode(open(path, 'rb').read()) mime = guess_type(path)[0] or 'application/octet-stream' return 'url(data:%s;base64,%s)' % (mime, data) url = media_url(rebased_url) except: logging.error('URL not found: %s' % url) - return 'url(%s%s)' % (url, hashid) + + if url_query is None: + url_query = '' + elif '?' in url: + url_query = '&' + url_query + else: + url_query = '?' + url_query + + return 'url(%s%s%s)' % (url, url_query, hashid) class CSSURL(Filter): """Rewrites URLs relative to media folder ("absolute" rewriting).""" def __init__(self, **kwargs): super(CSSURL, self).__init__(**kwargs) assert self.filetype == 'css', ( 'CSSURL only supports CSS output. ' 'The parent filter expects "%s".' % self.filetype) def get_output(self, variation): rewriter = URLRewriter() for input in self.get_input(variation): yield rewriter.rewrite_urls(input) def get_dev_output(self, name, variation): rewriter = URLRewriter() content = super(CSSURL, self).get_dev_output(name, variation) return rewriter.rewrite_urls(content) class CSSURLFileFilter(FileFilter): """Rewrites URLs relative to input file's location.""" def get_dev_output(self, name, variation): content = super(CSSURLFileFilter, self).get_dev_output(name, variation) if not REWRITE_CSS_URLS_RELATIVE_TO_SOURCE: return content rewriter = URLRewriter(posixpath.dirname(name)) return rewriter.rewrite_urls(content)
adieu/django-mediagenerator
315fae185093824014bfe4868f1ac1d3100e5341
add charset when serving text/* mime types
diff --git a/mediagenerator/middleware.py b/mediagenerator/middleware.py index 06ec3e9..9df7252 100644 --- a/mediagenerator/middleware.py +++ b/mediagenerator/middleware.py @@ -1,51 +1,53 @@ from .settings import DEV_MEDIA_URL, MEDIA_DEV_MODE # Only load other dependencies if they're needed if MEDIA_DEV_MODE: from .utils import _refresh_dev_names, _backend_mapping from django.http import HttpResponse, Http404 from django.utils.cache import patch_cache_control from django.utils.http import http_date import time class MediaMiddleware(object): """ Middleware for serving and browser-side caching of media files. This MUST be your *first* entry in MIDDLEWARE_CLASSES. Otherwise, some other middleware might add ETags or otherwise manipulate the caching headers which would result in the browser doing unnecessary HTTP roundtrips for unchanged media. """ MAX_AGE = 60 * 60 * 24 * 365 def process_request(self, request): if not MEDIA_DEV_MODE: return # We refresh the dev names only once for the whole request, so all # media_url() calls are cached. _refresh_dev_names() if not request.path.startswith(DEV_MEDIA_URL): return filename = request.path[len(DEV_MEDIA_URL):] try: backend = _backend_mapping[filename] except KeyError: raise Http404('No such media file "%s"' % filename) content, mimetype = backend.get_dev_output(filename) if isinstance(content, unicode): content = content.encode('utf-8') + if mimetype.startswith('text/'): + mimetype += '; charset=utf-8' response = HttpResponse(content, content_type=mimetype) response['Content-Length'] = len(content) # Cache manifest files MUST NEVER be cached or you'll be unable to update # your cached app!!! if response['Content-Type'] != 'text/cache-manifest' and \ response.status_code == 200: patch_cache_control(response, public=True, max_age=self.MAX_AGE) response['Expires'] = http_date(time.time() + self.MAX_AGE) return response
adieu/django-mediagenerator
052d9f1ae075940819345ace5df9f3e5c721a7c6
fixed clevercss import issue
diff --git a/mediagenerator/filters/clevercss.py b/mediagenerator/filters/clever.py similarity index 100% rename from mediagenerator/filters/clevercss.py rename to mediagenerator/filters/clever.py diff --git a/mediagenerator/generators/bundles/settings.py b/mediagenerator/generators/bundles/settings.py index eb7741c..679fa0b 100644 --- a/mediagenerator/generators/bundles/settings.py +++ b/mediagenerator/generators/bundles/settings.py @@ -1,25 +1,25 @@ from django.conf import settings DEFAULT_MEDIA_FILTERS = getattr(settings, 'DEFAULT_MEDIA_FILTERS', { - 'ccss': 'mediagenerator.filters.clevercss.CleverCSS', + 'ccss': 'mediagenerator.filters.clever.CleverCSS', 'coffee': 'mediagenerator.filters.coffeescript.CoffeeScript', 'css': 'mediagenerator.filters.cssurl.CSSURLFileFilter', 'html': 'mediagenerator.filters.template.Template', 'py': 'mediagenerator.filters.pyjs_filter.Pyjs', 'pyva': 'mediagenerator.filters.pyvascript_filter.PyvaScript', 'sass': 'mediagenerator.filters.sass.Sass', 'scss': 'mediagenerator.filters.sass.Sass', }) ROOT_MEDIA_FILTERS = getattr(settings, 'ROOT_MEDIA_FILTERS', {}) # These are applied in addition to ROOT_MEDIA_FILTERS. # The separation is done because we don't want users to # always specify the default filters when they merely want # to configure YUICompressor or Closure. BASE_ROOT_MEDIA_FILTERS = getattr(settings, 'BASE_ROOT_MEDIA_FILTERS', { '*': 'mediagenerator.filters.concat.Concat', 'css': 'mediagenerator.filters.cssurl.CSSURL', }) MEDIA_BUNDLES = getattr(settings, 'MEDIA_BUNDLES', ())
adieu/django-mediagenerator
48c0250d86688fb0968373893f713c46f3af273e
Fixed python 2.5 not having the followlinks option for os.walk with proper version detection.
diff --git a/mediagenerator/filters/pyjs_filter.py b/mediagenerator/filters/pyjs_filter.py index 8977308..a70ea04 100644 --- a/mediagenerator/filters/pyjs_filter.py +++ b/mediagenerator/filters/pyjs_filter.py @@ -1,276 +1,287 @@ from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, read_text_file from pyjs.translator import import_compiler, Translator, LIBRARY_PATH from textwrap import dedent import os +import sys try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # Register PYVA() function try: from pyvascript.grammar import compile from pyjs.translator import native_js_func @native_js_func def PYVA(content, unescape, is_statement, **kwargs): result = compile(dedent(unescape(content))) if not is_statement: return result.strip().rstrip('\r\n\t ;') return result except ImportError: # No PyvaScript installed pass _HANDLE_EXCEPTIONS = """ } finally { $pyjs.in_try_except -= 1; } } catch(err) { pyjslib['_handle_exception'](err); } """ PYJS_INIT_LIB_PATH = os.path.join(LIBRARY_PATH, 'builtin', 'public', '_pyjs.js') BUILTIN_PATH = os.path.join(LIBRARY_PATH, 'builtin') STDLIB_PATH = os.path.join(LIBRARY_PATH, 'lib') EXTRA_LIBS_PATH = os.path.join(os.path.dirname(__file__), 'pyjslibs') _LOAD_PYJSLIB = """ $p = $pyjs.loaded_modules["pyjslib"]; $p('pyjslib'); $pyjs.__modules__.pyjslib = $p['pyjslib'] """ INIT_CODE = """ var $wnd = window; var $doc = window.document; var $pyjs = new Object(); var $p = null; $pyjs.platform = 'safari'; $pyjs.global_namespace = this; $pyjs.__modules__ = {}; $pyjs.modules_hash = {}; $pyjs.loaded_modules = {}; $pyjs.options = new Object(); $pyjs.options.arg_ignore = true; $pyjs.options.arg_count = true; $pyjs.options.arg_is_instance = true; $pyjs.options.arg_instance_type = false; $pyjs.options.arg_kwarg_dup = true; $pyjs.options.arg_kwarg_unexpected_keyword = true; $pyjs.options.arg_kwarg_multiple_values = true; $pyjs.options.dynamic_loading = false; $pyjs.trackstack = []; $pyjs.track = {module:'__main__', lineno: 1}; $pyjs.trackstack.push($pyjs.track); $pyjs.__active_exception_stack__ = null; $pyjs.__last_exception_stack__ = null; $pyjs.__last_exception__ = null; $pyjs.in_try_except = 0; """.lstrip() class Pyjs(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, exclude_main_libs=False, main_module=None, debug=None, path=(), only_dependencies=None) if isinstance(self.path, basestring): self.path = (self.path,) self.path += tuple(get_media_dirs()) if self.only_dependencies is None: self.only_dependencies = bool(self.main_module) if self.only_dependencies: self.path += (STDLIB_PATH, BUILTIN_PATH, EXTRA_LIBS_PATH) super(Pyjs, self).__init__(**kwargs) assert self.filetype == 'js', ( 'Pyjs only supports compilation to js. ' 'The parent filter expects "%s".' % self.filetype) if self.only_dependencies: assert self.main_module, \ 'You must provide a main module in only_dependencies mode' self._compiled = {} self._collected = {} @classmethod def from_default(cls, name): return {'main_module': name.rsplit('.', 1)[0].replace('/', '.')} def get_output(self, variation): self._collect_all_modules() if not self.exclude_main_libs: yield self._compile_init() if self.only_dependencies: self._regenerate(dev_mode=False) for name in sorted(self._compiled.keys()): yield self._compiled[name][1] else: for name in sorted(self._collected.keys()): source = read_text_file(self._collected[name]) yield self._compile(name, source, dev_mode=False)[0] yield self._compile_main(dev_mode=False) def get_dev_output(self, name, variation): self._collect_all_modules() name = name.split('/', 1)[-1] if name == '._pyjs.js': return self._compile_init() elif name == '.main.js': return self._compile_main(dev_mode=True) if self.only_dependencies: self._regenerate(dev_mode=True) return self._compiled[name][1] else: source = read_text_file(self._collected[name]) return self._compile(name, source, dev_mode=True)[0] def get_dev_output_names(self, variation): self._collect_all_modules() if not self.exclude_main_libs: content = self._compile_init() hash = sha1(smart_str(content)).hexdigest() yield '._pyjs.js', hash if self.only_dependencies: self._regenerate(dev_mode=True) for name in sorted(self._compiled.keys()): yield name, self._compiled[name][2] else: for name in sorted(self._collected.keys()): yield name, None if self.main_module is not None or not self.exclude_main_libs: content = self._compile_main(dev_mode=True) hash = sha1(smart_str(content)).hexdigest() yield '.main.js', hash def _regenerate(self, dev_mode=False): # This function is only called in only_dependencies mode if self._compiled: for module_name, (mtime, content, hash) in self._compiled.items(): if module_name not in self._collected or \ not os.path.exists(self._collected[module_name]) or \ os.path.getmtime(self._collected[module_name]) != mtime: # Just recompile everything # TODO: track dependencies and changes and recompile only # what's necessary self._compiled = {} break else: # No changes return modules = [self.main_module, 'pyjslib'] while True: if not modules: break module_name = modules.pop() path = self._collected[module_name] mtime = os.path.getmtime(path) source = read_text_file(path) try: content, py_deps, js_deps = self._compile(module_name, source, dev_mode=dev_mode) except: self._compiled = {} raise hash = sha1(smart_str(content)).hexdigest() self._compiled[module_name] = (mtime, content, hash) for name in py_deps: if name not in self._collected: if '.' in name and name.rsplit('.', 1)[0] in self._collected: name = name.rsplit('.', 1)[0] else: raise ImportError('The pyjs module %s could not find ' 'the dependency %s' % (module_name, name)) if name not in self._compiled: modules.append(name) def _compile(self, name, source, dev_mode=False): if self.debug is None: debug = dev_mode else: debug = self.debug compiler = import_compiler(False) tree = compiler.parse(source) output = StringIO() translator = Translator(compiler, name, name, source, tree, output, # Debug options debug=debug, source_tracking=debug, line_tracking=debug, store_source=debug, # Speed and size optimizations function_argument_checking=debug, attribute_checking=False, inline_code=False, number_classes=False, # Sufficient Python conformance operator_funcs=True, bound_methods=True, descriptors=True, ) return output.getvalue(), translator.imported_modules, translator.imported_js def _compile_init(self): return INIT_CODE + read_text_file(PYJS_INIT_LIB_PATH) def _compile_main(self, dev_mode=False): if self.debug is None: debug = dev_mode else: debug = self.debug content = '' if not self.exclude_main_libs: content += _LOAD_PYJSLIB if self.main_module is not None: content += '\n\n' if debug: content += 'try {\n' content += ' try {\n' content += ' $pyjs.in_try_except += 1;\n ' content += 'pyjslib.___import___("%s", null, "__main__");' % self.main_module if debug: content += _HANDLE_EXCEPTIONS return content def _collect_all_modules(self): """Collect modules, so we can handle imports later""" for pkgroot in self.path: pkgroot = os.path.abspath(pkgroot) - for root, dirs, files in os.walk(pkgroot, followlinks=True): + + #python 2.5 does not have the followlinks keyword argument + has_followlinks = sys.version_info >= (2, 6) + if has_followlinks: + allfiles = os.walk(pkgroot, followlinks=True) + else: + allfiles = os.walk(pkgroot) + + for root, dirs, files in allfiles: if '__init__.py' in files: files.remove('__init__.py') # The root __init__.py is ignored if root != pkgroot: files.insert(0, '__init__.py') elif root != pkgroot: # Only add valid Python packages dirs[:] = [] continue for filename in files: if not filename.endswith('.py'): continue path = os.path.join(root, filename) + if not has_followlinks: + path = os.path.abspath(path) module_path = path[len(pkgroot) + len(os.sep):] if os.path.basename(module_path) == '__init__.py': module_name = os.path.dirname(module_path) else: module_name = module_path[:-3] assert '.' not in module_name, \ 'Invalid module file name: %s' % module_path module_name = module_name.replace(os.sep, '.') self._collected.setdefault(module_name, path) diff --git a/mediagenerator/generators/copyfiles.py b/mediagenerator/generators/copyfiles.py index fb27a2c..34599a7 100644 --- a/mediagenerator/generators/copyfiles.py +++ b/mediagenerator/generators/copyfiles.py @@ -1,44 +1,54 @@ from django.conf import settings from hashlib import sha1 from mediagenerator.base import Generator from mediagenerator.utils import get_media_dirs, find_file, prepare_patterns from mimetypes import guess_type import os +import sys COPY_MEDIA_FILETYPES = getattr(settings, 'COPY_MEDIA_FILETYPES', ('gif', 'jpg', 'jpeg', 'png', 'svg', 'svgz', 'ico', 'swf', 'ttf', 'otf', 'eot', 'woff')) IGNORE_PATTERN = prepare_patterns(getattr(settings, 'IGNORE_MEDIA_COPY_PATTERNS', ()), 'IGNORE_MEDIA_COPY_PATTERNS') class CopyFiles(Generator): def get_dev_output(self, name): path = find_file(name) fp = open(path, 'rb') content = fp.read() fp.close() mimetype = guess_type(path)[0] return content, mimetype def get_dev_output_names(self): media_files = {} for root in get_media_dirs(): self.collect_copyable_files(media_files, root) for name, source in media_files.items(): fp = open(source, 'rb') hash = sha1(fp.read()).hexdigest() fp.close() yield name, name, hash def collect_copyable_files(self, media_files, root): - for root_path, dirs, files in os.walk(root): + #python 2.5 does not have the followlinks keyword argument + has_followlinks = sys.version_info >= (2, 6) + if has_followlinks: + allfiles = os.walk(root, followlinks=True) + else: + allfiles = os.walk(root) + + for root_path, dirs, files in allfiles: for file in files: ext = os.path.splitext(file)[1].lstrip('.') - path = os.path.abspath(os.path.join(root_path, file)) + path = os.path.join(root_path, file) + if not has_followlinks: + path = os.path.abspath(path) media_path = path[len(root) + 1:].replace(os.sep, '/') if ext in COPY_MEDIA_FILETYPES and \ not IGNORE_PATTERN.match(media_path): media_files[media_path] = path
adieu/django-mediagenerator
608b1df5f3f6a8b5e6ff5c5825740ce96b4920e3
Fixed python 2.5 does not having the followlinks option for os.walk.
diff --git a/mediagenerator/generators/copyfiles.py b/mediagenerator/generators/copyfiles.py index 1e9285f..fb27a2c 100644 --- a/mediagenerator/generators/copyfiles.py +++ b/mediagenerator/generators/copyfiles.py @@ -1,43 +1,44 @@ from django.conf import settings from hashlib import sha1 from mediagenerator.base import Generator from mediagenerator.utils import get_media_dirs, find_file, prepare_patterns from mimetypes import guess_type import os COPY_MEDIA_FILETYPES = getattr(settings, 'COPY_MEDIA_FILETYPES', ('gif', 'jpg', 'jpeg', 'png', 'svg', 'svgz', 'ico', 'swf', 'ttf', 'otf', 'eot', 'woff')) IGNORE_PATTERN = prepare_patterns(getattr(settings, 'IGNORE_MEDIA_COPY_PATTERNS', ()), 'IGNORE_MEDIA_COPY_PATTERNS') + class CopyFiles(Generator): def get_dev_output(self, name): path = find_file(name) fp = open(path, 'rb') content = fp.read() fp.close() mimetype = guess_type(path)[0] return content, mimetype def get_dev_output_names(self): media_files = {} for root in get_media_dirs(): self.collect_copyable_files(media_files, root) for name, source in media_files.items(): fp = open(source, 'rb') hash = sha1(fp.read()).hexdigest() fp.close() yield name, name, hash def collect_copyable_files(self, media_files, root): - for root_path, dirs, files in os.walk(root, followlinks=True): + for root_path, dirs, files in os.walk(root): for file in files: ext = os.path.splitext(file)[1].lstrip('.') - path = os.path.join(root_path, file) + path = os.path.abspath(os.path.join(root_path, file)) media_path = path[len(root) + 1:].replace(os.sep, '/') if ext in COPY_MEDIA_FILETYPES and \ not IGNORE_PATTERN.match(media_path): media_files[media_path] = path
adieu/django-mediagenerator
296787e662703ec0c6c54beff7dea06ff2943b2f
Fixed unix issue concerning os.walk and softlinks.
diff --git a/mediagenerator/filters/pyjs_filter.py b/mediagenerator/filters/pyjs_filter.py index 25d388d..8977308 100644 --- a/mediagenerator/filters/pyjs_filter.py +++ b/mediagenerator/filters/pyjs_filter.py @@ -1,276 +1,276 @@ from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, read_text_file from pyjs.translator import import_compiler, Translator, LIBRARY_PATH from textwrap import dedent import os try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # Register PYVA() function try: from pyvascript.grammar import compile from pyjs.translator import native_js_func @native_js_func def PYVA(content, unescape, is_statement, **kwargs): result = compile(dedent(unescape(content))) if not is_statement: return result.strip().rstrip('\r\n\t ;') return result except ImportError: # No PyvaScript installed pass _HANDLE_EXCEPTIONS = """ } finally { $pyjs.in_try_except -= 1; } } catch(err) { pyjslib['_handle_exception'](err); } """ PYJS_INIT_LIB_PATH = os.path.join(LIBRARY_PATH, 'builtin', 'public', '_pyjs.js') BUILTIN_PATH = os.path.join(LIBRARY_PATH, 'builtin') STDLIB_PATH = os.path.join(LIBRARY_PATH, 'lib') EXTRA_LIBS_PATH = os.path.join(os.path.dirname(__file__), 'pyjslibs') _LOAD_PYJSLIB = """ $p = $pyjs.loaded_modules["pyjslib"]; $p('pyjslib'); $pyjs.__modules__.pyjslib = $p['pyjslib'] """ INIT_CODE = """ var $wnd = window; var $doc = window.document; var $pyjs = new Object(); var $p = null; $pyjs.platform = 'safari'; $pyjs.global_namespace = this; $pyjs.__modules__ = {}; $pyjs.modules_hash = {}; $pyjs.loaded_modules = {}; $pyjs.options = new Object(); $pyjs.options.arg_ignore = true; $pyjs.options.arg_count = true; $pyjs.options.arg_is_instance = true; $pyjs.options.arg_instance_type = false; $pyjs.options.arg_kwarg_dup = true; $pyjs.options.arg_kwarg_unexpected_keyword = true; $pyjs.options.arg_kwarg_multiple_values = true; $pyjs.options.dynamic_loading = false; $pyjs.trackstack = []; $pyjs.track = {module:'__main__', lineno: 1}; $pyjs.trackstack.push($pyjs.track); $pyjs.__active_exception_stack__ = null; $pyjs.__last_exception_stack__ = null; $pyjs.__last_exception__ = null; $pyjs.in_try_except = 0; """.lstrip() class Pyjs(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, exclude_main_libs=False, main_module=None, debug=None, path=(), only_dependencies=None) if isinstance(self.path, basestring): self.path = (self.path,) self.path += tuple(get_media_dirs()) if self.only_dependencies is None: self.only_dependencies = bool(self.main_module) if self.only_dependencies: self.path += (STDLIB_PATH, BUILTIN_PATH, EXTRA_LIBS_PATH) super(Pyjs, self).__init__(**kwargs) assert self.filetype == 'js', ( 'Pyjs only supports compilation to js. ' 'The parent filter expects "%s".' % self.filetype) if self.only_dependencies: assert self.main_module, \ 'You must provide a main module in only_dependencies mode' self._compiled = {} self._collected = {} @classmethod def from_default(cls, name): return {'main_module': name.rsplit('.', 1)[0].replace('/', '.')} def get_output(self, variation): self._collect_all_modules() if not self.exclude_main_libs: yield self._compile_init() if self.only_dependencies: self._regenerate(dev_mode=False) for name in sorted(self._compiled.keys()): yield self._compiled[name][1] else: for name in sorted(self._collected.keys()): source = read_text_file(self._collected[name]) yield self._compile(name, source, dev_mode=False)[0] yield self._compile_main(dev_mode=False) def get_dev_output(self, name, variation): self._collect_all_modules() name = name.split('/', 1)[-1] if name == '._pyjs.js': return self._compile_init() elif name == '.main.js': return self._compile_main(dev_mode=True) if self.only_dependencies: self._regenerate(dev_mode=True) return self._compiled[name][1] else: source = read_text_file(self._collected[name]) return self._compile(name, source, dev_mode=True)[0] def get_dev_output_names(self, variation): self._collect_all_modules() if not self.exclude_main_libs: content = self._compile_init() hash = sha1(smart_str(content)).hexdigest() yield '._pyjs.js', hash if self.only_dependencies: self._regenerate(dev_mode=True) for name in sorted(self._compiled.keys()): yield name, self._compiled[name][2] else: for name in sorted(self._collected.keys()): yield name, None if self.main_module is not None or not self.exclude_main_libs: content = self._compile_main(dev_mode=True) hash = sha1(smart_str(content)).hexdigest() yield '.main.js', hash def _regenerate(self, dev_mode=False): # This function is only called in only_dependencies mode if self._compiled: for module_name, (mtime, content, hash) in self._compiled.items(): if module_name not in self._collected or \ not os.path.exists(self._collected[module_name]) or \ os.path.getmtime(self._collected[module_name]) != mtime: # Just recompile everything # TODO: track dependencies and changes and recompile only # what's necessary self._compiled = {} break else: # No changes return modules = [self.main_module, 'pyjslib'] while True: if not modules: break module_name = modules.pop() path = self._collected[module_name] mtime = os.path.getmtime(path) source = read_text_file(path) try: content, py_deps, js_deps = self._compile(module_name, source, dev_mode=dev_mode) except: self._compiled = {} raise hash = sha1(smart_str(content)).hexdigest() self._compiled[module_name] = (mtime, content, hash) for name in py_deps: if name not in self._collected: if '.' in name and name.rsplit('.', 1)[0] in self._collected: name = name.rsplit('.', 1)[0] else: raise ImportError('The pyjs module %s could not find ' 'the dependency %s' % (module_name, name)) if name not in self._compiled: modules.append(name) def _compile(self, name, source, dev_mode=False): if self.debug is None: debug = dev_mode else: debug = self.debug compiler = import_compiler(False) tree = compiler.parse(source) output = StringIO() translator = Translator(compiler, name, name, source, tree, output, # Debug options debug=debug, source_tracking=debug, line_tracking=debug, store_source=debug, # Speed and size optimizations function_argument_checking=debug, attribute_checking=False, inline_code=False, number_classes=False, # Sufficient Python conformance operator_funcs=True, bound_methods=True, descriptors=True, ) return output.getvalue(), translator.imported_modules, translator.imported_js def _compile_init(self): return INIT_CODE + read_text_file(PYJS_INIT_LIB_PATH) def _compile_main(self, dev_mode=False): if self.debug is None: debug = dev_mode else: debug = self.debug content = '' if not self.exclude_main_libs: content += _LOAD_PYJSLIB if self.main_module is not None: content += '\n\n' if debug: content += 'try {\n' content += ' try {\n' content += ' $pyjs.in_try_except += 1;\n ' content += 'pyjslib.___import___("%s", null, "__main__");' % self.main_module if debug: content += _HANDLE_EXCEPTIONS return content def _collect_all_modules(self): """Collect modules, so we can handle imports later""" for pkgroot in self.path: pkgroot = os.path.abspath(pkgroot) - for root, dirs, files in os.walk(pkgroot): + for root, dirs, files in os.walk(pkgroot, followlinks=True): if '__init__.py' in files: files.remove('__init__.py') # The root __init__.py is ignored if root != pkgroot: files.insert(0, '__init__.py') elif root != pkgroot: # Only add valid Python packages dirs[:] = [] continue for filename in files: if not filename.endswith('.py'): continue path = os.path.join(root, filename) module_path = path[len(pkgroot) + len(os.sep):] if os.path.basename(module_path) == '__init__.py': module_name = os.path.dirname(module_path) else: module_name = module_path[:-3] assert '.' not in module_name, \ 'Invalid module file name: %s' % module_path module_name = module_name.replace(os.sep, '.') self._collected.setdefault(module_name, path) diff --git a/mediagenerator/generators/copyfiles.py b/mediagenerator/generators/copyfiles.py index f275767..1e9285f 100644 --- a/mediagenerator/generators/copyfiles.py +++ b/mediagenerator/generators/copyfiles.py @@ -1,43 +1,43 @@ from django.conf import settings from hashlib import sha1 from mediagenerator.base import Generator from mediagenerator.utils import get_media_dirs, find_file, prepare_patterns from mimetypes import guess_type import os COPY_MEDIA_FILETYPES = getattr(settings, 'COPY_MEDIA_FILETYPES', ('gif', 'jpg', 'jpeg', 'png', 'svg', 'svgz', 'ico', 'swf', 'ttf', 'otf', 'eot', 'woff')) IGNORE_PATTERN = prepare_patterns(getattr(settings, 'IGNORE_MEDIA_COPY_PATTERNS', ()), 'IGNORE_MEDIA_COPY_PATTERNS') class CopyFiles(Generator): def get_dev_output(self, name): path = find_file(name) fp = open(path, 'rb') content = fp.read() fp.close() mimetype = guess_type(path)[0] return content, mimetype def get_dev_output_names(self): media_files = {} for root in get_media_dirs(): self.collect_copyable_files(media_files, root) for name, source in media_files.items(): fp = open(source, 'rb') hash = sha1(fp.read()).hexdigest() fp.close() yield name, name, hash def collect_copyable_files(self, media_files, root): - for root_path, dirs, files in os.walk(root): + for root_path, dirs, files in os.walk(root, followlinks=True): for file in files: ext = os.path.splitext(file)[1].lstrip('.') path = os.path.join(root_path, file) media_path = path[len(root) + 1:].replace(os.sep, '/') if ext in COPY_MEDIA_FILETYPES and \ not IGNORE_PATTERN.match(media_path): media_files[media_path] = path
adieu/django-mediagenerator
8cc91c8985b4e49b95012f1bd3fed41eeb97ce03
fixed pyjs support for main module in subfolder
diff --git a/mediagenerator/filters/pyjs_filter.py b/mediagenerator/filters/pyjs_filter.py index 5c3a3c1..25d388d 100644 --- a/mediagenerator/filters/pyjs_filter.py +++ b/mediagenerator/filters/pyjs_filter.py @@ -1,276 +1,276 @@ from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, read_text_file from pyjs.translator import import_compiler, Translator, LIBRARY_PATH from textwrap import dedent import os try: from cStringIO import StringIO except ImportError: from StringIO import StringIO # Register PYVA() function try: from pyvascript.grammar import compile from pyjs.translator import native_js_func @native_js_func def PYVA(content, unescape, is_statement, **kwargs): result = compile(dedent(unescape(content))) if not is_statement: return result.strip().rstrip('\r\n\t ;') return result except ImportError: # No PyvaScript installed pass _HANDLE_EXCEPTIONS = """ } finally { $pyjs.in_try_except -= 1; } } catch(err) { pyjslib['_handle_exception'](err); } """ PYJS_INIT_LIB_PATH = os.path.join(LIBRARY_PATH, 'builtin', 'public', '_pyjs.js') BUILTIN_PATH = os.path.join(LIBRARY_PATH, 'builtin') STDLIB_PATH = os.path.join(LIBRARY_PATH, 'lib') EXTRA_LIBS_PATH = os.path.join(os.path.dirname(__file__), 'pyjslibs') _LOAD_PYJSLIB = """ $p = $pyjs.loaded_modules["pyjslib"]; $p('pyjslib'); $pyjs.__modules__.pyjslib = $p['pyjslib'] """ INIT_CODE = """ var $wnd = window; var $doc = window.document; var $pyjs = new Object(); var $p = null; $pyjs.platform = 'safari'; $pyjs.global_namespace = this; $pyjs.__modules__ = {}; $pyjs.modules_hash = {}; $pyjs.loaded_modules = {}; $pyjs.options = new Object(); $pyjs.options.arg_ignore = true; $pyjs.options.arg_count = true; $pyjs.options.arg_is_instance = true; $pyjs.options.arg_instance_type = false; $pyjs.options.arg_kwarg_dup = true; $pyjs.options.arg_kwarg_unexpected_keyword = true; $pyjs.options.arg_kwarg_multiple_values = true; $pyjs.options.dynamic_loading = false; $pyjs.trackstack = []; $pyjs.track = {module:'__main__', lineno: 1}; $pyjs.trackstack.push($pyjs.track); $pyjs.__active_exception_stack__ = null; $pyjs.__last_exception_stack__ = null; $pyjs.__last_exception__ = null; $pyjs.in_try_except = 0; """.lstrip() class Pyjs(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, exclude_main_libs=False, main_module=None, debug=None, path=(), only_dependencies=None) if isinstance(self.path, basestring): self.path = (self.path,) self.path += tuple(get_media_dirs()) if self.only_dependencies is None: self.only_dependencies = bool(self.main_module) if self.only_dependencies: self.path += (STDLIB_PATH, BUILTIN_PATH, EXTRA_LIBS_PATH) super(Pyjs, self).__init__(**kwargs) assert self.filetype == 'js', ( 'Pyjs only supports compilation to js. ' 'The parent filter expects "%s".' % self.filetype) if self.only_dependencies: assert self.main_module, \ 'You must provide a main module in only_dependencies mode' self._compiled = {} self._collected = {} @classmethod def from_default(cls, name): - return {'main_module': name.rsplit('.', 1)[0]} + return {'main_module': name.rsplit('.', 1)[0].replace('/', '.')} def get_output(self, variation): self._collect_all_modules() if not self.exclude_main_libs: yield self._compile_init() if self.only_dependencies: self._regenerate(dev_mode=False) for name in sorted(self._compiled.keys()): yield self._compiled[name][1] else: for name in sorted(self._collected.keys()): source = read_text_file(self._collected[name]) yield self._compile(name, source, dev_mode=False)[0] yield self._compile_main(dev_mode=False) def get_dev_output(self, name, variation): self._collect_all_modules() name = name.split('/', 1)[-1] if name == '._pyjs.js': return self._compile_init() elif name == '.main.js': return self._compile_main(dev_mode=True) if self.only_dependencies: self._regenerate(dev_mode=True) return self._compiled[name][1] else: source = read_text_file(self._collected[name]) return self._compile(name, source, dev_mode=True)[0] def get_dev_output_names(self, variation): self._collect_all_modules() if not self.exclude_main_libs: content = self._compile_init() hash = sha1(smart_str(content)).hexdigest() yield '._pyjs.js', hash if self.only_dependencies: self._regenerate(dev_mode=True) for name in sorted(self._compiled.keys()): yield name, self._compiled[name][2] else: for name in sorted(self._collected.keys()): yield name, None if self.main_module is not None or not self.exclude_main_libs: content = self._compile_main(dev_mode=True) hash = sha1(smart_str(content)).hexdigest() yield '.main.js', hash def _regenerate(self, dev_mode=False): # This function is only called in only_dependencies mode if self._compiled: for module_name, (mtime, content, hash) in self._compiled.items(): if module_name not in self._collected or \ not os.path.exists(self._collected[module_name]) or \ os.path.getmtime(self._collected[module_name]) != mtime: # Just recompile everything # TODO: track dependencies and changes and recompile only # what's necessary self._compiled = {} break else: # No changes return modules = [self.main_module, 'pyjslib'] while True: if not modules: break module_name = modules.pop() path = self._collected[module_name] mtime = os.path.getmtime(path) source = read_text_file(path) try: content, py_deps, js_deps = self._compile(module_name, source, dev_mode=dev_mode) except: self._compiled = {} raise hash = sha1(smart_str(content)).hexdigest() self._compiled[module_name] = (mtime, content, hash) for name in py_deps: if name not in self._collected: if '.' in name and name.rsplit('.', 1)[0] in self._collected: name = name.rsplit('.', 1)[0] else: raise ImportError('The pyjs module %s could not find ' 'the dependency %s' % (module_name, name)) if name not in self._compiled: modules.append(name) def _compile(self, name, source, dev_mode=False): if self.debug is None: debug = dev_mode else: debug = self.debug compiler = import_compiler(False) tree = compiler.parse(source) output = StringIO() translator = Translator(compiler, name, name, source, tree, output, # Debug options debug=debug, source_tracking=debug, line_tracking=debug, store_source=debug, # Speed and size optimizations function_argument_checking=debug, attribute_checking=False, inline_code=False, number_classes=False, # Sufficient Python conformance operator_funcs=True, bound_methods=True, descriptors=True, ) return output.getvalue(), translator.imported_modules, translator.imported_js def _compile_init(self): return INIT_CODE + read_text_file(PYJS_INIT_LIB_PATH) def _compile_main(self, dev_mode=False): if self.debug is None: debug = dev_mode else: debug = self.debug content = '' if not self.exclude_main_libs: content += _LOAD_PYJSLIB if self.main_module is not None: content += '\n\n' if debug: content += 'try {\n' content += ' try {\n' content += ' $pyjs.in_try_except += 1;\n ' content += 'pyjslib.___import___("%s", null, "__main__");' % self.main_module if debug: content += _HANDLE_EXCEPTIONS return content def _collect_all_modules(self): """Collect modules, so we can handle imports later""" for pkgroot in self.path: pkgroot = os.path.abspath(pkgroot) for root, dirs, files in os.walk(pkgroot): if '__init__.py' in files: files.remove('__init__.py') # The root __init__.py is ignored if root != pkgroot: files.insert(0, '__init__.py') elif root != pkgroot: # Only add valid Python packages dirs[:] = [] continue for filename in files: if not filename.endswith('.py'): continue path = os.path.join(root, filename) module_path = path[len(pkgroot) + len(os.sep):] if os.path.basename(module_path) == '__init__.py': module_name = os.path.dirname(module_path) else: module_name = module_path[:-3] assert '.' not in module_name, \ 'Invalid module file name: %s' % module_path module_name = module_name.replace(os.sep, '.') self._collected.setdefault(module_name, path)
adieu/django-mediagenerator
97e6e402aa6e0e0a10353cd1575810e86199dc16
fixed dev mode file serving of unicode content (content length was incorrect)
diff --git a/mediagenerator/middleware.py b/mediagenerator/middleware.py index bcb3217..06ec3e9 100644 --- a/mediagenerator/middleware.py +++ b/mediagenerator/middleware.py @@ -1,49 +1,51 @@ from .settings import DEV_MEDIA_URL, MEDIA_DEV_MODE # Only load other dependencies if they're needed if MEDIA_DEV_MODE: from .utils import _refresh_dev_names, _backend_mapping from django.http import HttpResponse, Http404 from django.utils.cache import patch_cache_control from django.utils.http import http_date import time class MediaMiddleware(object): """ Middleware for serving and browser-side caching of media files. This MUST be your *first* entry in MIDDLEWARE_CLASSES. Otherwise, some other middleware might add ETags or otherwise manipulate the caching headers which would result in the browser doing unnecessary HTTP roundtrips for unchanged media. """ MAX_AGE = 60 * 60 * 24 * 365 def process_request(self, request): if not MEDIA_DEV_MODE: return # We refresh the dev names only once for the whole request, so all # media_url() calls are cached. _refresh_dev_names() if not request.path.startswith(DEV_MEDIA_URL): return filename = request.path[len(DEV_MEDIA_URL):] try: backend = _backend_mapping[filename] except KeyError: raise Http404('No such media file "%s"' % filename) content, mimetype = backend.get_dev_output(filename) + if isinstance(content, unicode): + content = content.encode('utf-8') response = HttpResponse(content, content_type=mimetype) response['Content-Length'] = len(content) # Cache manifest files MUST NEVER be cached or you'll be unable to update # your cached app!!! if response['Content-Type'] != 'text/cache-manifest' and \ response.status_code == 200: patch_cache_control(response, public=True, max_age=self.MAX_AGE) response['Expires'] = http_date(time.time() + self.MAX_AGE) return response
adieu/django-mediagenerator
5a945407691a5d39191d6791b77896c868443b22
bumped version
diff --git a/setup.py b/setup.py index 8c26c91..e0c7282 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ from setuptools import setup, find_packages DESCRIPTION = 'Asset manager for Django' LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() except: pass setup(name='django-mediagenerator', - version='1.10.2', + version='1.10.3', packages=find_packages(exclude=('tests', 'tests.*', 'base_project', 'base_project.*')), package_data={'mediagenerator.filters': ['pyjslibs/*.py', '*.rb'], 'mediagenerator': ['templates/mediagenerator/manifest/*']}, author='Waldemar Kornewald', author_email='[email protected]', url='http://www.allbuttonspressed.com/projects/django-mediagenerator', description=DESCRIPTION, long_description=LONG_DESCRIPTION, platforms=['any'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], )
adieu/django-mediagenerator
b0765cb56cef369173980a9d72814b26b594f8b6
fixed Sass filter on Linux (again :) - Sass on Linux doesn't have the -E parameter
diff --git a/mediagenerator/filters/sass.py b/mediagenerator/filters/sass.py index 4f15d43..1af870b 100644 --- a/mediagenerator/filters/sass.py +++ b/mediagenerator/filters/sass.py @@ -1,153 +1,156 @@ from django.conf import settings from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, find_file, read_text_file from subprocess import Popen, PIPE import os import posixpath import re import sys # Emits extra debug info that can be used by the FireSass Firebug plugin SASS_DEBUG_INFO = getattr(settings, 'SASS_DEBUG_INFO', False) SASS_FRAMEWORKS = getattr(settings, 'SASS_FRAMEWORKS', ('compass', 'blueprint')) if isinstance(SASS_FRAMEWORKS, basestring): SASS_FRAMEWORKS = (SASS_FRAMEWORKS,) _RE_FLAGS = re.MULTILINE | re.UNICODE multi_line_comment_re = re.compile(r'/\*.*?\*/', _RE_FLAGS | re.DOTALL) one_line_comment_re = re.compile(r'//.*', _RE_FLAGS) import_re = re.compile(r'^@import\s+["\']?(.+?)["\']?\s*;?\s*$', _RE_FLAGS) class Sass(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, path=(), main_module=None) if isinstance(self.path, basestring): self.path = (self.path,) super(Sass, self).__init__(**kwargs) assert self.filetype == 'css', ( 'Sass only supports compilation to css. ' 'The parent filter expects "%s".' % self.filetype) assert self.main_module, \ 'You must provide a main module' self.path += tuple(get_media_dirs()) self.path_args = [] for path in self.path: self.path_args.extend(('-I', path.replace('\\', '/'))) self._compiled = None self._compiled_hash = None self._dependencies = {} @classmethod def from_default(cls, name): return {'main_module': name} def get_output(self, variation): self._regenerate(debug=False) yield self._compiled def get_dev_output(self, name, variation): assert name == self.main_module self._regenerate(debug=True) return self._compiled def get_dev_output_names(self, variation): self._regenerate(debug=True) yield self.main_module, self._compiled_hash def _compile(self, debug=False): extensions = os.path.join(os.path.dirname(__file__), 'sass_compass.rb') extensions = extensions.replace('\\', '/') - run = ['sass', '-E', 'utf-8', '-C', '-t', 'expanded', + run = ['sass', '-C', '-t', 'expanded', '--require', extensions] for framework in SASS_FRAMEWORKS: # Some frameworks are loaded by default if framework in ('blueprint', 'compass'): continue run.extend(('--require', framework)) if debug: run.append('--line-numbers') if SASS_DEBUG_INFO: run.append('--debug-info') run.extend(self.path_args) shell = sys.platform == 'win32' try: cmd = Popen(run, shell=shell, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) module = self.main_module.rsplit('.', 1)[0] output, error = cmd.communicate('@import "%s"' % module) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error - return output.decode('utf-8') + output = output.decode('utf-8') + if output.startswith('@charset '): + output = output.split(';', 1)[1] + return output except Exception, e: raise ValueError("Failed to execute Sass. Please make sure that " "you have installed Sass (http://sass-lang.com) and " "Compass (http://compass-style.org).\n" "Error was: %s" % e) def _regenerate(self, debug=False): if self._dependencies: for name, mtime in self._dependencies.items(): path = self._find_file(name) if not path or os.path.getmtime(path) != mtime: # Just recompile everything self._dependencies = {} break else: # No changes return modules = [self.main_module] while True: if not modules: break module_name = modules.pop() path = self._find_file(module_name) assert path, 'Could not find the Sass module %s' % module_name mtime = os.path.getmtime(path) self._dependencies[module_name] = mtime source = read_text_file(path) dependencies = self._get_dependencies(source) for name in dependencies: # Try relative import, first transformed = posixpath.join(posixpath.dirname(module_name), name) path = self._find_file(transformed) if path: name = transformed else: path = self._find_file(name) assert path, ('The Sass module %s could not find the ' 'dependency %s' % (module_name, name)) if name not in self._dependencies: modules.append(name) self._compiled = self._compile(debug=debug) self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() def _get_dependencies(self, source): clean_source = multi_line_comment_re.sub('\n', source) clean_source = one_line_comment_re.sub('', clean_source) return [name for name in import_re.findall(clean_source) if not name.endswith('.css')] def _find_file(self, name): parts = name.rsplit('/', 1) parts[-1] = '_' + parts[-1] partial = '/'.join(parts) if not name.endswith(('.sass', '.scss')): names = (name + '.sass', name + '.scss', partial + '.sass', partial + '.scss') else: names = (name, partial) for name in names: path = find_file(name, media_dirs=self.path) if path: return path diff --git a/mediagenerator/utils.py b/mediagenerator/utils.py index b319cd4..bdc5297 100644 --- a/mediagenerator/utils.py +++ b/mediagenerator/utils.py @@ -1,146 +1,145 @@ from . import settings as media_settings from .settings import (GLOBAL_MEDIA_DIRS, PRODUCTION_MEDIA_URL, IGNORE_APP_MEDIA_DIRS, MEDIA_GENERATORS, DEV_MEDIA_URL, GENERATED_MEDIA_NAMES_MODULE) from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from django.utils.http import urlquote import os import re try: NAMES = import_module(GENERATED_MEDIA_NAMES_MODULE).NAMES except (ImportError, AttributeError): NAMES = None _backends_cache = {} _media_dirs_cache = [] _generators_cache = [] _generated_names = {} _backend_mapping = {} def _load_generators(): if not _generators_cache: for name in MEDIA_GENERATORS: backend = load_backend(name)() _generators_cache.append(backend) return _generators_cache def _refresh_dev_names(): _generated_names.clear() _backend_mapping.clear() for backend in _load_generators(): for key, url, hash in backend.get_dev_output_names(): versioned_url = urlquote(url) if hash: versioned_url += '?version=' + hash _generated_names.setdefault(key, []) _generated_names[key].append(versioned_url) _backend_mapping[url] = backend class _MatchNothing(object): def match(self, content): return False def prepare_patterns(patterns, setting_name): """Helper function for patter-matching settings.""" if isinstance(patterns, basestring): patterns = (patterns,) if not patterns: return _MatchNothing() # First validate each pattern individually for pattern in patterns: try: re.compile(pattern, re.U) except re.error: raise ValueError("""Pattern "%s" can't be compiled """ "in %s" % (pattern, setting_name)) # Now return a combined pattern return re.compile('^(' + ')$|^('.join(patterns) + ')$', re.U) def get_production_mapping(): if NAMES is None: raise ImportError('Could not import %s. This ' 'file is needed for production mode. Please ' 'run manage.py generatemedia to create it.' % GENERATED_MEDIA_NAMES_MODULE) return NAMES def get_media_mapping(): if media_settings.MEDIA_DEV_MODE: return _generated_names return get_production_mapping() def get_media_url_mapping(): if media_settings.MEDIA_DEV_MODE: base_url = DEV_MEDIA_URL else: base_url = PRODUCTION_MEDIA_URL mapping = {} for key, value in get_media_mapping().items(): if isinstance(value, basestring): value = (value,) mapping[key] = [base_url + url for url in value] return mapping def media_urls(key, refresh=False): if media_settings.MEDIA_DEV_MODE: if refresh: _refresh_dev_names() return [DEV_MEDIA_URL + url for url in _generated_names[key]] - print repr(get_production_mapping()) return [PRODUCTION_MEDIA_URL + get_production_mapping()[key]] def media_url(key, refresh=False): urls = media_urls(key, refresh=refresh) if len(urls) == 1: return urls[0] raise ValueError('media_url() only works with URLs that contain exactly ' 'one file. Use media_urls() (or {% include_media %} in templates) instead.') def get_media_dirs(): if not _media_dirs_cache: media_dirs = GLOBAL_MEDIA_DIRS[:] for app in settings.INSTALLED_APPS: if app in IGNORE_APP_MEDIA_DIRS: continue for name in (u'static', u'media'): app_root = os.path.dirname(import_module(app).__file__) media_dirs.append(os.path.join(app_root, name)) _media_dirs_cache.extend(media_dirs) return _media_dirs_cache def find_file(name, media_dirs=None): if media_dirs is None: media_dirs = get_media_dirs() for root in media_dirs: path = os.path.normpath(os.path.join(root, name)) if os.path.isfile(path): return path def read_text_file(path): fp = open(path, 'r') output = fp.read() fp.close() return output.decode('utf8') def load_backend(backend): if backend not in _backends_cache: module_name, func_name = backend.rsplit('.', 1) _backends_cache[backend] = _load_backend(backend) return _backends_cache[backend] def _load_backend(path): module_name, attr_name = path.rsplit('.', 1) try: mod = import_module(module_name) except (ImportError, ValueError), e: raise ImproperlyConfigured('Error importing backend module %s: "%s"' % (module_name, e)) try: return getattr(mod, attr_name) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" backend' % (module_name, attr_name))
adieu/django-mediagenerator
ef4ea23cf7764d04b82218fd6f768e87bf529b9e
fixed lots of unicode issues
diff --git a/mediagenerator/filters/closure.py b/mediagenerator/filters/closure.py index 6069543..c06ac09 100644 --- a/mediagenerator/filters/closure.py +++ b/mediagenerator/filters/closure.py @@ -1,36 +1,36 @@ from django.conf import settings from django.utils.encoding import smart_str from mediagenerator.generators.bundles.base import Filter COMPILATION_LEVEL = getattr(settings, 'CLOSURE_COMPILATION_LEVEL', 'SIMPLE_OPTIMIZATIONS') class Closure(Filter): def __init__(self, **kwargs): self.config(kwargs, compilation_level=COMPILATION_LEVEL) super(Closure, self).__init__(**kwargs) assert self.filetype == 'js', ( 'Closure only supports compilation to js. ' 'The parent filter expects "%s".' % self.filetype) def get_output(self, variation): # We import this here, so App Engine Helper users don't get import # errors. from subprocess import Popen, PIPE for input in self.get_input(variation): try: compressor = settings.CLOSURE_COMPILER_PATH cmd = Popen(['java', '-jar', compressor, '--charset', 'utf-8', '--compilation_level', self.compilation_level], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) output, error = cmd.communicate(smart_str(input)) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error - yield output + yield output.decode('utf-8') except Exception, e: raise ValueError("Failed to execute Java VM or Closure. " "Please make sure that you have installed Java " "and that it's in your PATH and that you've configured " "CLOSURE_COMPILER_PATH in your settings correctly.\n" "Error was: %s" % e) diff --git a/mediagenerator/filters/coffeescript.py b/mediagenerator/filters/coffeescript.py index b562535..424be4e 100644 --- a/mediagenerator/filters/coffeescript.py +++ b/mediagenerator/filters/coffeescript.py @@ -1,66 +1,64 @@ from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter -from mediagenerator.utils import find_file +from mediagenerator.utils import find_file, read_text_file from subprocess import Popen, PIPE import os import sys class CoffeeScript(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, module=None) super(CoffeeScript, self).__init__(**kwargs) assert self.filetype == 'js', ( 'CoffeeScript only supports compilation to js. ' 'The parent filter expects "%s".' % self.filetype) self._compiled = None self._compiled_hash = None self._mtime = None @classmethod def from_default(cls, name): return {'module': name} def get_output(self, variation): self._regenerate(debug=False) yield self._compiled def get_dev_output(self, name, variation): assert name == self.module self._regenerate(debug=True) return self._compiled def get_dev_output_names(self, variation): self._regenerate(debug=True) yield self.module, self._compiled_hash def _regenerate(self, debug=False): path = find_file(self.module) mtime = os.path.getmtime(path) if mtime == self._mtime: return - fp = open(path, 'r') - source = fp.read() - fp.close() + source = read_text_file(path) self._compiled = self._compile(source, debug=debug) self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() self._mtime = mtime def _compile(self, input, debug=False): try: shell = sys.platform == 'win32' cmd = Popen(['coffee', '--compile', '--print', '--stdio', '--bare'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=shell, universal_newlines=True) - output, error = cmd.communicate(input) + output, error = cmd.communicate(smart_str(input)) assert cmd.wait() == 0, ('CoffeeScript command returned bad ' 'result:\n%s' % error) - return output + return output.decode('utf-8') except Exception, e: raise ValueError("Failed to run CoffeeScript compiler for this " "file. Please confirm that the \"coffee\" application is " "on your path and that you can run it from your own command " "line.\n" "Error was: %s" % e) diff --git a/mediagenerator/filters/sass.py b/mediagenerator/filters/sass.py index 5df6fd7..4f15d43 100644 --- a/mediagenerator/filters/sass.py +++ b/mediagenerator/filters/sass.py @@ -1,152 +1,153 @@ from django.conf import settings from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, find_file, read_text_file from subprocess import Popen, PIPE import os import posixpath import re import sys # Emits extra debug info that can be used by the FireSass Firebug plugin SASS_DEBUG_INFO = getattr(settings, 'SASS_DEBUG_INFO', False) SASS_FRAMEWORKS = getattr(settings, 'SASS_FRAMEWORKS', ('compass', 'blueprint')) if isinstance(SASS_FRAMEWORKS, basestring): SASS_FRAMEWORKS = (SASS_FRAMEWORKS,) _RE_FLAGS = re.MULTILINE | re.UNICODE multi_line_comment_re = re.compile(r'/\*.*?\*/', _RE_FLAGS | re.DOTALL) one_line_comment_re = re.compile(r'//.*', _RE_FLAGS) import_re = re.compile(r'^@import\s+["\']?(.+?)["\']?\s*;?\s*$', _RE_FLAGS) class Sass(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, path=(), main_module=None) if isinstance(self.path, basestring): self.path = (self.path,) super(Sass, self).__init__(**kwargs) assert self.filetype == 'css', ( 'Sass only supports compilation to css. ' 'The parent filter expects "%s".' % self.filetype) assert self.main_module, \ 'You must provide a main module' self.path += tuple(get_media_dirs()) self.path_args = [] for path in self.path: self.path_args.extend(('-I', path.replace('\\', '/'))) self._compiled = None self._compiled_hash = None self._dependencies = {} @classmethod def from_default(cls, name): return {'main_module': name} def get_output(self, variation): self._regenerate(debug=False) yield self._compiled def get_dev_output(self, name, variation): assert name == self.main_module self._regenerate(debug=True) return self._compiled def get_dev_output_names(self, variation): self._regenerate(debug=True) yield self.main_module, self._compiled_hash def _compile(self, debug=False): extensions = os.path.join(os.path.dirname(__file__), 'sass_compass.rb') extensions = extensions.replace('\\', '/') - run = ['sass', '-C', '-t', 'expanded', '--require', extensions] + run = ['sass', '-E', 'utf-8', '-C', '-t', 'expanded', + '--require', extensions] for framework in SASS_FRAMEWORKS: # Some frameworks are loaded by default if framework in ('blueprint', 'compass'): continue run.extend(('--require', framework)) if debug: run.append('--line-numbers') if SASS_DEBUG_INFO: run.append('--debug-info') run.extend(self.path_args) shell = sys.platform == 'win32' try: cmd = Popen(run, shell=shell, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) module = self.main_module.rsplit('.', 1)[0] output, error = cmd.communicate('@import "%s"' % module) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error - return output + return output.decode('utf-8') except Exception, e: raise ValueError("Failed to execute Sass. Please make sure that " "you have installed Sass (http://sass-lang.com) and " "Compass (http://compass-style.org).\n" "Error was: %s" % e) def _regenerate(self, debug=False): if self._dependencies: for name, mtime in self._dependencies.items(): path = self._find_file(name) if not path or os.path.getmtime(path) != mtime: # Just recompile everything self._dependencies = {} break else: # No changes return modules = [self.main_module] while True: if not modules: break module_name = modules.pop() path = self._find_file(module_name) assert path, 'Could not find the Sass module %s' % module_name mtime = os.path.getmtime(path) self._dependencies[module_name] = mtime source = read_text_file(path) dependencies = self._get_dependencies(source) for name in dependencies: # Try relative import, first transformed = posixpath.join(posixpath.dirname(module_name), name) path = self._find_file(transformed) if path: name = transformed else: path = self._find_file(name) assert path, ('The Sass module %s could not find the ' 'dependency %s' % (module_name, name)) if name not in self._dependencies: modules.append(name) self._compiled = self._compile(debug=debug) self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() def _get_dependencies(self, source): clean_source = multi_line_comment_re.sub('\n', source) clean_source = one_line_comment_re.sub('', clean_source) return [name for name in import_re.findall(clean_source) if not name.endswith('.css')] def _find_file(self, name): parts = name.rsplit('/', 1) parts[-1] = '_' + parts[-1] partial = '/'.join(parts) if not name.endswith(('.sass', '.scss')): names = (name + '.sass', name + '.scss', partial + '.sass', partial + '.scss') else: names = (name, partial) for name in names: path = find_file(name, media_dirs=self.path) if path: return path diff --git a/mediagenerator/filters/yuicompressor.py b/mediagenerator/filters/yuicompressor.py index bdb5f22..09ddc79 100644 --- a/mediagenerator/filters/yuicompressor.py +++ b/mediagenerator/filters/yuicompressor.py @@ -1,31 +1,31 @@ from django.conf import settings from django.utils.encoding import smart_str from mediagenerator.generators.bundles.base import Filter class YUICompressor(Filter): def __init__(self, **kwargs): super(YUICompressor, self).__init__(**kwargs) assert self.filetype in ('css', 'js'), ( 'YUICompressor only supports compilation to css and js. ' 'The parent filter expects "%s".' % self.filetype) def get_output(self, variation): # We import this here, so App Engine Helper users don't get import # errors. from subprocess import Popen, PIPE for input in self.get_input(variation): try: compressor = settings.YUICOMPRESSOR_PATH cmd = Popen(['java', '-jar', compressor, '--charset', 'utf-8', '--type', self.filetype], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) output, error = cmd.communicate(smart_str(input)) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error - yield output + yield output.decode('utf-8') except Exception, e: raise ValueError("Failed to execute Java VM or yuicompressor. " "Please make sure that you have installed Java " "and that it's in your PATH and that you've configured " "YUICOMPRESSOR_PATH in your settings correctly.\n" "Error was: %s" % e) diff --git a/mediagenerator/settings.py b/mediagenerator/settings.py index 04043ae..d6ffb55 100644 --- a/mediagenerator/settings.py +++ b/mediagenerator/settings.py @@ -1,35 +1,38 @@ from django.conf import settings +from django.utils.encoding import force_unicode import os import __main__ _map_file_path = '_generated_media_names.py' _media_dir = '_generated_media' # __main__ is not guaranteed to have the __file__ attribute if hasattr(__main__, '__file__'): _root = os.path.dirname(__main__.__file__) _map_file_path = os.path.join(_root, _map_file_path) _media_dir = os.path.join(_root, _media_dir) GENERATED_MEDIA_DIR = os.path.abspath( getattr(settings, 'GENERATED_MEDIA_DIR', _media_dir)) GENERATED_MEDIA_NAMES_MODULE = getattr(settings, 'GENERATED_MEDIA_NAMES_MODULE', '_generated_media_names') GENERATED_MEDIA_NAMES_FILE = os.path.abspath( getattr(settings, 'GENERATED_MEDIA_NAMES_FILE', _map_file_path)) DEV_MEDIA_URL = getattr(settings, 'DEV_MEDIA_URL', getattr(settings, 'STATIC_URL', settings.MEDIA_URL)) PRODUCTION_MEDIA_URL = getattr(settings, 'PRODUCTION_MEDIA_URL', DEV_MEDIA_URL) MEDIA_GENERATORS = getattr(settings, 'MEDIA_GENERATORS', ( 'mediagenerator.generators.copyfiles.CopyFiles', 'mediagenerator.generators.bundles.Bundles', 'mediagenerator.generators.manifest.Manifest', )) -GLOBAL_MEDIA_DIRS = getattr(settings, 'GLOBAL_MEDIA_DIRS', - getattr(settings, 'STATICFILES_DIRS', ())) +_global_media_dirs = getattr(settings, 'GLOBAL_MEDIA_DIRS', + getattr(settings, 'STATICFILES_DIRS', ())) +GLOBAL_MEDIA_DIRS = [os.path.normcase(os.path.normpath(force_unicode(path))) + for path in _global_media_dirs] IGNORE_APP_MEDIA_DIRS = getattr(settings, 'IGNORE_APP_MEDIA_DIRS', ('django.contrib.admin',)) MEDIA_DEV_MODE = getattr(settings, 'MEDIA_DEV_MODE', settings.DEBUG) diff --git a/mediagenerator/utils.py b/mediagenerator/utils.py index 0d1d474..b319cd4 100644 --- a/mediagenerator/utils.py +++ b/mediagenerator/utils.py @@ -1,146 +1,146 @@ from . import settings as media_settings from .settings import (GLOBAL_MEDIA_DIRS, PRODUCTION_MEDIA_URL, IGNORE_APP_MEDIA_DIRS, MEDIA_GENERATORS, DEV_MEDIA_URL, GENERATED_MEDIA_NAMES_MODULE) from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.importlib import import_module from django.utils.http import urlquote import os import re try: NAMES = import_module(GENERATED_MEDIA_NAMES_MODULE).NAMES except (ImportError, AttributeError): NAMES = None _backends_cache = {} _media_dirs_cache = [] _generators_cache = [] _generated_names = {} _backend_mapping = {} def _load_generators(): if not _generators_cache: for name in MEDIA_GENERATORS: backend = load_backend(name)() _generators_cache.append(backend) return _generators_cache def _refresh_dev_names(): _generated_names.clear() _backend_mapping.clear() for backend in _load_generators(): for key, url, hash in backend.get_dev_output_names(): versioned_url = urlquote(url) if hash: versioned_url += '?version=' + hash _generated_names.setdefault(key, []) _generated_names[key].append(versioned_url) _backend_mapping[url] = backend class _MatchNothing(object): def match(self, content): return False def prepare_patterns(patterns, setting_name): """Helper function for patter-matching settings.""" if isinstance(patterns, basestring): patterns = (patterns,) if not patterns: return _MatchNothing() # First validate each pattern individually for pattern in patterns: try: re.compile(pattern, re.U) except re.error: raise ValueError("""Pattern "%s" can't be compiled """ "in %s" % (pattern, setting_name)) # Now return a combined pattern return re.compile('^(' + ')$|^('.join(patterns) + ')$', re.U) def get_production_mapping(): if NAMES is None: raise ImportError('Could not import %s. This ' 'file is needed for production mode. Please ' 'run manage.py generatemedia to create it.' % GENERATED_MEDIA_NAMES_MODULE) return NAMES def get_media_mapping(): if media_settings.MEDIA_DEV_MODE: return _generated_names return get_production_mapping() def get_media_url_mapping(): if media_settings.MEDIA_DEV_MODE: base_url = DEV_MEDIA_URL else: base_url = PRODUCTION_MEDIA_URL mapping = {} for key, value in get_media_mapping().items(): if isinstance(value, basestring): value = (value,) mapping[key] = [base_url + url for url in value] return mapping def media_urls(key, refresh=False): if media_settings.MEDIA_DEV_MODE: if refresh: _refresh_dev_names() return [DEV_MEDIA_URL + url for url in _generated_names[key]] + print repr(get_production_mapping()) return [PRODUCTION_MEDIA_URL + get_production_mapping()[key]] def media_url(key, refresh=False): urls = media_urls(key, refresh=refresh) if len(urls) == 1: return urls[0] raise ValueError('media_url() only works with URLs that contain exactly ' 'one file. Use media_urls() (or {% include_media %} in templates) instead.') def get_media_dirs(): if not _media_dirs_cache: - media_dirs = [os.path.normcase(os.path.normpath(root)) - for root in GLOBAL_MEDIA_DIRS] + media_dirs = GLOBAL_MEDIA_DIRS[:] for app in settings.INSTALLED_APPS: if app in IGNORE_APP_MEDIA_DIRS: continue - for name in ('static', 'media'): + for name in (u'static', u'media'): app_root = os.path.dirname(import_module(app).__file__) media_dirs.append(os.path.join(app_root, name)) _media_dirs_cache.extend(media_dirs) return _media_dirs_cache def find_file(name, media_dirs=None): if media_dirs is None: media_dirs = get_media_dirs() for root in media_dirs: path = os.path.normpath(os.path.join(root, name)) if os.path.isfile(path): return path def read_text_file(path): fp = open(path, 'r') output = fp.read() fp.close() return output.decode('utf8') def load_backend(backend): if backend not in _backends_cache: module_name, func_name = backend.rsplit('.', 1) _backends_cache[backend] = _load_backend(backend) return _backends_cache[backend] def _load_backend(path): module_name, attr_name = path.rsplit('.', 1) try: mod = import_module(module_name) except (ImportError, ValueError), e: raise ImproperlyConfigured('Error importing backend module %s: "%s"' % (module_name, e)) try: return getattr(mod, attr_name) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" backend' % (module_name, attr_name))
adieu/django-mediagenerator
22ffd169cbc36d8ab7fc4e85212f7516b7edb24a
bumped version
diff --git a/setup.py b/setup.py index 657e411..8c26c91 100644 --- a/setup.py +++ b/setup.py @@ -1,33 +1,33 @@ from setuptools import setup, find_packages DESCRIPTION = 'Asset manager for Django' LONG_DESCRIPTION = None try: LONG_DESCRIPTION = open('README.rst').read() except: pass setup(name='django-mediagenerator', - version='1.10.1', + version='1.10.2', packages=find_packages(exclude=('tests', 'tests.*', 'base_project', 'base_project.*')), package_data={'mediagenerator.filters': ['pyjslibs/*.py', '*.rb'], 'mediagenerator': ['templates/mediagenerator/manifest/*']}, author='Waldemar Kornewald', author_email='[email protected]', url='http://www.allbuttonspressed.com/projects/django-mediagenerator', description=DESCRIPTION, long_description=LONG_DESCRIPTION, platforms=['any'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Application Frameworks', 'Topic :: Software Development :: Libraries :: Python Modules', 'License :: OSI Approved :: BSD License', ], )
adieu/django-mediagenerator
226bc484fd10b022a97c17aba45d1dbf2e4cc4af
added link definition
diff --git a/.deps b/.deps new file mode 100644 index 0000000..e26bd4c --- /dev/null +++ b/.deps @@ -0,0 +1,2 @@ +[links] +mediagenerator = django-mediagenerator/mediagenerator
adieu/django-mediagenerator
76239672284b79e19ee18ca294dfde01dafc168b
added upgrade notes
diff --git a/CHANGELOG.rst b/CHANGELOG.rst index e460faa..0d6cc99 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,138 +1,145 @@ Changelog ============================================================= +Version 1.10.2 +------------------------------------------------------------- + +**Upgrade notes:** If you've specified a custom ``SASS_FRAMEWORKS`` in your ``settings.py`` you now also have to list ``compass`` and ``blueprint`` in that setting. + +* All Compass/Sass frameworks (including ``compass`` and ``blueprint``) now have to be listed explictily in the ``SASS_FRAMEWORKS`` setting. + Version 1.10.1 ------------------------------------------------------------- * Added workaround for Windows bug in Sass 3.1. Backslash characters aren't handled correctly for "-I" import path parameters. Version 1.10 ------------------------------------------------------------- * Added Compass support to Sass filter. You now have to install both Compass and Sass. Import Sass/Compass frameworks via ``manage.py importsassframeworks``. * Fixed CoffeeScript support on OSX * Fixed support for non-ascii chars in input files * Added "Content-Length" response header for files served in dev mode (needed for Flash). Thanks to "sayane" for the patch. * Fixed typo which resulted in broken support for ``.html`` assets. Thanks to "pendletongp" for the patch. * Now showing instructive error message when Sass can't be found * Use correct output path for ``_generated_media_names.py`` even when ``manage.py generatemedia`` is not started from the project root. Thanks to "pendletongp" for the patch. * Added support for overriding the ``_generated_media_names`` module's import path and file system location (only needed for non-standard project structures). Version 1.9.2 ------------------------------------------------------------- * Added missing ``base.manifest`` template and ``base_project`` to zip package Version 1.9.1 ------------------------------------------------------------- * Fixed relative imports in Sass filter Version 1.9 ------------------------------------------------------------- * Added CoffeeScript support (use ``.coffee`` extension). Contributed by Andrew Allen. * Added caching for CoffeeScript compilation results * In cache manifests the ``NETWORK`` section now contains "``*``" by default * By default ``.woff`` files are now copied, too * Fixed first-time media generation when ``MEDIA_DEV_MODE=False`` * Fixed i18n filter in development mode. Contributed by Simon Payne. * Fixed support for "/" in bundle names in dev mode (always worked fine in production) * Changed ``DEV_MEDIA_URL`` fallback from ``STATICFILES_URL`` to ``STATIC_URL`` (has been changed in Django trunk) Version 1.8 ------------------------------------------------------------- * HTML5 manifest now uses a regex to match included/excluded files * Added support for scss files * Fixed Sass ``@import`` tracking for partials Version 1.7 ------------------------------------------------------------- * Large performance improvements, in particular on App Engine dev_appserver Version 1.6.1 ------------------------------------------------------------- * Fixed support for Django 1.1 which imports ``mediagenerator.templatetags.media`` as ``django.templatetags.media`` and thus breaks relative imports Version 1.6 ------------------------------------------------------------- **Upgrade notes:** The installation got simplified. Please remove the media code from your urls.py. The ``MediaMiddleware`` now takes care of everything. * Added support for CSS data URIs. Doesn't yet generate MHTML for IE6/7 support. * Added support for pre-bundling i18n JavaScript translations, so you don't need to use Django's slower AJAX view. With this filter translations are part of your generated JS bundle. * Added support for CleverCSS * Simplified installation process. The media view got completely replaced by ``MediaMiddleware``. * Fixed support for output variations (needed by i18n filter to generate the same JS file in different variations for each language) Version 1.5.1 ------------------------------------------------------------- **Upgrade notes:** There's a conflict with ``STATICFILES_URL`` in Django trunk (1.3). Use ``DEV_MEDIA_URL`` instead from now on. * ``DEV_MEDIA_URL`` should be used instead of ``MEDIA_URL`` and ``STATICFILES_URL``, though the other two are still valid for backwards-compatibility Version 1.5 ------------------------------------------------------------- This is another staticfiles-compatibility release which is intended to allow for writing reusable open-source apps. **Upgrade notes:** The CSS URL rewriting scheme has changed. Previously, ``url()`` statements in CSS files were treated similar to "absolute" URLs where the root is ``STATICFILES_URL`` (or ``MEDIA_URL``). This scheme was used because it was consistent with URLs in Sass. Now URLs are treated as relative to the CSS file. So, if the file ``css/style.css`` wants to link to ``img/icon.png`` the URL now has to be ``url(../img/icon.png)``. Previously it was ``url(img/icon.png)``. One way to upgrade to the staticfiles-compatible scheme is to modify your existing URLs. If you don't want to change your CSS files there is an alternative, but it's not staticfiles-compatible. Add the following to your settings: ``REWRITE_CSS_URLS_RELATIVE_TO_SOURCE = False`` **Important:** Sass files still use the old scheme (``url(img/icon.png)``) because this is **much** easier to understand and allows for more reusable code, especially when you ``@import`` other Sass modules and those link to images. * Made CSS URL rewriting system compatible with ``django.contrib.staticfiles`` * Added support for CSS URLs that contain a hash (e.g.: ``url('webfont.svg#webfontmAfNlbV6')``). Thanks to Karl Bowden for the patch! * Filter backends now have an additional ``self.bundle`` attribute which contains the final bundle name * Fixed an incompatibility with Django 1.1 and 1.0 (``django.utils.itercompat.product`` isn't available in those releases) * Fixed ``MediaMiddleware``, so it doesn't cache error responses Version 1.4 ------------------------------------------------------------- This is a compatibility release which prepares for the new staticfiles feature in Django 1.3. **Upgrade notes:** Place your app media in a "static" folder instead of a "media" folder. Use ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) instead of ``MEDIA_URL`` from now on. * App media is now searched in "static" folders instead of "media". For now, you can still use "media" folders, but this might be deprecated in the future (for the sake of having just one standard for reusable apps). * ``DEV_MEDIA_URL`` (edit: was ``STATICFILES_URL``) should be used instead of ``MEDIA_URL`` because the meaning of that variable has changed in Django 1.3. * ``DEV_MEDIA_URL`` falls back to ``STATICFILES_URL`` and ``GLOBAL_MEDIA_DIRS`` falls back to ``STATICFILES_DIRS`` if undefined (you should still use the former, respectively; this is just for convenience) Version 1.3.1 ------------------------------------------------------------- * Improved handling of media variations. This also fixes a bug with using CSS media types in production mode Version 1.3 ------------------------------------------------------------- * Added support for setting media type for CSS. E.g.: ``{% include_media 'bundle.css' media='print' %}`` Version 1.2.1 ------------------------------------------------------------- * Fixed caching problems on runserver when using i18n and ``LocaleMiddleware`` Version 1.2 ------------------------------------------------------------- **Upgrade notes:** Please add ``'mediagenerator.middleware.MediaMiddleware'`` as the **first** middleware in your settings.py. * Got rid of unnecessary HTTP roundtrips when ``USE_ETAGS = True`` * Added Django template filter (by default only used for .html files), contributed by Matt Bierner * Added media_url() filter which provides access to generated URLs from JS * CopyFiles backend can now ignore files matching certain regex patterns Version 1.1 ------------------------------------------------------------- * Added Closure compiler backend * Added HTML5 cache manifest file backend * Fixed Sass support on Linux * Updated pyjs filter to latest pyjs repo version * "swf" and "ico" files are now copied, too, by default
adieu/django-mediagenerator
7c3999a0b0bbe56f51c30b20d95283ee6a3346cb
from now on all Compass frameworks have to be listed explicitly
diff --git a/mediagenerator/filters/sass.py b/mediagenerator/filters/sass.py index a6b76c3..5df6fd7 100644 --- a/mediagenerator/filters/sass.py +++ b/mediagenerator/filters/sass.py @@ -1,148 +1,152 @@ from django.conf import settings from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, find_file, read_text_file from subprocess import Popen, PIPE import os import posixpath import re import sys # Emits extra debug info that can be used by the FireSass Firebug plugin SASS_DEBUG_INFO = getattr(settings, 'SASS_DEBUG_INFO', False) -SASS_FRAMEWORKS = getattr(settings, 'SASS_FRAMEWORKS', ()) +SASS_FRAMEWORKS = getattr(settings, 'SASS_FRAMEWORKS', + ('compass', 'blueprint')) if isinstance(SASS_FRAMEWORKS, basestring): SASS_FRAMEWORKS = (SASS_FRAMEWORKS,) _RE_FLAGS = re.MULTILINE | re.UNICODE multi_line_comment_re = re.compile(r'/\*.*?\*/', _RE_FLAGS | re.DOTALL) one_line_comment_re = re.compile(r'//.*', _RE_FLAGS) import_re = re.compile(r'^@import\s+["\']?(.+?)["\']?\s*;?\s*$', _RE_FLAGS) class Sass(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, path=(), main_module=None) if isinstance(self.path, basestring): self.path = (self.path,) super(Sass, self).__init__(**kwargs) assert self.filetype == 'css', ( 'Sass only supports compilation to css. ' 'The parent filter expects "%s".' % self.filetype) assert self.main_module, \ 'You must provide a main module' self.path += tuple(get_media_dirs()) self.path_args = [] for path in self.path: self.path_args.extend(('-I', path.replace('\\', '/'))) self._compiled = None self._compiled_hash = None self._dependencies = {} @classmethod def from_default(cls, name): return {'main_module': name} def get_output(self, variation): self._regenerate(debug=False) yield self._compiled def get_dev_output(self, name, variation): assert name == self.main_module self._regenerate(debug=True) return self._compiled def get_dev_output_names(self, variation): self._regenerate(debug=True) yield self.main_module, self._compiled_hash def _compile(self, debug=False): extensions = os.path.join(os.path.dirname(__file__), 'sass_compass.rb') extensions = extensions.replace('\\', '/') run = ['sass', '-C', '-t', 'expanded', '--require', extensions] for framework in SASS_FRAMEWORKS: + # Some frameworks are loaded by default + if framework in ('blueprint', 'compass'): + continue run.extend(('--require', framework)) if debug: run.append('--line-numbers') if SASS_DEBUG_INFO: run.append('--debug-info') run.extend(self.path_args) shell = sys.platform == 'win32' try: cmd = Popen(run, shell=shell, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) module = self.main_module.rsplit('.', 1)[0] output, error = cmd.communicate('@import "%s"' % module) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error return output except Exception, e: raise ValueError("Failed to execute Sass. Please make sure that " "you have installed Sass (http://sass-lang.com) and " "Compass (http://compass-style.org).\n" "Error was: %s" % e) def _regenerate(self, debug=False): if self._dependencies: for name, mtime in self._dependencies.items(): path = self._find_file(name) if not path or os.path.getmtime(path) != mtime: # Just recompile everything self._dependencies = {} break else: # No changes return modules = [self.main_module] while True: if not modules: break module_name = modules.pop() path = self._find_file(module_name) assert path, 'Could not find the Sass module %s' % module_name mtime = os.path.getmtime(path) self._dependencies[module_name] = mtime source = read_text_file(path) dependencies = self._get_dependencies(source) for name in dependencies: # Try relative import, first transformed = posixpath.join(posixpath.dirname(module_name), name) path = self._find_file(transformed) if path: name = transformed else: path = self._find_file(name) assert path, ('The Sass module %s could not find the ' 'dependency %s' % (module_name, name)) if name not in self._dependencies: modules.append(name) self._compiled = self._compile(debug=debug) self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() def _get_dependencies(self, source): clean_source = multi_line_comment_re.sub('\n', source) clean_source = one_line_comment_re.sub('', clean_source) return [name for name in import_re.findall(clean_source) if not name.endswith('.css')] def _find_file(self, name): parts = name.rsplit('/', 1) parts[-1] = '_' + parts[-1] partial = '/'.join(parts) if not name.endswith(('.sass', '.scss')): names = (name + '.sass', name + '.scss', partial + '.sass', partial + '.scss') else: names = (name, partial) for name in names: path = find_file(name, media_dirs=self.path) if path: return path diff --git a/mediagenerator/filters/sass_paths.rb b/mediagenerator/filters/sass_paths.rb index 6278798..e2a9ad6 100644 --- a/mediagenerator/filters/sass_paths.rb +++ b/mediagenerator/filters/sass_paths.rb @@ -1,12 +1,17 @@ require "rubygems" require "sass" require "compass" +DEFAULT_FRAMEWORKS = ["compass", "blueprint"] + ARGV.each do |arg| + next if arg == "compass" + next if arg == "blueprint" require arg end Compass::Frameworks::ALL.each do |framework| next if framework.name =~ /^_/ + next if DEFAULT_FRAMEWORKS.include?(framework.name) && !ARGV.include?(framework.name) print "#{File.expand_path(framework.stylesheets_directory)}\n" end
adieu/django-mediagenerator
6b046c6b980a37d02246389a91bec41b6efab7da
added support for specifying path of imported-sass-frameworks folder
diff --git a/mediagenerator/management/commands/importsassframeworks.py b/mediagenerator/management/commands/importsassframeworks.py index 3087ff8..c226173 100644 --- a/mediagenerator/management/commands/importsassframeworks.py +++ b/mediagenerator/management/commands/importsassframeworks.py @@ -1,70 +1,73 @@ from ...filters import sass from ...utils import get_media_dirs +from django.conf import settings from django.core.management.base import NoArgsCommand from subprocess import Popen, PIPE import os import shutil import sys import __main__ _frameworks_dir = 'imported-sass-frameworks' if hasattr(__main__, '__file__'): _root = os.path.dirname(__main__.__file__) _frameworks_dir = os.path.join(_root, _frameworks_dir) -FRAMEWORKS_DIR = os.path.normcase(os.path.abspath(_frameworks_dir)) +FRAMEWORKS_DIR = getattr(settings, 'IMPORTED_SASS_FRAMEWORKS_DIR', + _frameworks_dir) +FRAMEWORKS_DIR = os.path.normcase(os.path.abspath(FRAMEWORKS_DIR)) PATHS_SCRIPT = os.path.join(os.path.dirname(sass.__file__), 'sass_paths.rb') def copy_children(src, dst): for item in os.listdir(src): path = os.path.join(src, item) copy_fs_node(path, dst) def copy_fs_node(src, dst): basename = os.path.basename(src) dst = os.path.join(dst, basename) if os.path.isfile(src): shutil.copy(src, dst) elif os.path.isdir(src): shutil.copytree(src, dst) else: raise ValueError("Don't know how to copy file system node: %s" % src) class Command(NoArgsCommand): help = 'Copies Sass/Compass frameworks into the current project.' requires_model_validation = False def handle_noargs(self, **options): if os.path.exists(FRAMEWORKS_DIR): shutil.rmtree(FRAMEWORKS_DIR) os.mkdir(FRAMEWORKS_DIR) for path in self.get_framework_paths(): copy_children(path, FRAMEWORKS_DIR) if FRAMEWORKS_DIR not in get_media_dirs(): sys.stderr.write('Please add the "%(dir)s" ' 'folder to your GLOBAL_MEDIA_DIRS setting ' 'like this:\n\n' 'GLOBAL_MEDIA_DIRS = (\n' ' ...\n' " os.path.join(os.path.dirname(__file__),\n" " '%(dir)s'),\n" " ...\n" ")\n" % {'dir': os.path.basename(FRAMEWORKS_DIR)}) def get_framework_paths(self): run = ['ruby', PATHS_SCRIPT] run.extend(sass.SASS_FRAMEWORKS) try: cmd = Popen(run, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) output, error = cmd.communicate() assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error return map(os.path.abspath, filter(None, output.split('\n'))) except Exception, e: raise ValueError("Failed to execute an internal Ruby script. " "Please make sure that you have installed Ruby " "(http://ruby-lang.org), Sass (http://sass-lang.com), and " "Compass (http://compass-style.org).\n" "Error was: %s" % e)
adieu/django-mediagenerator
1e0dd8d257573b6986188ef7439ca758131e3845
changed line ending
diff --git a/.hgeol b/.hgeol index bad5a49..d5332c3 100644 --- a/.hgeol +++ b/.hgeol @@ -1,16 +1,19 @@ [patterns] +.deps = native +.hgignore = native +.hgeol = native **.txt = native **.pyva = native **.py = native -**.rb = native +**.ru = native **.c = native **.cpp = native **.cu = native **.h = native **.hpp = native **.tmpl = native **.html = native **.htm = native **.js = native **.manifest = native **.yaml = native diff --git a/mediagenerator/filters/sass_compass.rb b/mediagenerator/filters/sass_compass.rb index d22534b..23049b6 100644 --- a/mediagenerator/filters/sass_compass.rb +++ b/mediagenerator/filters/sass_compass.rb @@ -1,66 +1,66 @@ -require "rubygems" -require "compass" - -module Compass::SassExtensions::Functions::Urls - - def stylesheet_url(path, only_path = Sass::Script::Bool.new(false)) - if only_path.to_bool - Sass::Script::String.new(clean_path(path)) - else - clean_url(path) - end - end - - def font_url(path, only_path = Sass::Script::Bool.new(false)) - path = path.value # get to the string value of the literal. - - # Short curcuit if they have provided an absolute url. - if absolute_path?(path) - return Sass::Script::String.new("url(#{path})") - end - - if only_path.to_bool - Sass::Script::String.new(clean_path(path)) - else - clean_url(path) - end - end - - def image_url(path, only_path = Sass::Script::Bool.new(false)) - print "#{@options}\n" - path = path.value # get to the string value of the literal. - - if absolute_path?(path) - # Short curcuit if they have provided an absolute url. - return Sass::Script::String.new("url(#{path})") - end - - if only_path.to_bool - Sass::Script::String.new(clean_path(path)) - else - clean_url(path) - end - end - - private - - # Emits a path, taking off any leading "./" - def clean_path(url) - url = url.to_s - url = url[0..1] == "./" ? url[2..-1] : url - end - - # Emits a url, taking off any leading "./" - def clean_url(url) - Sass::Script::String.new("url('#{clean_path(url)}')") - end - - def absolute_path?(path) - path[0..0] == "/" || path[0..3] == "http" - end - -end - -module Sass::Script::Functions - include Compass::SassExtensions::Functions::Urls -end +require "rubygems" +require "compass" + +module Compass::SassExtensions::Functions::Urls + + def stylesheet_url(path, only_path = Sass::Script::Bool.new(false)) + if only_path.to_bool + Sass::Script::String.new(clean_path(path)) + else + clean_url(path) + end + end + + def font_url(path, only_path = Sass::Script::Bool.new(false)) + path = path.value # get to the string value of the literal. + + # Short curcuit if they have provided an absolute url. + if absolute_path?(path) + return Sass::Script::String.new("url(#{path})") + end + + if only_path.to_bool + Sass::Script::String.new(clean_path(path)) + else + clean_url(path) + end + end + + def image_url(path, only_path = Sass::Script::Bool.new(false)) + print "#{@options}\n" + path = path.value # get to the string value of the literal. + + if absolute_path?(path) + # Short curcuit if they have provided an absolute url. + return Sass::Script::String.new("url(#{path})") + end + + if only_path.to_bool + Sass::Script::String.new(clean_path(path)) + else + clean_url(path) + end + end + + private + + # Emits a path, taking off any leading "./" + def clean_path(url) + url = url.to_s + url = url[0..1] == "./" ? url[2..-1] : url + end + + # Emits a url, taking off any leading "./" + def clean_url(url) + Sass::Script::String.new("url('#{clean_path(url)}')") + end + + def absolute_path?(path) + path[0..0] == "/" || path[0..3] == "http" + end + +end + +module Sass::Script::Functions + include Compass::SassExtensions::Functions::Urls +end diff --git a/mediagenerator/filters/sass_paths.rb b/mediagenerator/filters/sass_paths.rb index 39900e9..6278798 100644 --- a/mediagenerator/filters/sass_paths.rb +++ b/mediagenerator/filters/sass_paths.rb @@ -1,12 +1,12 @@ -require "rubygems" -require "sass" -require "compass" - -ARGV.each do |arg| - require arg -end - -Compass::Frameworks::ALL.each do |framework| - next if framework.name =~ /^_/ - print "#{File.expand_path(framework.stylesheets_directory)}\n" -end +require "rubygems" +require "sass" +require "compass" + +ARGV.each do |arg| + require arg +end + +Compass::Frameworks::ALL.each do |framework| + next if framework.name =~ /^_/ + print "#{File.expand_path(framework.stylesheets_directory)}\n" +end
adieu/django-mediagenerator
7c347ae0229baf45db57e7df9ba25183915bad82
Fixed unicode support for Closure. Patch contributed by Andrew Shearer. Thanks!
diff --git a/mediagenerator/filters/closure.py b/mediagenerator/filters/closure.py index 2f61864..6069543 100644 --- a/mediagenerator/filters/closure.py +++ b/mediagenerator/filters/closure.py @@ -1,35 +1,36 @@ from django.conf import settings +from django.utils.encoding import smart_str from mediagenerator.generators.bundles.base import Filter COMPILATION_LEVEL = getattr(settings, 'CLOSURE_COMPILATION_LEVEL', 'SIMPLE_OPTIMIZATIONS') class Closure(Filter): def __init__(self, **kwargs): self.config(kwargs, compilation_level=COMPILATION_LEVEL) super(Closure, self).__init__(**kwargs) assert self.filetype == 'js', ( 'Closure only supports compilation to js. ' 'The parent filter expects "%s".' % self.filetype) def get_output(self, variation): # We import this here, so App Engine Helper users don't get import # errors. from subprocess import Popen, PIPE for input in self.get_input(variation): try: compressor = settings.CLOSURE_COMPILER_PATH cmd = Popen(['java', '-jar', compressor, '--charset', 'utf-8', '--compilation_level', self.compilation_level], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) - output, error = cmd.communicate(input) + output, error = cmd.communicate(smart_str(input)) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error yield output except Exception, e: raise ValueError("Failed to execute Java VM or Closure. " "Please make sure that you have installed Java " "and that it's in your PATH and that you've configured " "CLOSURE_COMPILER_PATH in your settings correctly.\n" "Error was: %s" % e)
adieu/django-mediagenerator
fb88d17a923c00d792f44122f53bf4df3022e67d
unicode fix in yuicompressor
diff --git a/mediagenerator/filters/yuicompressor.py b/mediagenerator/filters/yuicompressor.py index 47f035d..bdb5f22 100644 --- a/mediagenerator/filters/yuicompressor.py +++ b/mediagenerator/filters/yuicompressor.py @@ -1,30 +1,31 @@ from django.conf import settings +from django.utils.encoding import smart_str from mediagenerator.generators.bundles.base import Filter class YUICompressor(Filter): def __init__(self, **kwargs): super(YUICompressor, self).__init__(**kwargs) assert self.filetype in ('css', 'js'), ( 'YUICompressor only supports compilation to css and js. ' 'The parent filter expects "%s".' % self.filetype) def get_output(self, variation): # We import this here, so App Engine Helper users don't get import # errors. from subprocess import Popen, PIPE for input in self.get_input(variation): try: compressor = settings.YUICOMPRESSOR_PATH cmd = Popen(['java', '-jar', compressor, '--charset', 'utf-8', '--type', self.filetype], stdin=PIPE, stdout=PIPE, stderr=PIPE, universal_newlines=True) - output, error = cmd.communicate(input) + output, error = cmd.communicate(smart_str(input)) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error yield output except Exception, e: raise ValueError("Failed to execute Java VM or yuicompressor. " "Please make sure that you have installed Java " "and that it's in your PATH and that you've configured " "YUICOMPRESSOR_PATH in your settings correctly.\n" "Error was: %s" % e)
adieu/django-mediagenerator
b9795bb75eafe26e252bec42442d3c31c283f35c
fixed line endings
diff --git a/.hgeol b/.hgeol index b2d9e3b..bad5a49 100644 --- a/.hgeol +++ b/.hgeol @@ -1,15 +1,16 @@ [patterns] **.txt = native **.pyva = native **.py = native +**.rb = native **.c = native **.cpp = native **.cu = native **.h = native **.hpp = native **.tmpl = native **.html = native **.htm = native **.js = native **.manifest = native **.yaml = native diff --git a/base_project/settings.py b/base_project/settings.py index 162764f..45ab554 100644 --- a/base_project/settings.py +++ b/base_project/settings.py @@ -1,77 +1,75 @@ # -*- coding: utf-8 -*- import os DEBUG = True TEMPLATE_DEBUG = DEBUG MEDIA_BUNDLES = ( ('main.css', 'css/reset.css', 'css/style.css', 'css/icons/icon.css', ), ) # Get project root folder _project_root = os.path.dirname(__file__) # Set global media search paths GLOBAL_MEDIA_DIRS = ( os.path.join(_project_root, 'static'), ) # Set media URL (important: don't forget the trailing slash!). # PRODUCTION_MEDIA_URL is used when running manage.py generatemedia MEDIA_DEV_MODE = DEBUG DEV_MEDIA_URL = '/devmedia/' PRODUCTION_MEDIA_URL = '/media/' # Configure yuicompressor if available YUICOMPRESSOR_PATH = os.path.join( os.path.dirname(_project_root), 'yuicompressor.jar') if os.path.exists(YUICOMPRESSOR_PATH): ROOT_MEDIA_FILTERS = { 'js': 'mediagenerator.filters.yuicompressor.YUICompressor', 'css': 'mediagenerator.filters.yuicompressor.YUICompressor', } ADMIN_MEDIA_PREFIX = '/media/admin/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'sqlite.db', } } SECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi' SITE_ID = 1 INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', 'django.contrib.sites', 'mediagenerator', ) MIDDLEWARE_CLASSES = ( 'mediagenerator.middleware.MediaMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) TEMPLATE_CONTEXT_PROCESSORS = ( 'django.core.context_processors.auth', 'django.core.context_processors.request', ) USE_I18N = False -MEDIA_ROOT = os.path.join(_project_root, 'media') - TEMPLATE_DIRS = (os.path.join(_project_root, 'templates'),) ROOT_URLCONF = 'urls' diff --git a/mediagenerator/filters/sass.py b/mediagenerator/filters/sass.py index 1854ae9..a6b76c3 100644 --- a/mediagenerator/filters/sass.py +++ b/mediagenerator/filters/sass.py @@ -1,146 +1,148 @@ from django.conf import settings from django.utils.encoding import smart_str from hashlib import sha1 from mediagenerator.generators.bundles.base import Filter from mediagenerator.utils import get_media_dirs, find_file, read_text_file from subprocess import Popen, PIPE import os import posixpath import re import sys # Emits extra debug info that can be used by the FireSass Firebug plugin SASS_DEBUG_INFO = getattr(settings, 'SASS_DEBUG_INFO', False) SASS_FRAMEWORKS = getattr(settings, 'SASS_FRAMEWORKS', ()) +if isinstance(SASS_FRAMEWORKS, basestring): + SASS_FRAMEWORKS = (SASS_FRAMEWORKS,) _RE_FLAGS = re.MULTILINE | re.UNICODE multi_line_comment_re = re.compile(r'/\*.*?\*/', _RE_FLAGS | re.DOTALL) one_line_comment_re = re.compile(r'//.*', _RE_FLAGS) import_re = re.compile(r'^@import\s+["\']?(.+?)["\']?\s*;?\s*$', _RE_FLAGS) class Sass(Filter): takes_input = False def __init__(self, **kwargs): self.config(kwargs, path=(), main_module=None) if isinstance(self.path, basestring): self.path = (self.path,) super(Sass, self).__init__(**kwargs) assert self.filetype == 'css', ( 'Sass only supports compilation to css. ' 'The parent filter expects "%s".' % self.filetype) assert self.main_module, \ 'You must provide a main module' self.path += tuple(get_media_dirs()) self.path_args = [] for path in self.path: self.path_args.extend(('-I', path.replace('\\', '/'))) self._compiled = None self._compiled_hash = None self._dependencies = {} @classmethod def from_default(cls, name): return {'main_module': name} def get_output(self, variation): self._regenerate(debug=False) yield self._compiled def get_dev_output(self, name, variation): assert name == self.main_module self._regenerate(debug=True) return self._compiled def get_dev_output_names(self, variation): self._regenerate(debug=True) yield self.main_module, self._compiled_hash def _compile(self, debug=False): extensions = os.path.join(os.path.dirname(__file__), 'sass_compass.rb') extensions = extensions.replace('\\', '/') run = ['sass', '-C', '-t', 'expanded', '--require', extensions] for framework in SASS_FRAMEWORKS: run.extend(('--require', framework)) if debug: run.append('--line-numbers') if SASS_DEBUG_INFO: run.append('--debug-info') run.extend(self.path_args) shell = sys.platform == 'win32' try: cmd = Popen(run, shell=shell, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) module = self.main_module.rsplit('.', 1)[0] output, error = cmd.communicate('@import "%s"' % module) assert cmd.wait() == 0, 'Command returned bad result:\n%s' % error return output except Exception, e: raise ValueError("Failed to execute Sass. Please make sure that " "you have installed Sass (http://sass-lang.com) and " "Compass (http://compass-style.org).\n" "Error was: %s" % e) def _regenerate(self, debug=False): if self._dependencies: for name, mtime in self._dependencies.items(): path = self._find_file(name) if not path or os.path.getmtime(path) != mtime: # Just recompile everything self._dependencies = {} break else: # No changes return modules = [self.main_module] while True: if not modules: break module_name = modules.pop() path = self._find_file(module_name) assert path, 'Could not find the Sass module %s' % module_name mtime = os.path.getmtime(path) self._dependencies[module_name] = mtime source = read_text_file(path) dependencies = self._get_dependencies(source) for name in dependencies: # Try relative import, first transformed = posixpath.join(posixpath.dirname(module_name), name) path = self._find_file(transformed) if path: name = transformed else: path = self._find_file(name) assert path, ('The Sass module %s could not find the ' 'dependency %s' % (module_name, name)) if name not in self._dependencies: modules.append(name) self._compiled = self._compile(debug=debug) self._compiled_hash = sha1(smart_str(self._compiled)).hexdigest() def _get_dependencies(self, source): clean_source = multi_line_comment_re.sub('\n', source) clean_source = one_line_comment_re.sub('', clean_source) return [name for name in import_re.findall(clean_source) if not name.endswith('.css')] def _find_file(self, name): parts = name.rsplit('/', 1) parts[-1] = '_' + parts[-1] partial = '/'.join(parts) if not name.endswith(('.sass', '.scss')): names = (name + '.sass', name + '.scss', partial + '.sass', partial + '.scss') else: names = (name, partial) for name in names: path = find_file(name, media_dirs=self.path) if path: return path diff --git a/mediagenerator/filters/sass_compass.rb b/mediagenerator/filters/sass_compass.rb index 23049b6..d22534b 100644 --- a/mediagenerator/filters/sass_compass.rb +++ b/mediagenerator/filters/sass_compass.rb @@ -1,66 +1,66 @@ -require "rubygems" -require "compass" - -module Compass::SassExtensions::Functions::Urls - - def stylesheet_url(path, only_path = Sass::Script::Bool.new(false)) - if only_path.to_bool - Sass::Script::String.new(clean_path(path)) - else - clean_url(path) - end - end - - def font_url(path, only_path = Sass::Script::Bool.new(false)) - path = path.value # get to the string value of the literal. - - # Short curcuit if they have provided an absolute url. - if absolute_path?(path) - return Sass::Script::String.new("url(#{path})") - end - - if only_path.to_bool - Sass::Script::String.new(clean_path(path)) - else - clean_url(path) - end - end - - def image_url(path, only_path = Sass::Script::Bool.new(false)) - print "#{@options}\n" - path = path.value # get to the string value of the literal. - - if absolute_path?(path) - # Short curcuit if they have provided an absolute url. - return Sass::Script::String.new("url(#{path})") - end - - if only_path.to_bool - Sass::Script::String.new(clean_path(path)) - else - clean_url(path) - end - end - - private - - # Emits a path, taking off any leading "./" - def clean_path(url) - url = url.to_s - url = url[0..1] == "./" ? url[2..-1] : url - end - - # Emits a url, taking off any leading "./" - def clean_url(url) - Sass::Script::String.new("url('#{clean_path(url)}')") - end - - def absolute_path?(path) - path[0..0] == "/" || path[0..3] == "http" - end - -end - -module Sass::Script::Functions - include Compass::SassExtensions::Functions::Urls -end +require "rubygems" +require "compass" + +module Compass::SassExtensions::Functions::Urls + + def stylesheet_url(path, only_path = Sass::Script::Bool.new(false)) + if only_path.to_bool + Sass::Script::String.new(clean_path(path)) + else + clean_url(path) + end + end + + def font_url(path, only_path = Sass::Script::Bool.new(false)) + path = path.value # get to the string value of the literal. + + # Short curcuit if they have provided an absolute url. + if absolute_path?(path) + return Sass::Script::String.new("url(#{path})") + end + + if only_path.to_bool + Sass::Script::String.new(clean_path(path)) + else + clean_url(path) + end + end + + def image_url(path, only_path = Sass::Script::Bool.new(false)) + print "#{@options}\n" + path = path.value # get to the string value of the literal. + + if absolute_path?(path) + # Short curcuit if they have provided an absolute url. + return Sass::Script::String.new("url(#{path})") + end + + if only_path.to_bool + Sass::Script::String.new(clean_path(path)) + else + clean_url(path) + end + end + + private + + # Emits a path, taking off any leading "./" + def clean_path(url) + url = url.to_s + url = url[0..1] == "./" ? url[2..-1] : url + end + + # Emits a url, taking off any leading "./" + def clean_url(url) + Sass::Script::String.new("url('#{clean_path(url)}')") + end + + def absolute_path?(path) + path[0..0] == "/" || path[0..3] == "http" + end + +end + +module Sass::Script::Functions + include Compass::SassExtensions::Functions::Urls +end diff --git a/mediagenerator/filters/sass_paths.rb b/mediagenerator/filters/sass_paths.rb index 6278798..39900e9 100644 --- a/mediagenerator/filters/sass_paths.rb +++ b/mediagenerator/filters/sass_paths.rb @@ -1,12 +1,12 @@ -require "rubygems" -require "sass" -require "compass" - -ARGV.each do |arg| - require arg -end - -Compass::Frameworks::ALL.each do |framework| - next if framework.name =~ /^_/ - print "#{File.expand_path(framework.stylesheets_directory)}\n" -end +require "rubygems" +require "sass" +require "compass" + +ARGV.each do |arg| + require arg +end + +Compass::Frameworks::ALL.each do |framework| + next if framework.name =~ /^_/ + print "#{File.expand_path(framework.stylesheets_directory)}\n" +end
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
578