Merge branch 'master' into offline

Conflicts:
	.gitignore
	tests/settings.py

Moved offline test template to new location.
This commit is contained in:
Ulrich Petri
2011-01-28 00:01:55 +01:00
53 changed files with 1303 additions and 346 deletions

4
.gitignore vendored
View File

@@ -4,4 +4,6 @@ dist
MANIFEST
*.pyc
*.egg-info
tests/media/
.tox/
*.egg
docs/_build/

View File

@@ -1,18 +1,20 @@
Christian Metts
Christian Metts <xian@mintchaos.com>
Carl Meyer
Jannis Leidel
Django Compressor's filters started life as the filters from Andreas Pelme's
django-compress.
Contributors:
Aaron Godfrey
Atamert Ölçgen
Ben Spaulding
Benjamin Wohlwend
Brad Whittington
Carl Meyer
Chris Adams
David Ziegler
Gert Van Gool
Jannis Leidel
Justin Lilly
Maciek Szczesniak
Mehmet S. Catalbas

View File

@@ -1,6 +1,6 @@
django_compressor
-----------------
Copyright (c) 2009 Christian Metts <xian@mintchaos.com>
Copyright (c) 2009-2011 django_compressor authors (see AUTHORS file)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View File

@@ -1,4 +1,5 @@
include AUTHORS
include README.rst
include LICENSE
recursive-include compressor/templates/compressor *.html
recursive-include compressor/templates/compressor *.html
recursive-include compressor/tests/media *.js *.css *.png

View File

@@ -1,208 +1,13 @@
Django compressor
=================
==================
Compresses linked and inline javascript or CSS into a single cached file.
Syntax::
The main website for django-compressor is
`github.com/jezdez/django_compressor`_ where you can also file tickets.
{% compress <js/css> %}
<html of inline or linked JS/CSS>
{% endcompress %}
You can also install the `in-development version`_ of django-compressor with
``pip install django_compressor==dev`` or ``easy_install django_compressor==dev``.
Examples::
{% compress css %}
<link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
{% endcompress %}
Which would be rendered something like::
<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css" charset="utf-8">
or::
{% compress js %}
<script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">obj.value = "value";</script>
{% endcompress %}
Which would be rendered something like::
<script type="text/javascript" src="/media/CACHE/js/3f33b9146e12.js" charset="utf-8"></script>
Linked files must be on your COMPRESS_URL (which defaults to MEDIA_URL).
If DEBUG is true off-site files will throw exceptions. If DEBUG is false
they will be silently stripped.
If COMPRESS is False (defaults to the opposite of DEBUG) the compress tag
simply returns exactly what it was given, to ease development.
CSS Notes:
**********
All relative url() bits specified in linked CSS files are automatically
converted to absolute URLs while being processed. Any local absolute URLs (those
starting with a '/') are left alone.
Stylesheets that are @import'd are not compressed into the main file. They are
left alone.
If the media attribute is set on <style> and <link> elements, a separate
compressed file is created and linked for each media value you specified.
This allows the media attribute to remain on the generated link element,
instead of wrapping your CSS with @media blocks (which can break your own
@media queries or @font-face declarations). It also allows browsers to avoid
downloading CSS for irrelevant media types.
**Recommendations:**
* Use only relative or full domain absolute URLs in your CSS files.
* Avoid @import! Simply list all your CSS files in the HTML, they'll be combined anyway.
Why another static file combiner for django?
********************************************
Short version: None of them did exactly what I needed.
Long version:
**JS/CSS belong in the templates**
Every static combiner for django I've seen makes you configure
your static files in your settings.py. While that works, it doesn't make
sense. Static files are for display. And it's not even an option if your
settings are in completely different repositories and use different deploy
processes from the templates that depend on them.
**Flexibility**
django_compressor doesn't care if different pages use different combinations
of statics. It doesn't care if you use inline scripts or styles. It doesn't
get in the way.
**Automatic regeneration and cache-foreverable generated output**
Statics are never stale and browsers can be told to cache the output forever.
**Full test suite**
I has one.
Settings
********
Django compressor has a number of settings that control it's behavior.
They've been given sensible defaults.
``COMPRESS``
------------
:Default: the opposite of ``DEBUG``
Boolean that decides if compression will happen.
``COMPRESS_URL``
----------------
:Default: ``MEDIA_URL``
Controls the URL that linked media will be read from and compressed media
will be written to.
``COMPRESS_ROOT``
-----------------
:Default: ``MEDIA_ROOT``
Controls the absolute file path that linked media will be read from and
compressed media will be written to.
``COMPRESS_OUTPUT_DIR``
-----------------------
:Default: ``'CACHE'``
Controls the directory inside `COMPRESS_ROOT` that compressed files will
be written to.
``COMPRESS_CSS_FILTERS``
------------------------
:Default: ``['compressor.filters.css_default.CssAbsoluteFilter']``
A list of filters that will be applied to CSS.
``COMPRESS_JS_FILTERS``
-----------------------
:Default: ``['compressor.filters.jsmin.JSMinFilter']``
A list of filters that will be applied to javascript.
``COMPRESS_STORAGE``
--------------------
:Default: ``'compressor.storage.CompressorFileStorage'``
The dotted path to a Django Storage backend to be used to save the
compressed files.
``COMPRESS_PARSER``
--------------------
:Default: ``'compressor.parser.BeautifulSoupParser'``
The backend to use when parsing the JavaScript or Stylesheet files.
The backends included in ``compressor``:
- ``compressor.parser.BeautifulSoupParser``
- ``compressor.parser.LxmlParser``
See `Dependencies`_ for more info about the packages you need for each parser.
``COMPRESS_REBUILD_TIMEOUT``
----------------------------
:Default: ``2592000`` (30 days in seconds)
The period of time after which the the compressed files are rebuilt even if
no file changes are detected.
``COMPRESS_MINT_DELAY``
------------------------
:Default: ``30`` (seconds)
The upper bound on how long any compression should take to run. Prevents
dog piling, should be a lot smaller than ``COMPRESS_REBUILD_TIMEOUT``.
``COMPRESS_MTIME_DELAY``
------------------------
:Default: ``None``
The amount of time (in seconds) to cache the result of the check of the
modification timestamp of a file. Disabled by default. Should be smaller
than ``COMPRESS_REBUILD_TIMEOUT`` and ``COMPRESS_MINT_DELAY``.
Dependencies
************
* BeautifulSoup_ (for the default ``compressor.parser.BeautifulSoupParser``)
::
pip install BeautifulSoup
* lxml_ (for the optional ``compressor.parser.LxmlParser``, requires libxml2_)
::
STATIC_DEPS=true pip install lxml
.. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/
.. _lxml: http://codespeak.net/lxml/
.. _libxml2: http://xmlsoft.org/
.. _github.com/jezdez/django_compressor: http://github.com/jezdez/django_compressor
.. _in-development version: http://github.com/jezdez/django_compressor/tarball/master#egg=django_compressor-dev

