[Python-modules-commits] [django-webpack-loader] 01/05: importing django-webpack-loader_0.2.4.orig.tar.gz

Michael Fladischer fladi at moszumanska.debian.org
Thu Feb 18 13:49:16 UTC 2016


This is an automated email from the git hooks/post-receive script.

fladi pushed a commit to branch master
in repository django-webpack-loader.

commit 46f0cd031a826b550db67c645beb2ee2579bc126
Author: Michael Fladischer <FladischerMichael at fladi.at>
Date:   Thu Feb 18 12:42:00 2016 +0100

    importing django-webpack-loader_0.2.4.orig.tar.gz
---
 LICENSE                                       | 22 +++++++
 PKG-INFO                                      | 18 ++++++
 setup.cfg                                     |  2 +
 setup.py                                      | 24 +++++++
 webpack_loader/__init__.py                    |  1 +
 webpack_loader/apps.py                        | 28 ++++++++
 webpack_loader/contrib/__init__.py            |  0
 webpack_loader/contrib/jinja2ext.py           |  9 +++
 webpack_loader/errors.py                      |  9 +++
 webpack_loader/signals.py                     |  1 +
 webpack_loader/templatetags/__init__.py       |  0
 webpack_loader/templatetags/webpack_loader.py | 64 +++++++++++++++++++
 webpack_loader/utils.py                       | 92 +++++++++++++++++++++++++++
 13 files changed, 270 insertions(+)

diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..00c6388
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,22 @@
+The MIT License (MIT)
+
+Copyright (c) 2015 Owais Lone
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
diff --git a/PKG-INFO b/PKG-INFO
new file mode 100644
index 0000000..ca86fd7
--- /dev/null
+++ b/PKG-INFO
@@ -0,0 +1,18 @@
+Metadata-Version: 1.1
+Name: django-webpack-loader
+Version: 0.2.4
+Summary: Transparently use webpack with django
+Home-page: https://github.com/owais/django-webpack-loader
+Author: Owais Lone
+Author-email: hello at owaislone.org
+License: UNKNOWN
+Download-URL: https://github.com/owais/django-webpack-loader/tarball/0.2.4
+Description: UNKNOWN
+Keywords: django,webpack,assets
+Platform: UNKNOWN
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Framework :: Django
+Classifier: Environment :: Web Environment
+Classifier: License :: OSI Approved :: MIT License
diff --git a/setup.cfg b/setup.cfg
new file mode 100644
index 0000000..b88034e
--- /dev/null
+++ b/setup.cfg
@@ -0,0 +1,2 @@
+[metadata]
+description-file = README.md
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..8bf02ab
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,24 @@
+from distutils.core import setup
+
+version = '0.2.4'
+
+setup(
+  name = 'django-webpack-loader',
+  packages = ['webpack_loader', 'webpack_loader/templatetags', 'webpack_loader/contrib'],
+  version = version,
+  description = 'Transparently use webpack with django',
+  author = 'Owais Lone',
+  author_email = 'hello at owaislone.org',
+  download_url = 'https://github.com/owais/django-webpack-loader/tarball/{}'.format(version),
+  url = 'https://github.com/owais/django-webpack-loader', # use the URL to the github repo
+  keywords = ['django', 'webpack', 'assets'], # arbitrary keywords
+  data_files = [("", ["LICENSE"])],
+  classifiers = [
+    'Programming Language :: Python :: 2.7',
+    'Programming Language :: Python :: 3.3',
+    'Programming Language :: Python :: 3.4',
+    'Framework :: Django',
+    'Environment :: Web Environment',
+    'License :: OSI Approved :: MIT License',
+  ],
+)
diff --git a/webpack_loader/__init__.py b/webpack_loader/__init__.py
new file mode 100644
index 0000000..6b8fc6c
--- /dev/null
+++ b/webpack_loader/__init__.py
@@ -0,0 +1 @@
+default_app_config = 'webpack_loader.apps.WebpackLoaderConfig'
diff --git a/webpack_loader/apps.py b/webpack_loader/apps.py
new file mode 100644
index 0000000..141bbe0
--- /dev/null
+++ b/webpack_loader/apps.py
@@ -0,0 +1,28 @@
+from django.apps import AppConfig
+
+from .errors import BAD_CONFIG_ERROR
+
+
+def webpack_cfg_check(app_configs, **kwargs):
+    from django.conf import settings
+
+    check_failed = False
+    user_config = getattr(settings, 'WEBPACK_LOADER', {})
+    try:
+        user_config = [dict({}, **cfg) for cfg in user_config.values()]
+    except TypeError:
+        check_failed = True
+
+    errors = []
+    if check_failed:
+        errors.append(BAD_CONFIG_ERROR)
+    return errors
+
+
+class WebpackLoaderConfig(AppConfig):
+    name = 'webpack_loader'
+    verbose_name = "Webpack Loader"
+
+    def ready(self):
+        from django.core.checks import register, Tags
+        register(Tags.compatibility)(webpack_cfg_check)
diff --git a/webpack_loader/contrib/__init__.py b/webpack_loader/contrib/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/webpack_loader/contrib/jinja2ext.py b/webpack_loader/contrib/jinja2ext.py
new file mode 100644
index 0000000..38a530c
--- /dev/null
+++ b/webpack_loader/contrib/jinja2ext.py
@@ -0,0 +1,9 @@
+import jinja2.ext
+
+from ..templatetags.webpack_loader import render_bundle
+
+
+class WebpackExtension(jinja2.ext.Extension):
+    def __init__(self, environment):
+        super(WebpackExtension, self).__init__(environment)
+        environment.globals["render_bundle"] = lambda *a, **k: jinja2.Markup(render_bundle(*a, **k))
diff --git a/webpack_loader/errors.py b/webpack_loader/errors.py
new file mode 100644
index 0000000..c071e67
--- /dev/null
+++ b/webpack_loader/errors.py
@@ -0,0 +1,9 @@
+from django.core.checks import Error
+
+
+BAD_CONFIG_ERROR = Error(
+    'Error while parsing WEBPACK_LOADER configuration',
+    hint='Is WEBPACK_LOADER config valid?',
+    obj='django.conf.settings.WEBPACK_LOADER',
+    id='django-webpack-loader.E001',
+)
diff --git a/webpack_loader/signals.py b/webpack_loader/signals.py
new file mode 100644
index 0000000..c99094d
--- /dev/null
+++ b/webpack_loader/signals.py
@@ -0,0 +1 @@
+# will hook into collectstatic
diff --git a/webpack_loader/templatetags/__init__.py b/webpack_loader/templatetags/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/webpack_loader/templatetags/webpack_loader.py b/webpack_loader/templatetags/webpack_loader.py
new file mode 100644
index 0000000..dbf5cb5
--- /dev/null
+++ b/webpack_loader/templatetags/webpack_loader.py
@@ -0,0 +1,64 @@
+from django import template
+from django.conf import settings
+from django.utils.safestring import mark_safe
+
+from ..utils import get_config, get_assets, get_bundle
+
+
+register = template.Library()
+
+
+def filter_by_extension(bundle, extension):
+    for chunk in bundle:
+        if chunk['name'].endswith('.{}'.format(extension)):
+            yield chunk
+
+
+def render_as_tags(bundle):
+    tags = []
+    for chunk in bundle:
+        url = chunk.get('publicPath') or chunk['url']
+        if chunk['name'].endswith('.js'):
+            tags.append('<script type="text/javascript" src="{}"></script>'.format(url))
+        elif chunk['name'].endswith('.css'):
+            tags.append('<link type="text/css" href="{}" rel="stylesheet"/>'.format(url))
+    return mark_safe('\n'.join(tags))
+
+
+def _get_bundle(bundle_name, extension, config):
+    bundle = get_bundle(bundle_name, get_config(config))
+    if extension:
+        bundle = filter_by_extension(bundle, extension)
+    return bundle
+
+
+ at register.simple_tag
+def render_bundle(bundle_name, extension=None, config='DEFAULT'):
+    return render_as_tags(_get_bundle(bundle_name, extension, config))
+
+
+ at register.simple_tag
+def webpack_static(asset_name, config='DEFAULT'):
+    return "{}{}".format(
+        get_assets(get_config(config)).get(
+            'publicPath', getattr(settings, 'STATIC_URL')
+        ),
+        asset_name
+    )
+
+
+ at register.assignment_tag
+def get_files(bundle_name, extension=None, config='DEFAULT'):
+    """
+    Returns all chunks in the given bundle.
+    Example usage::
+
+        {% get_files 'editor' 'css' as editor_css_chunks %}
+        CKEDITOR.config.contentsCss = '{{ editor_css_chunks.0.publicPath }}';
+
+    :param bundle_name: The name of the bundle
+    :param extension: (optional) filter by extension
+    :param config: (optional) the name of the configuration
+    :return: a list of matching chunks
+    """
+    return list(_get_bundle(bundle_name, extension, config))
diff --git a/webpack_loader/utils.py b/webpack_loader/utils.py
new file mode 100644
index 0000000..420322d
--- /dev/null
+++ b/webpack_loader/utils.py
@@ -0,0 +1,92 @@
+import re
+import json
+import time
+
+from django.conf import settings
+from django.contrib.staticfiles.storage import staticfiles_storage
+
+
+__all__ = ('get_assets', 'get_config', 'get_bundle',)
+
+
+DEFAULT_CONFIG = {
+    'DEFAULT': {
+        'BUNDLE_DIR_NAME': 'webpack_bundles/',
+        'STATS_FILE': 'webpack-stats.json',
+        # FIXME: Explore usage of fsnotify
+        'POLL_INTERVAL': 0.1,
+        'IGNORE': ['.+\.hot-update.js', '.+\.map']
+    }
+}
+
+
+user_config = getattr(settings, 'WEBPACK_LOADER', DEFAULT_CONFIG)
+
+user_config = {
+    name: dict(DEFAULT_CONFIG['DEFAULT'], **cfg)
+    for name, cfg in user_config.items()
+}
+
+for entry in user_config.values():
+    entry['ignores'] = [re.compile(I) for I in entry['IGNORE']]
+
+
+class WebpackError(BaseException):
+    pass
+
+
+class WebpackLoaderBadStatsError(BaseException):
+    pass
+
+
+def get_config(config_name):
+    return user_config[config_name]
+
+
+def get_assets(config):
+    try:
+        with open(config['STATS_FILE']) as f:
+            return json.load(f)
+    except IOError:
+        raise IOError(
+            'Error reading {}. Are you sure webpack has generated the file '
+            'and the path is correct?'.format(config['STATS_FILE']))
+
+
+def filter_files(files, config):
+    for F in files:
+        filename = F['name']
+        ignore = any(regex.match(filename) for regex in config['ignores'])
+        if not ignore:
+            relpath = '{}{}'.format(config['BUNDLE_DIR_NAME'], filename)
+            F['url'] = staticfiles_storage.url(relpath)
+            yield F
+
+
+def get_bundle(bundle_name, config):
+    assets = get_assets(config)
+
+    if settings.DEBUG:
+        # poll when debugging and block request until bundle is compiled
+        # TODO: support timeouts
+        while assets['status'] == 'compiling':
+            time.sleep(config['POLL_INTERVAL'])
+            assets = get_assets(config)
+
+    if assets.get('status') == 'done':
+        files = assets['chunks'][bundle_name]
+        return filter_files(files, config)
+
+    elif assets.get('status') == 'error':
+        if 'file' not in assets:
+            assets['file'] = ''
+        error = u"""
+        {error} in {file}
+        {message}
+        """.format(**assets)
+        raise WebpackError(error)
+
+    raise WebpackLoaderBadStatsError(
+        "The stats file does not contain valid data. Make sure "
+        "webpack-bundle-tracker plugin is enabled and try to run "
+        "webpack again.")

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/django-webpack-loader.git



More information about the Python-modules-commits mailing list