View File

@@ -1,5 +0,0 @@
from compressor.base import Compressor
from compressor.js import JsCompressor
from compressor.css import CssCompressor
from compressor.utils import get_hexdigest, get_mtime
from compressor.exceptions import UncompressableFileError

View File

@@ -22,12 +22,18 @@ class Compressor(object):
raise NotImplementedError('split_contents must be defined in a subclass')
def get_filename(self, url):
if not url.startswith(self.storage.base_url):
raise UncompressableFileError('"%s" is not in COMPRESS_URL ("%s") and can not be compressed' % (url, self.storage.base_url))
basename = url.replace(self.storage.base_url, "", 1)
if not self.storage.exists(basename):
raise UncompressableFileError('"%s" does not exist' % self.storage.path(basename))
return self.storage.path(basename)
try:
base_url = self.storage.base_url
except AttributeError:
base_url = settings.MEDIA_URL
if not url.startswith(base_url):
raise UncompressableFileError('"%s" is not in COMPRESS_URL ("%s") and can not be compressed' % (url, base_url))
basename = url.replace(base_url, "", 1)
filename = os.path.join(settings.MEDIA_ROOT, basename)
if not os.path.exists(filename):
raise UncompressableFileError('"%s" does not exist' % filename)
return filename
def _get_parser(self):
if self._parser:

4
compressor/cache.py Normal file
View File

@@ -0,0 +1,4 @@
from django.core.cache import get_cache
from compressor.conf import settings
cache = get_cache(settings.CACHE_BACKEND)

View File

@@ -1,8 +1,11 @@
from django.core.exceptions import ImproperlyConfigured
from django.conf import settings
MEDIA_URL = getattr(settings, 'COMPRESS_URL', settings.MEDIA_URL)
if not MEDIA_URL.endswith('/'):
raise ImproperlyConfigured(
'The MEDIA_URL and COMPRESS_URL settings must have a trailing slash.')
MEDIA_ROOT = getattr(settings, 'COMPRESS_ROOT', settings.MEDIA_ROOT)
OUTPUT_DIR = getattr(settings, 'COMPRESS_OUTPUT_DIR', 'CACHE')
STORAGE = getattr(settings, 'COMPRESS_STORAGE', 'compressor.storage.CompressorFileStorage')
@@ -58,3 +61,13 @@ PARSER = getattr(settings, 'COMPRESS_PARSER', 'compressor.parser.BeautifulSoupPa
# Allows changing verbosity from the settings.
VERBOSE = getattr(settings, "COMPRESS_VERBOSE", False)
# the cache backend to use
CACHE_BACKEND = getattr(settings, 'COMPRESS_CACHE_BACKEND', None)
if CACHE_BACKEND is None:
# If we are on Django 1.3 AND using the new CACHES setting...
if getattr(settings, "CACHES", None):
CACHE_BACKEND = "default"
else:
# fallback for people still using the old CACHE_BACKEND setting
CACHE_BACKEND = settings.CACHE_BACKEND

View File

@@ -1,17 +1,18 @@
from django.conf import settings as django_settings
from compressor.conf import settings
from compressor.base import Compressor, UncompressableFileError
from compressor.base import Compressor
from compressor.exceptions import UncompressableFileError
class CssCompressor(Compressor):
def __init__(self, content, output_prefix="css"):
super(CssCompressor, self).__init__(content, output_prefix)
self.extension = ".css"
self.template_name = "compressor/css.html"
self.template_name_inline = "compressor/css_inline.html"
self.filters = list(settings.COMPRESS_CSS_FILTERS)
self.type = 'css'
super(CssCompressor, self).__init__(content, output_prefix)
def split_contents(self):
if self.split_content:

View File

@@ -1,7 +1,8 @@
import subprocess
from subprocess import Popen, PIPE
from compressor.conf import settings
from compressor.filters import FilterBase, FilterError
from compressor.utils import cmd_split
class ClosureCompilerFilter(FilterBase):
@@ -12,15 +13,9 @@ class ClosureCompilerFilter(FilterBase):
command = '%s %s' % (settings.CLOSURE_COMPILER_BINARY, arguments)
try:
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.write(self.content)
p.stdin.close()
p = Popen(cmd_split(command), stdout=PIPE, stdin=PIPE, stderr=PIPE)
filtered, err = p.communicate(self.content)
filtered = p.stdout.read()
p.stdout.close()
err = p.stderr.read()
p.stderr.close()
except IOError, e:
raise FilterError(e)

View File

@@ -11,12 +11,12 @@ URL_PATTERN = re.compile(r'url\(([^\)]+)\)')
class CssAbsoluteFilter(FilterBase):
def input(self, filename=None, **kwargs):
media_root = os.path.abspath(settings.MEDIA_ROOT)
media_root = os.path.normcase(os.path.abspath(settings.MEDIA_ROOT))
if filename is not None:
filename = os.path.abspath(filename)
filename = os.path.normcase(os.path.abspath(filename))
if not filename or not filename.startswith(media_root):
return self.content
self.media_path = filename[len(media_root):]
self.media_path = filename[len(media_root):].replace(os.sep, '/')
self.media_path = self.media_path.lstrip('/')
self.media_url = settings.MEDIA_URL.rstrip('/')
try:

View File

@@ -1,7 +1,8 @@
import subprocess
from subprocess import Popen, PIPE
from compressor.conf import settings
from compressor.filters import FilterBase, FilterError
from compressor.utils import cmd_split
class YUICompressorFilter(FilterBase):
@@ -19,16 +20,8 @@ class YUICompressorFilter(FilterBase):
command += ' --verbose'
try:
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
p.stdin.write(self.content)
p.stdin.close()
filtered = p.stdout.read()
p.stdout.close()
err = p.stderr.read()
p.stderr.close()
p = Popen(cmd_split(command), stdin=PIPE, stdout=PIPE, stderr=PIPE)
filtered, err = p.communicate(self.content)
except IOError, e:
raise FilterError(e)
@@ -42,11 +35,13 @@ class YUICompressorFilter(FilterBase):
return filtered
class YUICSSFilter(YUICompressorFilter):
def __init__(self, *args, **kwargs):
super(YUICSSFilter, self).__init__(*args, **kwargs)
self.type = 'css'
class YUIJSFilter(YUICompressorFilter):
def __init__(self, *args, **kwargs):
super(YUIJSFilter, self).__init__(*args, **kwargs)

View File

@@ -1,17 +1,19 @@
from django.conf import settings as django_settings
from compressor.conf import settings
from compressor.base import Compressor, UncompressableFileError
from compressor.base import Compressor
from compressor.exceptions import UncompressableFileError
class JsCompressor(Compressor):
def __init__(self, content, output_prefix="js"):
super(JsCompressor, self).__init__(content, output_prefix)
self.extension = ".js"
self.template_name = "compressor/js.html"
self.template_name_inline = "compressor/js_inline.html"
self.filters = settings.COMPRESS_JS_FILTERS
self.type = 'js'
super(JsCompressor, self).__init__(content, output_prefix)
def split_contents(self):
if self.split_content:

View File

@@ -2,11 +2,11 @@ import fnmatch
import os
from optparse import make_option
from django.core.cache import cache
from django.core.management.base import NoArgsCommand, CommandError
from compressor.cache import cache
from compressor.conf import settings
from compressor.utils import get_mtime, get_mtime_cachekey
from compressor.utils import get_mtime, get_mtime_cachekey, walk
class Command(NoArgsCommand):
help = "Add or remove all mtime values from the cache"
@@ -57,7 +57,7 @@ class Command(NoArgsCommand):
files_to_add = set()
keys_to_delete = set()
for root, dirs, files in os.walk(settings.MEDIA_ROOT, followlinks=options['follow_links']):
for root, dirs, files in walk(settings.MEDIA_ROOT, followlinks=options['follow_links']):
for dir_ in dirs:
if self.is_ignored(dir_):
dirs.remove(dir_)

View File

@@ -1 +1 @@
<link rel="stylesheet" href="{{ url }}" type="text/css" {% if media %}media="{{ media }}" {% endif %}charset="utf-8" />
<link rel="stylesheet" href="{{ url }}" type="text/css"{% if media %} media="{{ media }}"{% endif %}>

View File

@@ -1 +1 @@
<style type="text/css"{% if media %} media="{{ media }}"{% endif %}>{{ content|safe }}</style>
<style type="text/css"{% if media %} media="{{ media }}"{% endif %}>{{ content|safe }}</style>

View File

@@ -1,8 +1,10 @@
import time
from django import template
from django.core.cache import cache
from compressor import CssCompressor, JsCompressor
from compressor.css import CssCompressor
from compressor.js import JsCompressor
from compressor.cache import cache
from compressor.conf import settings
from compressor.utils import make_offline_cache_key

View File

Before

Width:  |  Height:  |  Size: 733 B

After

Width:  |  Height:  |  Size: 733 B

View File

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env python
import os
import sys
from django.conf import settings
TEST_DIR = os.path.dirname(os.path.abspath(__file__))
if not settings.configured:
settings.configure(
COMPRESS_CACHE_BACKEND = 'dummy://',
DATABASE_ENGINE='sqlite3',
INSTALLED_APPS=[
'compressor',
'compressor.tests',
],
MEDIA_URL = '/media/',
MEDIA_ROOT = os.path.join(TEST_DIR, 'media'),
TEMPLATE_DIRS = (
os.path.join(TEST_DIR, 'templates'),
),
TEST_DIR = TEST_DIR,
)
from django.test.simple import run_tests
def runtests(*test_args):
if not test_args:
test_args = ['tests']
parent = os.path.join(TEST_DIR, "..", "..")
sys.path.insert(0, parent)
failures = run_tests(test_args, verbosity=1, interactive=True)
sys.exit(failures)
if __name__ == '__main__':
runtests(*sys.argv[1:])

View File

@@ -0,0 +1,16 @@
import gzip
from compressor.storage import CompressorFileStorage
class TestStorage(CompressorFileStorage):
"""
Test compressor storage that gzips storage files
"""
def url(self, name):
return u'%s.gz' % super(TestStorage, self).url(name)
def save(self, filename, content):
filename = super(TestStorage, self).save(filename, content)
out = gzip.open(u'%s.gz' % self.path(filename), 'wb')
out.writelines(open(self.path(filename), 'rb'))
out.close()

View File

@@ -1,17 +1,18 @@
import os
import re
import gzip
from BeautifulSoup import BeautifulSoup
from django.template import Template, Context, TemplateSyntaxError
from django.test import TestCase
from django.core.files.storage import get_storage_class
from django.conf import settings as django_settings
from django.core.cache.backends import dummy
from compressor import CssCompressor, JsCompressor, storage
from compressor import storage
from compressor.css import CssCompressor
from compressor.js import JsCompressor
from compressor.conf import settings
from compressor.storage import CompressorFileStorage
from compressor.utils import get_hexdigest, get_mtime
from compressor.utils import get_hashed_mtime
class CompressorTestCase(TestCase):
@@ -66,7 +67,7 @@ class CompressorTestCase(TestCase):
self.assertEqual('f7c661b7a124', self.cssNode.hash)
def test_css_return_if_on(self):
output = u'<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css" charset="utf-8" />'
output = u'<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css">'
self.assertEqual(output, self.cssNode.output().strip())
def test_js_split(self):
@@ -110,6 +111,7 @@ class CompressorTestCase(TestCase):
self.assertEqual(output, JsCompressor(self.js).output())
settings.OUTPUT_DIR = old_output_dir
class LxmlCompressorTestCase(CompressorTestCase):
def test_css_split(self):
@@ -130,10 +132,6 @@ class LxmlCompressorTestCase(CompressorTestCase):
def tearDown(self):
settings.PARSER = self.old_parser
def get_hashed_mtime(filename, length=12):
filename = os.path.realpath(filename)
mtime = str(int(get_mtime(filename)))
return get_hexdigest(mtime)[:length]
class CssAbsolutizingTestCase(TestCase):
def setUp(self):
@@ -180,7 +178,6 @@ class CssAbsolutizingTestCase(TestCase):
output = "p { background: url('%simages/image.gif?%s') }" % (settings.MEDIA_URL, get_hashed_mtime(filename))
self.assertEqual(output, filter.input(filename=filename))
def test_css_hunks(self):
hash_dict = {
'hash1': get_hashed_mtime(os.path.join(settings.MEDIA_ROOT, 'css/url/url1.css')),
@@ -276,7 +273,7 @@ class TemplatetagTestCase(TestCase):
{% endcompress %}
"""
context = { 'MEDIA_URL': settings.MEDIA_URL }
out = u'<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css" charset="utf-8" />'
out = u'<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css">'
self.assertEqual(out, render(template, context))
def test_nonascii_css_tag(self):
@@ -286,7 +283,7 @@ class TemplatetagTestCase(TestCase):
{% endcompress %}
"""
context = { 'MEDIA_URL': settings.MEDIA_URL }
out = '<link rel="stylesheet" href="/media/CACHE/css/1c1c0855907b.css" type="text/css" charset="utf-8" />'
out = '<link rel="stylesheet" href="/media/CACHE/css/1c1c0855907b.css" type="text/css">'
self.assertEqual(out, render(template, context))
def test_js_tag(self):
@@ -325,23 +322,11 @@ class TemplatetagTestCase(TestCase):
{% endcompress %}"""
self.assertRaises(TemplateSyntaxError, render, template, {})
class TestStorage(CompressorFileStorage):
"""
Test compressor storage that gzips storage files
"""
def url(self, name):
return u'%s.gz' % super(TestStorage, self).url(name)
def save(self, filename, content):
filename = super(TestStorage, self).save(filename, content)
out = gzip.open(u'%s.gz' % self.path(filename), 'wb')
out.writelines(open(self.path(filename), 'rb'))
out.close()
class StorageTestCase(TestCase):
def setUp(self):
self._storage = storage.default_storage
storage.default_storage = get_storage_class('core.tests.TestStorage')()
storage.default_storage = get_storage_class('compressor.tests.storage.TestStorage')()
settings.COMPRESS = True
def tearDown(self):
@@ -355,7 +340,7 @@ class StorageTestCase(TestCase):
{% endcompress %}
"""
context = { 'MEDIA_URL': settings.MEDIA_URL }
out = u'<link rel="stylesheet" href="/media/CACHE/css/5b231a62e9a6.css.gz" type="text/css" charset="utf-8" />'
out = u'<link rel="stylesheet" href="/media/CACHE/css/5b231a62e9a6.css.gz" type="text/css">'
self.assertEqual(out, render(template, context))
@@ -364,3 +349,10 @@ class VerboseTestCase(CompressorTestCase):
def setUp(self):
super(VerboseTestCase, self).setUp()
setattr(settings, "COMPRESS_VERBOSE", True)
class CacheBackendTestCase(CompressorTestCase):
def test_correct_backend(self):
from compressor.cache import cache
self.assertEqual(cache.__class__, dummy.CacheClass)

View File

@@ -1,5 +1,7 @@
import os
from django.core.cache import cache
from shlex import split as cmd_split
from compressor.cache import cache
from compressor.conf import settings
from compressor.exceptions import FilterError
@@ -27,6 +29,11 @@ def get_mtime(filename):
return mtime
return os.path.getmtime(filename)
def get_hashed_mtime(filename, length=12):
filename = os.path.realpath(filename)
mtime = str(int(get_mtime(filename)))
return get_hexdigest(mtime)[:length]
def get_class(class_string, exception=FilterError):
"""
@@ -57,3 +64,18 @@ def get_mod_func(callback):
except ValueError:
return callback, ''
return callback[:dot], callback[dot+1:]
def walk(root, topdown=True, onerror=None, followlinks=False):
"""
A version of os.walk that can follow symlinks for Python < 2.6
"""
for dirpath, dirnames, filenames in os.walk(root, topdown, onerror):
yield (dirpath, dirnames, filenames)
if followlinks:
for d in dirnames:
p = os.path.join(dirpath, d)
if os.path.islink(p):
for link_dirpath, link_dirnames, link_filenames in walk(p):
yield (link_dirpath, link_dirnames, link_filenames)

130
docs/Makefile Normal file
View File

@@ -0,0 +1,130 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/django-compressor.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/django-compressor.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/django-compressor"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/django-compressor"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
make -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."

View File

@@ -0,0 +1,238 @@
/**
* Sphinx stylesheet -- default theme
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/
@import url("basic.css");
/* -- page layout ----------------------------------------------------------- */
body {
font-family: Arial, sans-serif;
font-size: 100%;
background-color: #111111;
color: #555555;
margin: 0;
padding: 0;
}
div.documentwrapper {
float: left;
width: 100%;
}
div.bodywrapper {
margin: 0 0 0 300px;
}
hr{
border: 1px solid #B1B4B6;
}
div.document {
background-color: #fafafa;
}
div.body {
background-color: #ffffff;
color: #3E4349;
padding: 1em 30px 30px 30px;
font-size: 0.9em;
}
div.footer {
color: #555;
width: 100%;
padding: 13px 0;
text-align: center;
font-size: 75%;
}
div.footer a {
color: #444444;
}
div.related {
background-color: #6b2a1e;
color: #ffffff;
font: 1.2em/40px "Helvetica Neue", Arial, Helvetica, Geneva, sans-serif;
}
span.pre {
font: 0.7em Monaco, "Courier New", Courier, mono;
}
div.related a {
color: #fff4eb;
}
div.related .right {
font-size: 0.9em;
}
div.sphinxsidebar {
font-size: 0.9em;
line-height: 1.5em;
width: 300px
}
div.sphinxsidebarwrapper{
padding: 20px 0;
}
div.sphinxsidebar h3,
div.sphinxsidebar h4 {
font-family: Arial, sans-serif;
color: #222222;
font-size: 1.2em;
font-weight: bold;
margin: 0;
padding: 5px 10px;
text-shadow: 1px 1px 0 white
}
div.sphinxsidebar h3 a {
color: #444444;
}
div.sphinxsidebar p {
color: #888888;
padding: 5px 20px;
margin: 0.5em 0px;
}
div.sphinxsidebar p.topless {
}
div.sphinxsidebar ul {
margin: 10px 10px 10px 20px;
padding: 0;
color: #000000;
}
div.sphinxsidebar a {
color: #444444;
}
div.sphinxsidebar a:hover {
color: #E32E00;
}
div.sphinxsidebar input {
border: 1px solid #cccccc;
font-family: sans-serif;
font-size: 1.1em;
padding: 0.15em 0.3em;
}
div.sphinxsidebar input[type=text]{
margin-left: 20px;
}
/* -- body styles ----------------------------------------------------------- */
a {
color: #005B81;
text-decoration: none;
}
a:hover {
color: #E32E00;
}
div.body h1,
div.body h2,
div.body h3,
div.body h4,
div.body h5,
div.body h6 {
font-family: Arial, sans-serif;
font-weight: normal;
color: #212224;
margin: 30px 0px 10px 0px;
padding: 5px 0 5px 0px;
text-shadow: 0px 1px 0 white;
border-bottom: 1px solid #C8D5E3;
}
div.body h1 { margin-top: 0; font-size: 200%; }
div.body h2 { font-size: 150%; }
div.body h3 { font-size: 120%; }
div.body h4 { font-size: 110%; }
div.body h5 { font-size: 100%; }
div.body h6 { font-size: 100%; }
a.headerlink {
color: #c60f0f;
font-size: 0.8em;
padding: 0 4px 0 4px;
text-decoration: none;
}
a.headerlink:hover {
background-color: #c60f0f;
color: white;
}
div.body p, div.body dd, div.body li {
line-height: 1.8em;
}
div.admonition p.admonition-title + p {
display: inline;
}
div.highlight{
background-color: white;
}
div.note {
background-color: #eeeeee;
border: 1px solid #cccccc;
}
div.seealso {
background-color: #ffffcc;
border: 1px solid #ffff66;
}
div.topic {
background-color: #fafafa;
border-width: 0;
}
div.warning {
background-color: #ffe4e4;
border: 1px solid #ff6666;
}
p.admonition-title {
display: inline;
}
p.admonition-title:after {
content: ":";
}
pre {
padding: 4px 6px;
background-color: #fff;
border: 1px solid #ccc;
color: #222222;
margin: 1.5em 0 1.5em 0;
border-right-color: #e3e3e3;
border-bottom-color: #e3e3e3;
line-height: 1.5em;
font-size: 1.1em;
}
tt {
color: #222222;
padding: 1px 2px;
font-size: 1.2em;
font-family: monospace;
}
#table-of-contents ul {
padding-left: 2em;
}

3
docs/_theme/compressor/theme.conf vendored Normal file
View File

@@ -0,0 +1,3 @@
[theme]
inherit = basic
stylesheet = compressor.css

216
docs/conf.py Normal file
View File

@@ -0,0 +1,216 @@
# -*- coding: utf-8 -*-
#
# django-compressor documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 21 11:47:42 2011.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
# sys.path.insert(0, os.path.abspath('..'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
# extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.txt'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'Django compressor'
copyright = u'2011, Django compressor authors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.6'
# The full version, including alpha/beta/rc tags.
release = '0.6a8'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'murphy'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'compressor'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ['_theme']
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'django-compressordoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'django-compressor.tex', u'Django compressor Documentation',
u'Django compressor authors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'django-compressor', u'Django compressor Documentation',
[u'Django compressor authors'], 1)
]

240
docs/index.txt Normal file
View File

@@ -0,0 +1,240 @@
Django compressor
=================
Compresses linked and inline javascript or CSS into a single cached file.
Syntax:
.. code-block:: django
{% load compress %}
{% compress <js/css> %}
<html of inline or linked JS/CSS>
{% endcompress %}
Examples:
.. code-block:: django
{% load compress %}
{% compress css %}
<link rel="stylesheet" href="/media/css/one.css" type="text/css" charset="utf-8">
<style type="text/css">p { border:5px solid green;}</style>
<link rel="stylesheet" href="/media/css/two.css" type="text/css" charset="utf-8">
{% endcompress %}
Which would be rendered something like:
.. code-block:: html
<link rel="stylesheet" href="/media/CACHE/css/f7c661b7a124.css" type="text/css" charset="utf-8">
or:
.. code-block:: django
{% load compress %}
{% compress js %}
<script src="/media/js/one.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">obj.value = "value";</script>
{% endcompress %}
Which would be rendered something like:
.. code-block:: html
<script type="text/javascript" src="/media/CACHE/js/3f33b9146e12.js" charset="utf-8"></script>
Linked files must be on your COMPRESS_URL (which defaults to MEDIA_URL).
If DEBUG is true off-site files will throw exceptions. If DEBUG is false
they will be silently stripped.
If COMPRESS is False (defaults to the opposite of DEBUG) the compress tag
simply returns exactly what it was given, to ease development.
.. note::
For production sites it is advisable to use a real cache backend such as
memcached to speed up the checks of compressed files. Make sure you set
your Django cache backend appropriately.
CSS Notes:
**********
All relative ``url()`` bits specified in linked CSS files are automatically
converted to absolute URLs while being processed. Any local absolute URLs (those
starting with a ``'/'``) are left alone.
Stylesheets that are ``@import``'d are not compressed into the main file.
They are left alone.
If the media attribute is set on <style> and <link> elements, a separate
compressed file is created and linked for each media value you specified.
This allows the media attribute to remain on the generated link element,
instead of wrapping your CSS with @media blocks (which can break your own
@media queries or @font-face declarations). It also allows browsers to avoid
downloading CSS for irrelevant media types.
**Recommendations:**
* Use only relative or full domain absolute URLs in your CSS files.
* Avoid @import! Simply list all your CSS files in the HTML, they'll be combined anyway.
Why another static file combiner for django?
********************************************
Short version: None of them did exactly what I needed.
Long version:
**JS/CSS belong in the templates**
Every static combiner for django I've seen makes you configure
your static files in your settings.py. While that works, it doesn't make
sense. Static files are for display. And it's not even an option if your
settings are in completely different repositories and use different deploy
processes from the templates that depend on them.
**Flexibility**
django_compressor doesn't care if different pages use different combinations
of statics. It doesn't care if you use inline scripts or styles. It doesn't
get in the way.
**Automatic regeneration and cache-foreverable generated output**
Statics are never stale and browsers can be told to cache the output forever.
**Full test suite**
I has one.
Settings
********
Django compressor has a number of settings that control it's behavior.
They've been given sensible defaults.
``COMPRESS``
------------
:Default: the opposite of ``DEBUG``
Boolean that decides if compression will happen.
``COMPRESS_URL``
----------------
:Default: ``MEDIA_URL``
Controls the URL that linked media will be read from and compressed media
will be written to.
``COMPRESS_ROOT``
-----------------
:Default: ``MEDIA_ROOT``
Controls the absolute file path that linked media will be read from and
compressed media will be written to.
``COMPRESS_OUTPUT_DIR``
-----------------------
:Default: ``'CACHE'``
Controls the directory inside `COMPRESS_ROOT` that compressed files will
be written to.
``COMPRESS_CSS_FILTERS``
------------------------
:Default: ``['compressor.filters.css_default.CssAbsoluteFilter']``
A list of filters that will be applied to CSS.
``COMPRESS_JS_FILTERS``
-----------------------
:Default: ``['compressor.filters.jsmin.JSMinFilter']``
A list of filters that will be applied to javascript.
``COMPRESS_STORAGE``
--------------------
:Default: ``'compressor.storage.CompressorFileStorage'``
The dotted path to a Django Storage backend to be used to save the
compressed files.
``COMPRESS_PARSER``
--------------------
:Default: ``'compressor.parser.BeautifulSoupParser'``
The backend to use when parsing the JavaScript or Stylesheet files.
The backends included in ``compressor``:
- ``compressor.parser.BeautifulSoupParser``
- ``compressor.parser.LxmlParser``
See `Dependencies`_ for more info about the packages you need for each parser.
``COMPRESS_CACHE_BACKEND``
--------------------------
:Default: ``"default"`` or ``CACHE_BACKEND``
The backend to use for caching, in case you want to use a different cache
backend for compressor.
If you have set the ``CACHES`` setting (new in Django 1.3),
``COMPRESS_CACHE_BACKEND`` defaults to ``"default"``, which is the alias for
the default cache backend. You can set it to a different alias that you have
configured in your ``CACHES`` setting.
If you have not set ``CACHES`` and are still using the old ``CACHE_BACKEND``
setting, ``COMPRESS_CACHE_BACKEND`` defaults to the ``CACHE_BACKEND`` setting.
``COMPRESS_REBUILD_TIMEOUT``
----------------------------
:Default: ``2592000`` (30 days in seconds)
The period of time after which the the compressed files are rebuilt even if
no file changes are detected.
``COMPRESS_MINT_DELAY``
------------------------
:Default: ``30`` (seconds)
The upper bound on how long any compression should take to run. Prevents
dog piling, should be a lot smaller than ``COMPRESS_REBUILD_TIMEOUT``.
``COMPRESS_MTIME_DELAY``
------------------------
:Default: ``None``
The amount of time (in seconds) to cache the result of the check of the
modification timestamp of a file. Disabled by default. Should be smaller
than ``COMPRESS_REBUILD_TIMEOUT`` and ``COMPRESS_MINT_DELAY``.
Dependencies
************
* BeautifulSoup_ (for the default ``compressor.parser.BeautifulSoupParser``)
::
pip install BeautifulSoup
* lxml_ (for the optional ``compressor.parser.LxmlParser``, requires libxml2_)
::
STATIC_DEPS=true pip install lxml
.. _BeautifulSoup: http://www.crummy.com/software/BeautifulSoup/
.. _lxml: http://codespeak.net/lxml/
.. _libxml2: http://xmlsoft.org/

170
docs/make.bat Normal file
View File

@@ -0,0 +1,170 @@
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\django-compressor.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\django-compressor.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end

130
setup.py
View File

@@ -1,39 +1,121 @@
import os
from distutils.core import setup
import sys
from fnmatch import fnmatchcase
from distutils.util import convert_path
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
# Provided as an attribute, so you can append to these instead
# of replicating them:
standard_exclude = ('*.py', '*.pyc', '*$py.class', '*~', '.*', '*.bak')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build',
'./dist', 'EGG-INFO', '*.egg-info')
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
# Note: you may want to copy this into your setup.py file verbatim, as
# you can't import this from another package, when you don't know if
# that package is installed yet.
def find_package_data(
where='.', package='',
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{'package': [files]}
Where ``files`` is a list of all the files in that package that
don't match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are not packages won't be included (but directories under packages
will).
Directories matching any pattern in ``exclude_directories`` will
be ignored; by default directories with leading ``.``, ``CVS``,
and ``_darcs`` will be ignored.
If ``show_ignored`` is true, then all the files that aren't
included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive.
"""
out = {}
stack = [(convert_path(where), '', package, only_in_packages)]
while stack:
where, prefix, package, only_in_packages = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"Directory %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
if (os.path.isfile(os.path.join(fn, '__init__.py'))
and not prefix):
if not package:
new_package = name
else:
new_package = package + '.' + name
stack.append((fn, '', new_package, False))
else:
stack.append((fn, prefix + name + '/', package, only_in_packages))
elif package or not only_in_packages:
# is a file
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"File %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
out.setdefault(package, []).append(prefix+name)
return out
README = read('README.rst')
setup(
name = "django_compressor",
version = "0.6a6",
url = 'http://github.com/mintchaos/django_compressor',
version = "0.6a8",
url = 'http://django_compressor.readthedocs.org/',
license = 'BSD',
description = "Compresses linked and inline javascript or CSS into a single cached file.",
long_description = README,
author = 'Christian Metts',
author_email = 'xian@mintchaos.com',
packages = [
'compressor',
'compressor.conf',
'compressor.filters',
'compressor.filters.jsmin',
'compressor.filters.cssmin',
'compressor.templatetags',
'compressor.management',
'compressor.management.commands',
],
package_data = {
'compressor': [
'templates/compressor/*.html',
],
},
requires = [
author = 'Jannis Leidel',
author_email = 'jannis@leidel.info',
packages = find_packages(),
package_data = find_package_data('compressor'),
install_requires = [
'BeautifulSoup',
],
tests_require = [
'Django', 'lxml', 'BeautifulSoup',
],
classifiers = [
'Development Status :: 4 - Beta',
'Framework :: Django',
@@ -42,5 +124,7 @@ setup(
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP',
]
],
test_suite='compressor.tests.runtests.runtests',
zip_safe = False,
)

View File

View File

@@ -1,16 +0,0 @@
#!/usr/bin/env python
from django.core.management import execute_manager
import sys
# Give tests/manage.py access to django-compress
from os.path import dirname, abspath
sys.path += [dirname(dirname(abspath(__file__)))]
try:
import settings # Assumed to be in the same directory.
except ImportError:
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)

View File

@@ -1,26 +0,0 @@
import sys
from os.path import dirname, abspath, join
TEST_DIR = dirname(abspath(__file__))
DEBUG = True
ROOT_URLCONF = 'urls'
MEDIA_URL = '/media/'
MEDIA_ROOT = join(TEST_DIR, 'media')
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = 'django_compressor_tests.db'
INSTALLED_APPS = [
'core',
'compressor',
]
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
)
TEMPLATE_DIRS = (
join(TEST_DIR, 'templates'),
)

View File

27
tox.ini Normal file
View File

@@ -0,0 +1,27 @@
[tox]
envlist =
py25, py26, py27, py25-trunk, py26-trunk, py27-trunk
[testenv]
commands =
python setup.py test
deps =
django==1.2.4
# We lied here, these are not really trunk, but rather the 1.3 beta-1, which
# is close enough.
[testenv:py25-trunk]
basepython = python2.5
deps =
http://www.djangoproject.com/download/1.3-beta-1/tarball/
[testenv:py26-trunk]
basepython = python2.6
deps =
http://www.djangoproject.com/download/1.3-beta-1/tarball/
[testenv:py27-trunk]
basepython = python2.7
deps =
http://www.djangoproject.com/download/1.3-beta-1/tarball/