pax_global_header 0000666 0000000 0000000 00000000064 12674562234 0014525 g ustar 00root root 0000000 0000000 52 comment=3c041b63bd041379efca6ae7519e901daaa63bfd
libsass-python-0.11.0/ 0000775 0000000 0000000 00000000000 12674562234 0014563 5 ustar 00root root 0000000 0000000 libsass-python-0.11.0/.ackrc 0000664 0000000 0000000 00000000103 12674562234 0015641 0 ustar 00root root 0000000 0000000 --ignore-dir=.tox
--ignore-dir=build
--ignore-dir=libsass.egg-info
libsass-python-0.11.0/.coveragerc 0000664 0000000 0000000 00000001146 12674562234 0016706 0 ustar 00root root 0000000 0000000 [run]
parallel = True
branch = True
source = $PWD
data_file = $PWD/.coverage
omit =
.tox/*
/usr/*
*/tmp*
*/setup.py
*/upload_appveyor_builds.py
[report]
show_missing = True
exclude_lines =
# Have to re-enable the standard pragma
\#\s*pragma: no cover
# Don't complain if tests don't hit defensive assertion code:
^\s*raise AssertionError\b
^\s*raise NotImplementedError\b
^\s*return NotImplemented\b
^\s*raise TypeError\b
^\s*raise$
# Don't complain if non-runnable code isn't run:
^if __name__ == ['"]__main__['"]:$
[html]
directory = coverage-html
libsass-python-0.11.0/.gitignore 0000664 0000000 0000000 00000000305 12674562234 0016551 0 ustar 00root root 0000000 0000000 *.egg
*.egg-info
*.pyc
*.pyd
*.so
.*.swp
.DS_Store
._.DS_Store
.coverage
.tox
/.libsass-upstream-version
build/
dist/
docs/_build
testpkg/build/
testpkg/dist/
testpkg/testpkg/static/css/*.scss.css
libsass-python-0.11.0/.gitmodules 0000664 0000000 0000000 00000000115 12674562234 0016735 0 ustar 00root root 0000000 0000000 [submodule "libsass"]
path = libsass
url = git://github.com/sass/libsass.git
libsass-python-0.11.0/.travis.yml 0000664 0000000 0000000 00000000503 12674562234 0016672 0 ustar 00root root 0000000 0000000 language: python
python:
- pypy
- pypy3
- 2.6
- 2.7
- 3.3
- 3.4
- 3.5
install:
- pip install -rrequirements-dev.txt coveralls
script:
- COVERAGE_PROCESS_START=$PWD/.coveragerc py.test sasstests.py
- coverage combine
- coverage report
- flake8 .
after_success:
- coveralls
cache:
directories:
- $HOME/.cache/pip
libsass-python-0.11.0/CONTRIBUTING.rst 0000664 0000000 0000000 00000005031 12674562234 0017223 0 ustar 00root root 0000000 0000000 Contributor's guide
===================
Coding style
------------
- Follow `PEP 8`_. flake8_ would help.
- Order imports by lexicographical order.
- Prefer relative imports.
- All functions, classes, methods, attributes, and modules should have
the docstring.
- Functions and methods should contain ``:param:``, ``:type:``
(``:return:``, ``:rtype`` if it returns something),
(``:raise:`` if it may raise an error) in their docstring.
.. _flake8: https://gitlab.com/pycqa/flake8
.. _PEP 8: www.python.org/dev/peps/pep-0008
Tests
-----
- All code patches should contain one or more unit tests or regression tests.
- All code patches have to successfully run tests on every Python version
we aim to support. tox_ would help.
- All commits will be tested by Travis_ (Linux) and
AppVeyor_ (Windows).
.. _tox: http://tox.testrun.org/
.. _Travis: http://travis-ci.org/dahlia/libsass-python
.. _AppVeyor: https://ci.appveyor.com/project/dahlia/libsass-python
Maintainer's guide
==================
Releasing
---------
Here's a brief check list for releasing a new version:
- Double check if the version is correctly bumped.
You can bump the version by changing ``__version__`` in sass.py file.
Note that it might be already bumped by other maintainers,
so check what's the latest release version from PyPI_.
- The changelog has to be complete, and frozen.
"To be released" sentence has to be replaced by the actual release date.
- If the code freeze for the release is done (including version bump),
tag the commit using ``git tag`` command. The tag name has to simply be
the version name e.g. ``1.2.3``. Of course, the tag also has to be pushed
to the upstream repository.
- Make a source distribution and upload it to PyPI
(``python3 setup.py sdist upload``).
If it's successful the new version must appear on PyPI_.
- AppVeyor_ automatically makes binary wheels for Windows, but each CI build
takes longer than an hour. These wheels are not automatically uploaded,
but there's upload_appveyor_builds.py script that downloads built wheels and
uploads them to PyPI.
- The `docs website`__ also has to be updated.
It's currently a static website deployed on GitHub Pages.
Use ``python setup.py upload_doc`` command.
Although it seems possible to be automated using Travis.
- Manually create a release through https://github.com/dahlia/libsass-python/releases/
Ping Hong Minhee (hongminhee@member.fsf.org, @dahlia on GitHub) if you need
any help!
.. _PyPI: https://pypi.python.org/pypi/libsass
__ http://hongminhee.org/libsass-python/
libsass-python-0.11.0/LICENSE 0000664 0000000 0000000 00000002070 12674562234 0015567 0 ustar 00root root 0000000 0000000 Copyright (c) 2015 Hong Minhee
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.
libsass-python-0.11.0/MANIFEST.in 0000664 0000000 0000000 00000000336 12674562234 0016323 0 ustar 00root root 0000000 0000000 recursive-include libsass *.c
recursive-include libsass *.cpp
recursive-include libsass *.h
recursive-include libsass *.hpp
include libsass/Makefile
include .libsass-upstream-version
include test/*.scss
include README.rst
libsass-python-0.11.0/Makefile 0000664 0000000 0000000 00000002677 12674562234 0016237 0 ustar 00root root 0000000 0000000 # This is to speed up development time.
# Usage:
# Needed once:
# $ virtualenv venv
# $ . venv/bin/activate
# $ pip install -e .`
# $ pip install werkzeug
# Once that is done, to rebuild simply:
# $ make -j 4 && python -m unittest sasstests
PY_HEADERS := -I/usr/include/python2.7
C_SOURCES := $(wildcard libsass/src/*.c)
C_OBJECTS = $(patsubst libsass/src/%.c,build2/libsass/c/%.o,$(C_SOURCES))
CPP_SOURCES := $(wildcard libsass/src/*.cpp)
CPP_OBJECTS = $(patsubst libsass/src/%.cpp,build2/libsass/cpp/%.o,$(CPP_SOURCES))
LIBSASS_VERSION = $(shell git -C libsass describe --abbrev=4 --dirty --always --tags)
BASEFLAGS := -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -fPIC -I./libsass/include $(PY_HEADERS) -Wno-parentheses -Werror=switch -DLIBSASS_VERSION='"$(LIBSASS_VERSION)"'
CFLAGS := $(BASEFLAGS) -Wstrict-prototypes
CPPFLAGS := $(BASEFLAGS) -std=c++0x
LFLAGS := -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fPIC -lstdc++
all: _sass.so
build2/libsass/c/%.o: libsass/src/%.c
@mkdir -p build2/libsass/c/
gcc $(CFLAGS) -c $^ -o $@
build2/libsass/cpp/%.o: libsass/src/%.cpp
@mkdir -p build2/libsass/cpp/
gcc $(CPPFLAGS) -c $^ -o $@
build2/pysass.o: pysass.cpp
@mkdir -p build2
gcc $(CPPFLAGS) -Wno-write-strings -c $^ -o $@
_sass.so: $(C_OBJECTS) $(CPP_OBJECTS) build2/pysass.o
g++ $(LFLAGS) $^ -o $@
.PHONY: clean
clean:
rm -rf build2 _sass.so
libsass-python-0.11.0/README.rst 0000664 0000000 0000000 00000006123 12674562234 0016254 0 ustar 00root root 0000000 0000000 libsass-python: Sass_/SCSS for Python
=====================================
.. image:: https://badge.fury.io/py/libsass.svg
:alt: PyPI
:target: https://pypi.python.org/pypi/libsass
.. image:: https://travis-ci.org/dahlia/libsass-python.svg?branch=python
:target: https://travis-ci.org/dahlia/libsass-python
:alt: Build Status
.. image:: https://ci.appveyor.com/api/projects/status/yghrs9jw7b67c0ia/branch/python?svg=true
:target: https://ci.appveyor.com/project/dahlia/libsass-python
:alt: Build Status (Windows)
.. image:: https://img.shields.io/coveralls/dahlia/libsass-python/python.svg
:target: https://coveralls.io/r/dahlia/libsass-python
:alt: Coverage Status
This package provides a simple Python extension module ``sass`` which is
binding Libsass_ (written in C/C++ by Hampton Catlin and Aaron Leung).
It's very straightforward and there isn't any headache related Python
distribution/deployment. That means you can add just ``libsass`` into
your ``setup.py``'s ``install_requires`` list or ``requirements.txt`` file.
Need no Ruby nor Node.js.
It currently supports CPython 2.6, 2.7, 3.3--3.5, and PyPy 2.3+!
.. _Sass: http://sass-lang.com/
.. _Libsass: https://github.com/sass/libsass
Features
--------
- You don't need any Ruby/Node.js stack at all, for development or deployment
either.
- Fast. (Libsass_ is written in C++.)
- Simple API. See the below example code for details.
- Custom functions.
- ``@import`` callbacks.
- Support both tabbed (Sass) and braces (SCSS) syntax.
- WSGI middleware for ease of development.
It automatically compiles Sass/SCSS files for each request.
- ``setuptools``/``distutils`` integration.
You can build all Sass/SCSS files using
``setup.py build_sass`` command.
- Works also on PyPy.
- Provides prebuilt wheel_ binaries for Windows and Mac.
.. _wheel: https://www.python.org/dev/peps/pep-0427/
Install
-------
It's available on PyPI_, so you can install it using ``pip`` (or
``easy_install``):
.. code-block:: console
$ pip install libsass
.. note::
libsass requires some features introduced by the recent C++ standard.
You need a C++ compiler that support those features.
See also libsass project's README_ file.
.. _PyPI: https://pypi.python.org/pypi/libsass
.. _README: https://github.com/sass/libsass#readme
.. _example:
Example
-------
.. code-block:: pycon
>>> import sass
>>> print sass.compile(string='a { b { color: blue; } }')
a b {
color: blue; }
Docs
----
There's the user guide manual and the full API reference for ``libsass``:
http://hongminhee.org/libsass-python/
You can build the docs by yourself:
.. code-block:: console
$ cd docs/
$ make html
The built docs will go to ``docs/_build/html/`` directory.
Credit
------
Hong Minhee wrote this Python binding of Libsass_.
Hampton Catlin and Aaron Leung wrote Libsass_, which is portable C/C++
implementation of SASS_.
Hampton Catlin originally designed SASS_ language and wrote the first
reference implementation of it in Ruby.
The above three softwares are all distributed under `MIT license`_.
.. _MIT license: http://mit-license.org/
libsass-python-0.11.0/appveyor.yml 0000664 0000000 0000000 00000001535 12674562234 0017157 0 ustar 00root root 0000000 0000000 version: "{build}"
environment:
matrix:
- PYTHON: "C:\\Python27"
PYTHON_ARCH: 32
- PYTHON: "C:\\Python27-x64"
PYTHON_ARCH: 64
- PYTHON: "C:\\Python34"
PYTHON_ARCH: 32
- PYTHON: "C:\\Python34-x64"
PYTHON_ARCH: 32
- PYTHON: "C:\\Python35"
PYTHON_ARCH: 32
- PYTHON: "C:\\Python35-x64"
PYTHON_ARCH: 64
matrix:
fast_finish: true
init:
- "ECHO %PATH%"
- "ECHO %PYTHON%"
- ps: "ls C:/Python*"
install:
- "git submodule update --init"
- "%PYTHON%\\Scripts\\pip.exe --version"
- "%PYTHON%\\Scripts\\pip.exe install -rrequirements-dev.txt wheel"
build: false
test_script:
- '%PYTHON%\\python.exe -c "import os, pprint; pprint.pprint(sorted(os.environ.items()))"'
- "%PYTHON%\\python.exe -m pytest sasstests.py"
after_test:
- "%PYTHON%\\python.exe setup.py bdist_wheel"
artifacts:
- path: dist\*
cache:
- '%LOCALAPPDATA%\pip\cache'
libsass-python-0.11.0/docs/ 0000775 0000000 0000000 00000000000 12674562234 0015513 5 ustar 00root root 0000000 0000000 libsass-python-0.11.0/docs/Makefile 0000664 0000000 0000000 00000012700 12674562234 0017153 0 ustar 00root root 0000000 0000000 # 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) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where 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 " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@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/libsass.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/libsass.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/libsass"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/libsass"
@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."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
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."
libsass-python-0.11.0/docs/changes.rst 0000664 0000000 0000000 00000032113 12674562234 0017655 0 ustar 00root root 0000000 0000000 Changelog
=========
Version 0.11.0
--------------
Released on March 23, 2016.
- Follow up the libsass upstream: 3.3.4 --- See the release notes of Libsass
3.3.4__. [:issue:`144` by Anthony Sottile]
- Expose libsass version in `sassc --version` and `sass.libsass_version`
[:issue:`142` :issue:`141` :issue:`140` by Anthony Sottile]
- Fix warning about unused enum on switch [:issue:`127` :issue:`131` by
Anthony Sottile]
- Sourcemaps no longer imply source comments [:issue:`124` :issue:`130` by
Tim Tisdall]
- Add `--source-comments` option to `sassc` [:issue:`124` :issue:`130` by
Anthony Sottile]
- Improve formatting of `CompileError` under python3 [:issue:`123` by Anthony
Sottile]
- Raise when compiling a directory which does not exist [:issue:`116`
:issue:`119` by Anthony Sottile]
__ https://github.com/sass/libsass/releases/tag/3.3.4
Version 0.10.1
--------------
Released on January 29, 2016.
- Follow up the libsass upstream: 3.3.3 --- See the release notes of Libsass
3.3.3__. [by Anthony Sottile]
- Allow -t for style like sassc [:issue:`98` by Anthony Sottile]
__ https://github.com/sass/libsass/releases/tag/3.3.3
Version 0.10.0
--------------
Released on December 15, 2015.
- Support custom import callbacks [:issue:`81` by Alice Zoë Bevan–McGregor,
Anthony Sottile]
- Disallow arbitrary kwargs in compile() [:issue:`109` by Anthony Sottile]
Version 0.9.3
-------------
Released on December 03, 2015.
- Support "indented" SASS compilation [:issue:`41` by Alice Zoë Bevan–McGregor]
- Fix wheels on windows [:issue:`28` :issue:`49` by Anthony Sottile]
Version 0.9.2
-------------
Released on November 12, 2015.
- Follow up the libsass upstream: 3.3.2 --- See the release notes of Libsass
3.3.2__. [by Anthony Sottile]
- Require VS 2015 to build on windows [:issue:`99` by Anthony Sottile]
__ https://github.com/sass/libsass/releases/tag/3.3.2
Version 0.9.1
-------------
Released on October 29, 2015.
- Follow up the libsass upstream: 3.3.1 --- See the release notes of Libsass
3.3.1__. [by Anthony Sottile]
__ https://github.com/sass/libsass/releases/tag/3.3.1
Version 0.9.0
-------------
Released on October 28, 2015.
- Fix a bug with writing UTF-8 to a file [:issue:`72` by Caleb Ely]
- Fix a segmentation fault on ^C [:issue:`87` by Anthony Sottile]
- Follow up the libsass upstream: 3.3.0 --- See the release notes of Libsass
3.3.0__. [:issue:`96` by Anthony Sottile]
__ https://github.com/sass/libsass/releases/tag/3.3.0
Version 0.8.3
-------------
Released on August 2, 2015.
- Follow up the libsass upstream: 3.2.5 --- See the release notes of Libsass
3.2.5__. [:issue:`79`, :issue:`80` by Anthony Sottile]
- Fixed a bug that :file:`*.sass` files were ignored.
[:issue:`78` by Guilhem MAS-PAITRAULT]
__ https://github.com/sass/libsass/releases/tag/3.2.5
Version 0.8.2
-------------
Released on May 19, 2015.
- Follow up the libsass upstream: 3.2.4 --- See the release notes of Libsass
3.2.3__, and 3.2.4__. [:issue:`69` by Anthony Sottile]
- The default value of :class:`~sassutils.wsgi.SassMiddleware`'s
``error_status`` parameter was changed from ``'500 Internal Server Error'``
to ``'200 OK'`` so that Mozilla Firefox can render the error message well.
[:issue:`67`, :issue:`68`, :issue:`70` by zxv]
__ https://github.com/sass/libsass/releases/tag/3.2.3
__ https://github.com/sass/libsass/releases/tag/3.2.4
Version 0.8.1
-------------
Released on May 14, 2015.
- Fixed a bug that there was no ``'expanded'`` in :const:`sass.OUTPUT_STYLES`
but ``'expected'`` instead which is a typo. [:issue:`66` by Triangle717]
- Fixed broken FreeBSD build. [:issue:`65` by Toshiharu Moriyama]
Version 0.8.0
-------------
Released on May 3, 2015.
- Follow up the libsass upstream: 3.2.2 --- See the release notes of Libsass
3.2.0__, 3.2.1__, and 3.2.2__.
[:issue:`61`, :issue:`52`, :issue:`56`, :issue:`58`, :issue:`62`, :issue:`64`
by Anthony Sottile]
- Compact and expanded output styles [:issue:`37`]
- Strings and interpolation closer to Ruby Sass
- The correctness of the generated sourcemap files
- Directive buddling
- Full support for the ``@at-root`` directive
- Full support for ``!global`` variable scoping
- Now underscored files are ignored when compiling a directory.
[:issue:`57` by Anthony Sottile]
- Fixed broken FreeBSD build. [:issue:`34`, :issue:`60` by Ilya Baryshev]
- :class:`~sassutils.wsgi.SassMiddleware` became to log syntax errors
if exist during compilation to ``sassutils.wsgi.SassMiddleware`` logger
with level ``ERROR``. [:issue:`42`]
__ https://github.com/sass/libsass/releases/tag/3.2.0
__ https://github.com/sass/libsass/releases/tag/3.2.1
__ https://github.com/sass/libsass/releases/tag/3.2.2
Version 0.7.0
-------------
Released on March 6, 2015.
Anthony Sottile contributed to the most of this release. Huge thanks to him!
- Follow up the libsass upstream: 3.1.0 --- See the `release note`__ of Libsass.
[:issue:`38`, :issue:`43` by Anthony Sottile]
- Custom functions and imports
- Decrementing in ``@for`` loops
- ``@debug`` and ``@error``
- ``not`` operator
- ``nth()`` for maps
- ``inspect()``
- ``feature-exists()``
- ``unique-id()``
- ``random()``
- Added custom functions support. [:issue:`13`, :issue:`44` by Anthony Sottile]
- Added :class:`sass.SassFunction` class.
- Added ``custom_functions`` parameter to :func:`sass.compile()` function.
- Added data types for custom functions:
- :class:`sass.SassNumber`
- :class:`sass.SassColor`
- :class:`sass.SassList`
- :class:`sass.SassMap`
- :class:`sass.SassError`
- :class:`sass.SassWarning`
- Added ``precision`` parameter to :func:`sass.compile()` function.
[:issue:`39` by Andrea Stagi]
- :program:`sassc` has a new :option:`-p `/:option:`--precision
` option. [:issue:`39` by Andrea Stagi]
__ https://github.com/sass/libsass/releases/tag/3.1.0
Version 0.6.2
-------------
Released on November 25, 2014.
Although 0.6.0--0.6.1 have needed GCC (G++) 4.8+, LLVM Clang 3.3+,
now it became back to only need GCC (G++) 4.6+, LLVM Clang 2.9+,
or Visual Studio 2013 Update 4+.
- Follow up the libsass upstream: 3.0.2 --- See the `release note`__ of libsass.
[:issue:`33` by Rodolphe Pelloux-Prayer]
- Fixed a bug that :program:`sassc --watch` crashed when a file is not
compilable on the first try. [:issue:`32` by Alan Justino da Silva]
- Fixed broken build on Windows.
__ https://github.com/sass/libsass/releases/tag/3.0.2
Version 0.6.1
-------------
Released on November 6, 2014.
- Follow up the libsass upstream: 3.0.1 --- See the `release note`__ of Libsass.
- Fixed a bug that :class:`~sassutils.wsgi.SassMiddleware` never closes
the socket on some WSGI servers e.g. ``eventlet.wsgi``.
__ https://github.com/sass/libsass/releases/tag/3.0.1
Version 0.6.0
-------------
Released on October 27, 2014.
Note that since libsass-python 0.6.0 (and libsass 3.0) it requires C++11
to compile. Although 0.6.2 became back to only need GCC (G++) 4.6+,
LLVM Clang 2.9+, from 0.6.0 to 0.6.1 you need GCC (G++) 4.8+, LLVM Clang 3.3+,
or Visual Studio 2013 Update 4+.
- Follow up the libsass upstream: 3.0 --- See the `release note`__ of Libsass.
- Decent extends support
- Basic Sass Maps Support
- Better UTF-8 Support
- ``call()`` function
- Better Windows Support
- Spec Enhancements
- Added missing `partial import`_ support. [:issue:`27` by item4]
- :const:`~sass.SOURCE_COMMENTS` became deprecated.
- :func:`sass.compile()`'s parameter ``source_comments`` now can take only
:const:`bool` instead of :const:`str`. String values like ``'none'``,
``'line_numbers'``, and ``'map'`` become deprecated, and will be obsolete
soon.
- :func:`~sassutils.builder.build_directory()` function has a new optional
parameter ``output_style``.
- :meth:`~sassutils.builder.Build.build()` method has a new optional
parameter ``output_style``.
- Added ``--output-style``/``-s`` option to
:class:`~sassutils.distutils.build_sass` command. [:issue:`25`]
__ https://github.com/sass/libsass/releases/tag/3.0
.. _partial import: http://sass-lang.com/documentation/file.SASS_REFERENCE.html#partials
Version 0.5.1
-------------
Released on September 23, 2014.
- Fixed a bug that :class:`~sassutils.wsgi.SassMiddleware` yielded
:class:`str` instead of :class:`bytes` on Python 3.
- Fixed several Unicode-related bugs on Windows.
- Fixed a bug that :func:`~sassutils.builder.build_directory()`,
:class:`~sassutils.wsgi.SassMiddleware`, and
:class:`~sassutils.distutils.build_sass` don't recursively build
subdirectories.
Version 0.5.0
-------------
Released on June 6, 2014.
- Follow up the libsass upstream: 2.0 --- See the `release note`__ of Libsass.
- Added indented syntax support (:file:`*.sass` files).
- Added expanded selector support (BEM).
- Added string functions.
- Fixed UTF-8 support.
- Backward incompatibility: broken extends.
__ https://github.com/sass/libsass/releases/tag/v2.0
Unstable version 0.4.2.20140529.cd3ee1cbe3
------------------------------------------
Released on May 29, 2014.
- Version scheme changed to use periods (``.``) instead of hyphens (``-``)
due to setuptools seems to treat hyphens special.
- Fixed malformed packaging that doesn't correctly preserve the package name
and version.
Unstable Version 0.4.2-20140528-cd3ee1cbe3
------------------------------------------
Released on May 28, 2014.
- Follow up the libsass upstream:
:upcommit:`cd3ee1cbe34d5316eb762a43127a3de9575454ee`.
Version 0.4.2
-------------
Released on May 22, 2014.
- Fixed build failing on Mac OS X 10.8 or earlier. [:issue:`19`]
- Fixed :exc:`UnicodeEncodeError` that :meth:`Manifest.build_one()
` method rises when the input source
contains any non-ASCII Unicode characters.
Version 0.4.1
-------------
Released on May 20, 2014.
- Fixed :exc:`UnicodeEncodeError` that rise when the input source contains
any non-ASCII Unicode characters.
Version 0.4.0
-------------
Released on May 6, 2014.
- :program:`sassc` has a new :option:`-w `/:option:`--watch
` option.
- Expose source maps support:
- :program:`sassc` has a new :option:`-m `/:option:`-g
`/:option:`--sourcemap ` option.
- :class:`~sassutils.wsgi.SassMiddleware` now also creates source map files
with filenames followed by :file:`.map` suffix.
- :meth:`Manifest.build_one() ` method
has a new ``source_map`` option. This option builds also a source map
file with the filename followed by :file:`.map` suffix.
- :func:`sass.compile()` has a new optional parameter ``source_comments``.
It can be one of :const:`sass.SOURCE_COMMENTS` keys. It also has
a new parameter ``source_map_filename`` which is required only when
``source_comments='map'``.
- Fixed Python 3 incompatibility of :program:`sassc` program.
- Fixed a bug that multiple ``include_paths`` doesn't work on Windows.
Version 0.3.0
-------------
Released on February 21, 2014.
- Added support for Python 3.3. [:issue:`7`]
- Dropped support for Python 2.5.
- Fixed build failing on Mac OS X.
[:issue:`4`, :issue:`5`, :issue:`6` by Hyungoo Kang]
- Now builder creates target recursive subdirectories even if it doesn't
exist yet, rather than siliently fails.
[:issue:`8`, :issue:`9` by Philipp Volguine]
- Merged recent changes from libsass 1.0.1: `57a2f62--v1.0.1`_.
- Supports `variable arguments`_.
- Supports sourcemaps.
.. _57a2f62--v1.0.1: https://github.com/sass/libsass/compare/57a2f627b4d2fbd3cf1913b241f1d5aa31e35580...v1.0.1
.. _variable arguments: http://sass-lang.com/docs/yardoc/file.SASS_CHANGELOG.html#variable_arguments
Version 0.2.4
-------------
Released on December 4, 2012.
- Added :mod:`sassc` CLI executable script.
- Added :const:`sass.OUTPUT_STYLES` constant map.
- Merged recent changes from libsass upstream:
`e997102--a84b181`__.
__ https://github.com/sass/libsass/compare/e9971023785dabd41aa44f431f603f62b15e6017...a84b181a6e59463c0ac9796ca7fdaf4864f0ad84
Version 0.2.3
-------------
Released on October 24, 2012.
- :mod:`sassutils.distutils`: Prevent double monkey patch of ``sdist``.
- Merged upstream changes of libsass.
Version 0.2.2
-------------
Released on September 28, 2012.
- Fixed a link error on PyPy and Linux.
- Fixed build errors on Windows.
Version 0.2.1
-------------
Released on September 12, 2012.
- Support Windows.
Version 0.2.0
-------------
Released on August 24, 2012.
- Added new :mod:`sassutils` package.
- Added :mod:`sassutils.builder` module to build the whole directory
at a time.
- Added :mod:`sassutils.distutils` module for :mod:`distutils` and
:mod:`setuptools` integration.
- Added :mod:`sassutils.wsgi` module which provides a development-purpose
WSGI middleware.
- Added :class:`~sassutils.distutils.build_sass` command for
:mod:`distutils`/:mod:`setuptools`.
Version 0.1.1
-------------
Released on August 18, 2012.
- Fixed segmentation fault for reading ``filename`` which does not exist.
Now it raises a proper ``exceptions.IOError`` exception.
Version 0.1.0
-------------
Released on August 17, 2012. Initial version.
libsass-python-0.11.0/docs/conf.py 0000664 0000000 0000000 00000020437 12674562234 0017020 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# libsass documentation build configuration file, created by
# sphinx-quickstart on Sun Aug 19 22:45:57 2012.
#
# 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 os
import sys
import warnings
# 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('..'))
import sass
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.3'
# 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.intersphinx',
'sphinx.ext.extlinks']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'libsass'
copyright = u'2012, Hong Minhee'
# 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. (Parse setup.py script.)
version = sass.__version__
# The full version, including alpha/beta/rc tags.
release = version
# 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 = 'sphinx'
# 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 = 'alabaster'
# 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 = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v 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 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 = 'libsassdoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'libsass.tex', u'libsass Documentation',
u'Hong Minhee', '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
# 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', 'libsass', u'libsass Documentation',
[u'Hong Minhee'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'libsass', u'libsass Documentation',
u'Hong Minhee', 'libsass', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {
'python': ('http://docs.python.org/', None),
'setuptools': ('http://pythonhosted.org/setuptools/', None),
'flask': ('http://flask.pocoo.org/docs/', None)
}
extlinks = {
'issue': ('https://github.com/dahlia/libsass-python/issues/%s', '#'),
'branch': ('https://github.com/dahlia/libsass-python/compare/master...%s',
''),
'commit': ('https://github.com/dahlia/libsass-python/commit/%s', ''),
'upcommit': ('https://github.com/sass/libsass/commit/%s', ''),
}
libsass-python-0.11.0/docs/frameworks/ 0000775 0000000 0000000 00000000000 12674562234 0017673 5 ustar 00root root 0000000 0000000 libsass-python-0.11.0/docs/frameworks/flask.rst 0000664 0000000 0000000 00000012264 12674562234 0021532 0 ustar 00root root 0000000 0000000 Using with Flask
================
This guide explains how to use libsass with Flask_ web framework.
:mod:`sassutils` package provides several tools that can be integrated
to web applications written in Flask.
.. _Flask: http://flask.pocoo.org/
.. contents::
Directory layout
----------------
Imagine the project contained in such directory layout:
- :file:`setup.py`
- :file:`myapp/`
- :file:`__init__.py`
- :file:`static/`
- :file:`sass/`
- :file:`css/`
- :file:`templates/`
SASS/SCSS files will go inside :file:`myapp/static/sass/` directory.
Compiled CSS files will go inside :file:`myapp/static/css/` directory.
CSS files can be regenerated, so add :file:`myapp/static/css/` into your
ignore list like :file:`.gitignore` or :file:`.hgignore`.
Defining manifest
-----------------
The :mod:`sassutils` defines a concept named :dfn:`manifest`.
Manifest is building settings of SASS/SCSS. It specifies some paths
related to building SASS/SCSS:
- The path of the directory which contains SASS/SCSS source files.
- The path of the directory compiled CSS files will go.
- The path, is exposed to HTTP (through WSGI), of the directory that
will contain compiled CSS files.
Every package may have their own manifest. Paths have to be relative
to the path of the package.
For example, in the project the package name is :mod:`myapp`.
The path of the package is :file:`myapp/`. The path of SASS/SCSS directory
is :file:`static/sass/` (relative to the package directory).
The path of CSS directory is :file:`static/css/`.
The exposed path is :file:`/static/css`.
This settings can be represented as the following manifests::
{
'myapp': ('static/sass', 'static/css', '/static/css')
}
As you can see the above, the set of manifests are represented in dictionary.
Keys are packages names. Values are tuples of paths.
Building SASS/SCSS for each request
-----------------------------------
.. seealso::
Flask --- `Hooking in WSGI Middlewares`__
The section which explains how to integrate WSGI middlewares to
Flask.
Flask --- :ref:`flask:app-dispatch`
The documentation which explains how Flask dispatch each
request internally.
__ http://flask.pocoo.org/docs/quickstart/#hooking-in-wsgi-middlewares
In development, to manually build SASS/SCSS files for each change is
so tiring. :class:`~sassutils.wsgi.SassMiddleware` makes the web
application to automatically build SASS/SCSS files for each request.
It's a WSGI middleware, so it can be plugged into the web app written in
Flask.
:class:`~sassutils.wsgi.SassMiddleware` takes two required parameters:
- The WSGI-compliant callable object.
- The set of manifests represented as dictionary.
So::
from flask import Flask
from sassutils.wsgi import SassMiddleware
app = Flask(__name__)
app.wsgi_app = SassMiddleware(app.wsgi_app, {
'myapp': ('static/sass', 'static/css', '/static/css')
})
And then, if you want to link a compiled CSS file, use :func:`~flask.url_for()`
function:
.. sourcecode:: html+jinja
.. note::
The linked filename is :file:`style.scss.css`, not just :file:`style.scss`.
All compiled filenames have trailing ``.css`` suffix.
Building SASS/SCSS for each deployment
--------------------------------------
.. note::
This section assumes that you use setuptools_ for deployment.
.. seealso::
Flask --- :ref:`flask:distribute-deployment`
How to deploy Flask application using setuptools_.
If libsass has been installed in the :file:`site-packages` (for example,
your virtualenv), :file:`setup.py` script also gets had new command
provided by libsass: :class:`~sassutils.distutils.build_sass`.
The command is aware of ``sass_manifests`` option of :file:`setup.py` and
builds all SASS/SCSS sources according to the manifests.
Add these arguments to :file:`setup.py` script::
setup(
# ...,
setup_requires=['libsass >= 0.6.0'],
sass_manifests={
'myapp': ('static/sass', 'static/css', '/static/css')
}
)
The ``setup_requires`` option makes sure that the libsass is installed
in :file:`site-packages` (for example, your virtualenv) before
:file:`setup.py` script. That means: if you run :file:`setup.py` script
and libsass isn't installed yet at the moment, it will automatically
install libsass first.
The ``sass_manifests`` specifies the manifests for libsass.
Now :program:`setup.py build_sass` will compile all SASS/SCSS files
in the specified path and generates compiled CSS files into the specified
path (according to the manifests).
If you use it with ``sdist`` or ``bdist`` command, a packed archive also
will contain compiled CSS files!
.. sourcecode:: console
$ python setup.py build_sass sdist
You can add aliases to make these commands to always run ``build_sass``
command before. Make :file:`setup.cfg` config:
.. sourcecode:: ini
[aliases]
sdist = build_sass sdist
bdist = build_sass bdist
Now it automatically builds SASS/SCSS sources and include compiled CSS files
to the package archive when you run :program:`setup.py sdist`.
.. _setuptools: https://pypi.python.org/pypi/setuptools
libsass-python-0.11.0/docs/index.rst 0000664 0000000 0000000 00000006773 12674562234 0017371 0 ustar 00root root 0000000 0000000 libsass-python: Sass_/SCSS for Python
=====================================
This package provides a simple Python extension module :mod:`sass` which is
binding Libsass_ (written in C/C++ by Hampton Catlin and Aaron Leung).
It's very straightforward and there isn't any headache related Python
distribution/deployment. That means you can add just ``libsass`` into
your :file:`setup.py`'s ``install_requires`` list or :file:`requirements.txt`
file.
It currently supports CPython 2.6, 2.7, 3.3--3.5, and PyPy 2.3+!
.. _SASS: http://sass-lang.com/
.. _Libsass: https://github.com/sass/libsass
Features
--------
- You don't need any Ruby/Node.js stack at all, for development or deployment
either.
- Fast. (Libsass_ is written in C++.)
- Simple API. See :ref:`example code ` for details.
- Custom functions.
- ``@import`` callbacks.
- Support both tabbed (Sass) and braces (SCSS) syntax.
- WSGI middleware for ease of development.
It automatically compiles Sass/SCSS files for each request.
See also :mod:`sassutils.wsgi` for details.
- :mod:`setuptools`/:mod:`distutils` integration.
You can build all Sass/SCSS files using
:program:`setup.py build_sass` command.
See also :mod:`sassutils.distutils` for details.
- Works also on PyPy.
- Provides prebuilt wheel (:pep:`427`) binaries for Windows and Mac.
Install
-------
It's available on PyPI_, so you can install it using :program:`pip`:
.. code-block:: console
$ pip install libsass
.. note::
libsass requires some features introduced by the recent C++ standard.
You need a C++ compiler that support those features.
See also libsass project's README_ file.
.. _PyPI: https://pypi.python.org/pypi/libsass
.. _README: https://github.com/sass/libsass#readme
.. _example:
Example
-------
>>> import sass
>>> sass.compile(string='a { b { color: blue; } }')
'a b {\n color: blue; }\n'
User's Guide
------------
.. toctree::
:maxdepth: 2
frameworks/flask
changes
References
----------
.. toctree::
:maxdepth: 2
sassc
sass
sassutils
Credit
------
Hong Minhee wrote this Python binding of Libsass_.
Hampton Catlin and Aaron Leung wrote Libsass_, which is portable C/C++
implementation of SASS_.
Hampton Catlin originally designed SASS_ language and wrote the first
reference implementation of it in Ruby.
The above three softwares are all distributed under `MIT license`_.
.. _MIT license: http://mit-license.org/
Open source
-----------
GitHub (Git repository + issues)
https://github.com/dahlia/libsass-python
Travis CI
https://travis-ci.org/dahlia/libsass-python
.. image:: https://travis-ci.org/dahlia/libsass-python.svg?branch=python
:target: https://travis-ci.org/dahlia/libsass-python
:alt: Build Status
AppVeyor (CI for Windows)
https://ci.appveyor.com/project/dahlia/libsass-python
.. image:: https://ci.appveyor.com/api/projects/status/yghrs9jw7b67c0ia/branch/python?svg=true
:target: https://ci.appveyor.com/project/dahlia/libsass-python
:alt: Build Status (Windows)
Coveralls (Test coverage)
https://coveralls.io/r/dahlia/libsass-python
.. image:: https://img.shields.io/coveralls/dahlia/libsass-python.svg
:target: https://coveralls.io/r/dahlia/libsass-python
:alt: Coverage Status
PyPI
https://pypi.python.org/pypi/libsass
.. image:: https://badge.fury.io/py/libsass.svg
:alt: PyPI
:target: https://pypi.python.org/pypi/libsass
Changelog
:doc:`changes`
Indices and tables
------------------
- :ref:`genindex`
- :ref:`modindex`
- :ref:`search`
libsass-python-0.11.0/docs/make.bat 0000664 0000000 0000000 00000011752 12674562234 0017126 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ 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. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
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\libsass.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\libsass.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" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
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
libsass-python-0.11.0/docs/sass.rst 0000664 0000000 0000000 00000000042 12674562234 0017212 0 ustar 00root root 0000000 0000000 .. automodule:: sass
:members:
libsass-python-0.11.0/docs/sassc.rst 0000664 0000000 0000000 00000000070 12674562234 0017356 0 ustar 00root root 0000000 0000000
.. program:: sassc
.. automodule:: sassc
:members:
libsass-python-0.11.0/docs/sassutils.rst 0000664 0000000 0000000 00000000207 12674562234 0020276 0 ustar 00root root 0000000 0000000
.. automodule:: sassutils
.. toctree::
:maxdepth: 2
sassutils/builder
sassutils/distutils
sassutils/wsgi
libsass-python-0.11.0/docs/sassutils/ 0000775 0000000 0000000 00000000000 12674562234 0017545 5 ustar 00root root 0000000 0000000 libsass-python-0.11.0/docs/sassutils/builder.rst 0000664 0000000 0000000 00000000060 12674562234 0021721 0 ustar 00root root 0000000 0000000
.. automodule:: sassutils.builder
:members:
libsass-python-0.11.0/docs/sassutils/distutils.rst 0000664 0000000 0000000 00000000062 12674562234 0022321 0 ustar 00root root 0000000 0000000
.. automodule:: sassutils.distutils
:members:
libsass-python-0.11.0/docs/sassutils/wsgi.rst 0000664 0000000 0000000 00000000055 12674562234 0021250 0 ustar 00root root 0000000 0000000
.. automodule:: sassutils.wsgi
:members:
libsass-python-0.11.0/libsass/ 0000775 0000000 0000000 00000000000 12674562234 0016223 5 ustar 00root root 0000000 0000000 libsass-python-0.11.0/pysass.cpp 0000664 0000000 0000000 00000055512 12674562234 0016621 0 ustar 00root root 0000000 0000000 #include
#include
#include
#if PY_MAJOR_VERSION >= 3
#define PySass_IF_PY3(three, two) (three)
#define PySass_Int_FromLong(v) PyLong_FromLong(v)
#define PySass_Bytes_Check(o) PyBytes_Check(o)
#define PySass_Bytes_GET_SIZE(o) PyBytes_GET_SIZE(o)
#define PySass_Bytes_AS_STRING(o) PyBytes_AS_STRING(o)
#define PySass_Object_Bytes(o) PyUnicode_AsUTF8String(PyObject_Str(o))
#else
#define PySass_IF_PY3(three, two) (two)
#define PySass_Int_FromLong(v) PyInt_FromLong(v)
#define PySass_Bytes_Check(o) PyString_Check(o)
#define PySass_Bytes_GET_SIZE(o) PyString_GET_SIZE(o)
#define PySass_Bytes_AS_STRING(o) PyString_AS_STRING(o)
#define PySass_Object_Bytes(o) PyObject_Str(o)
#endif
#ifdef __cplusplus
extern "C" {
#endif
static PyObject* _to_py_value(const union Sass_Value* value);
static union Sass_Value* _to_sass_value(PyObject* value);
static union Sass_Value* _color_to_sass_value(PyObject* value);
static union Sass_Value* _number_to_sass_value(PyObject* value);
static union Sass_Value* _list_to_sass_value(PyObject* value);
static union Sass_Value* _mapping_to_sass_value(PyObject* value);
static union Sass_Value* _unicode_to_sass_value(PyObject* value);
static union Sass_Value* _warning_to_sass_value(PyObject* value);
static union Sass_Value* _error_to_sass_value(PyObject* value);
static union Sass_Value* _unknown_type_to_sass_error(PyObject* value);
static union Sass_Value* _exception_to_sass_error();
static PyObject* _to_py_value(const union Sass_Value* value) {
PyObject* retv = NULL;
PyObject* types_mod = PyImport_ImportModule("sass");
PyObject* sass_comma = PyObject_GetAttrString(types_mod, "SASS_SEPARATOR_COMMA");
PyObject* sass_space = PyObject_GetAttrString(types_mod, "SASS_SEPARATOR_SPACE");
switch (sass_value_get_tag(value)) {
case SASS_NULL:
retv = Py_None;
Py_INCREF(retv);
break;
case SASS_BOOLEAN:
retv = PyBool_FromLong(sass_boolean_get_value(value));
break;
case SASS_STRING:
retv = PyUnicode_FromString(sass_string_get_value(value));
break;
case SASS_NUMBER:
retv = PyObject_CallMethod(
types_mod,
"SassNumber",
PySass_IF_PY3("dy", "ds"),
sass_number_get_value(value),
sass_number_get_unit(value)
);
break;
case SASS_COLOR:
retv = PyObject_CallMethod(
types_mod,
"SassColor",
"dddd",
sass_color_get_r(value),
sass_color_get_g(value),
sass_color_get_b(value),
sass_color_get_a(value)
);
break;
case SASS_LIST: {
size_t i = 0;
PyObject* items = PyTuple_New(sass_list_get_length(value));
PyObject* separator = sass_comma;
switch (sass_list_get_separator(value)) {
case SASS_COMMA:
separator = sass_comma;
break;
case SASS_SPACE:
separator = sass_space;
break;
case SASS_HASH:
assert(0);
break;
}
for (i = 0; i < sass_list_get_length(value); i += 1) {
PyTuple_SetItem(
items,
i,
_to_py_value(sass_list_get_value(value, i))
);
}
retv = PyObject_CallMethod(
types_mod, "SassList", "OO", items, separator
);
break;
}
case SASS_MAP: {
size_t i = 0;
PyObject* items = PyTuple_New(sass_map_get_length(value));
for (i = 0; i < sass_map_get_length(value); i += 1) {
PyObject* kvp = PyTuple_New(2);
PyTuple_SetItem(
kvp, 0, _to_py_value(sass_map_get_key(value, i))
);
PyTuple_SetItem(
kvp, 1, _to_py_value(sass_map_get_value(value, i))
);
PyTuple_SetItem(items, i, kvp);
}
retv = PyObject_CallMethod(types_mod, "SassMap", "(O)", items);
Py_DECREF(items);
break;
}
case SASS_ERROR:
case SASS_WARNING:
/* @warning and @error cannot be passed */
break;
}
if (retv == NULL) {
PyErr_SetString(PyExc_TypeError, "Unexpected sass type");
}
Py_DECREF(types_mod);
Py_DECREF(sass_comma);
Py_DECREF(sass_space);
return retv;
}
static union Sass_Value* _color_to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* r_value = PyObject_GetAttrString(value, "r");
PyObject* g_value = PyObject_GetAttrString(value, "g");
PyObject* b_value = PyObject_GetAttrString(value, "b");
PyObject* a_value = PyObject_GetAttrString(value, "a");
retv = sass_make_color(
PyFloat_AsDouble(r_value),
PyFloat_AsDouble(g_value),
PyFloat_AsDouble(b_value),
PyFloat_AsDouble(a_value)
);
Py_DECREF(r_value);
Py_DECREF(g_value);
Py_DECREF(b_value);
Py_DECREF(a_value);
return retv;
}
static union Sass_Value* _list_to_sass_value(PyObject* value) {
PyObject* types_mod = PyImport_ImportModule("sass");
PyObject* sass_comma = PyObject_GetAttrString(types_mod, "SASS_SEPARATOR_COMMA");
PyObject* sass_space = PyObject_GetAttrString(types_mod, "SASS_SEPARATOR_SPACE");
union Sass_Value* retv = NULL;
Py_ssize_t i = 0;
PyObject* items = PyObject_GetAttrString(value, "items");
PyObject* separator = PyObject_GetAttrString(value, "separator");
Sass_Separator sep = SASS_COMMA;
if (separator == sass_comma) {
sep = SASS_COMMA;
} else if (separator == sass_space) {
sep = SASS_SPACE;
} else {
assert(0);
}
retv = sass_make_list(PyTuple_Size(items), sep);
for (i = 0; i < PyTuple_Size(items); i += 1) {
sass_list_set_value(
retv, i, _to_sass_value(PyTuple_GET_ITEM(items, i))
);
}
Py_DECREF(types_mod);
Py_DECREF(sass_comma);
Py_DECREF(sass_space);
Py_DECREF(items);
Py_DECREF(separator);
return retv;
}
static union Sass_Value* _mapping_to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
size_t i = 0;
Py_ssize_t pos = 0;
PyObject* d_key = NULL;
PyObject* d_value = NULL;
PyObject* dct = PyDict_New();
PyDict_Update(dct, value);
retv = sass_make_map(PyDict_Size(dct));
while (PyDict_Next(dct, &pos, &d_key, &d_value)) {
sass_map_set_key(retv, i, _to_sass_value(d_key));
sass_map_set_value(retv, i, _to_sass_value(d_value));
i += 1;
}
Py_DECREF(dct);
return retv;
}
static union Sass_Value* _number_to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* d_value = PyObject_GetAttrString(value, "value");
PyObject* unit = PyObject_GetAttrString(value, "unit");
PyObject* bytes = PyUnicode_AsEncodedString(unit, "UTF-8", "strict");
retv = sass_make_number(
PyFloat_AsDouble(d_value), PySass_Bytes_AS_STRING(bytes)
);
Py_DECREF(d_value);
Py_DECREF(unit);
Py_DECREF(bytes);
return retv;
}
static union Sass_Value* _unicode_to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* bytes = PyUnicode_AsEncodedString(value, "UTF-8", "strict");
retv = sass_make_string(PySass_Bytes_AS_STRING(bytes));
Py_DECREF(bytes);
return retv;
}
static union Sass_Value* _warning_to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* msg = PyObject_GetAttrString(value, "msg");
PyObject* bytes = PyUnicode_AsEncodedString(msg, "UTF-8", "strict");
retv = sass_make_warning(PySass_Bytes_AS_STRING(bytes));
Py_DECREF(msg);
Py_DECREF(bytes);
return retv;
}
static union Sass_Value* _error_to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* msg = PyObject_GetAttrString(value, "msg");
PyObject* bytes = PyUnicode_AsEncodedString(msg, "UTF-8", "strict");
retv = sass_make_error(PySass_Bytes_AS_STRING(bytes));
Py_DECREF(msg);
Py_DECREF(bytes);
return retv;
}
static union Sass_Value* _unknown_type_to_sass_error(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* type = PyObject_Type(value);
PyObject* type_name = PyObject_GetAttrString(type, "__name__");
PyObject* fmt = PyUnicode_FromString(
"Unexpected type: `{0}`.\n"
"Expected one of:\n"
"- None\n"
"- bool\n"
"- str\n"
"- SassNumber\n"
"- SassColor\n"
"- SassList\n"
"- dict\n"
"- SassMap\n"
"- SassWarning\n"
"- SassError\n"
);
PyObject* format_meth = PyObject_GetAttrString(fmt, "format");
PyObject* result = PyObject_CallFunctionObjArgs(
format_meth, type_name, NULL
);
PyObject* bytes = PyUnicode_AsEncodedString(result, "UTF-8", "strict");
retv = sass_make_error(PySass_Bytes_AS_STRING(bytes));
Py_DECREF(type);
Py_DECREF(type_name);
Py_DECREF(fmt);
Py_DECREF(format_meth);
Py_DECREF(result);
Py_DECREF(bytes);
return retv;
}
static PyObject* _exception_to_bytes() {
PyObject* retv = NULL;
PyObject* etype = NULL;
PyObject* evalue = NULL;
PyObject* etb = NULL;
PyErr_Fetch(&etype, &evalue, &etb);
PyErr_NormalizeException(&etype, &evalue, &etb);
{
PyObject* traceback_mod = PyImport_ImportModule("traceback");
PyObject* traceback_parts = PyObject_CallMethod(
traceback_mod, "format_exception", "OOO", etype, evalue, etb
);
PyList_Insert(traceback_parts, 0, PyUnicode_FromString("\n"));
PyObject* joinstr = PyUnicode_FromString("");
PyObject* result = PyUnicode_Join(joinstr, traceback_parts);
retv = PyUnicode_AsEncodedString(result, "UTF-8", "strict");
Py_DECREF(traceback_mod);
Py_DECREF(traceback_parts);
Py_DECREF(joinstr);
Py_DECREF(result);
}
Py_DECREF(etype);
Py_DECREF(evalue);
Py_DECREF(etb);
return retv;
}
static union Sass_Value* _exception_to_sass_error() {
PyObject* bytes = _exception_to_bytes();
union Sass_Value* retv = sass_make_error(PySass_Bytes_AS_STRING(bytes));
Py_DECREF(bytes);
return retv;
}
static Sass_Import_List _exception_to_sass_import_error(const char* path) {
PyObject* bytes = _exception_to_bytes();
Sass_Import_List import_list = sass_make_import_list(1);
import_list[0] = sass_make_import_entry(path, 0, 0);
sass_import_set_error(import_list[0], PySass_Bytes_AS_STRING(bytes), 0, 0);
Py_DECREF(bytes);
return import_list;
}
static union Sass_Value* _to_sass_value(PyObject* value) {
union Sass_Value* retv = NULL;
PyObject* types_mod = PyImport_ImportModule("sass");
PyObject* sass_number_t = PyObject_GetAttrString(types_mod, "SassNumber");
PyObject* sass_color_t = PyObject_GetAttrString(types_mod, "SassColor");
PyObject* sass_list_t = PyObject_GetAttrString(types_mod, "SassList");
PyObject* sass_warning_t = PyObject_GetAttrString(types_mod, "SassWarning");
PyObject* sass_error_t = PyObject_GetAttrString(types_mod, "SassError");
PyObject* collections_mod = PyImport_ImportModule("collections");
PyObject* mapping_t = PyObject_GetAttrString(collections_mod, "Mapping");
if (value == Py_None) {
retv = sass_make_null();
} else if (PyBool_Check(value)) {
retv = sass_make_boolean(value == Py_True);
} else if (PyUnicode_Check(value)) {
retv = _unicode_to_sass_value(value);
} else if (PySass_Bytes_Check(value)) {
retv = sass_make_string(PySass_Bytes_AS_STRING(value));
/* XXX: PyMapping_Check returns true for lists and tuples in python3 :( */
/* XXX: pypy derps on dicts: https://bitbucket.org/pypy/pypy/issue/1970 */
} else if (PyDict_Check(value) || PyObject_IsInstance(value, mapping_t)) {
retv = _mapping_to_sass_value(value);
} else if (PyObject_IsInstance(value, sass_number_t)) {
retv = _number_to_sass_value(value);
} else if (PyObject_IsInstance(value, sass_color_t)) {
retv = _color_to_sass_value(value);
} else if (PyObject_IsInstance(value, sass_list_t)) {
retv = _list_to_sass_value(value);
} else if (PyObject_IsInstance(value, sass_warning_t)) {
retv = _warning_to_sass_value(value);
} else if (PyObject_IsInstance(value, sass_error_t)) {
retv = _error_to_sass_value(value);
}
if (retv == NULL) {
retv = _unknown_type_to_sass_error(value);
}
Py_DECREF(types_mod);
Py_DECREF(sass_number_t);
Py_DECREF(sass_color_t);
Py_DECREF(sass_list_t);
Py_DECREF(sass_warning_t);
Py_DECREF(sass_error_t);
Py_DECREF(collections_mod);
Py_DECREF(mapping_t);
return retv;
}
static union Sass_Value* _call_py_f(
const union Sass_Value* sass_args,
Sass_Function_Entry cb,
struct Sass_Compiler* compiler
) {
size_t i;
PyObject* pyfunc = (PyObject*)sass_function_get_cookie(cb);
PyObject* py_args = PyTuple_New(sass_list_get_length(sass_args));
PyObject* py_result = NULL;
union Sass_Value* sass_result = NULL;
for (i = 0; i < sass_list_get_length(sass_args); i += 1) {
const union Sass_Value* sass_arg = sass_list_get_value(sass_args, i);
PyObject* py_arg = NULL;
if (!(py_arg = _to_py_value(sass_arg))) goto done;
PyTuple_SetItem(py_args, i, py_arg);
}
if (!(py_result = PyObject_CallObject(pyfunc, py_args))) goto done;
sass_result = _to_sass_value(py_result);
done:
if (sass_result == NULL) {
sass_result = _exception_to_sass_error();
}
Py_XDECREF(py_args);
Py_XDECREF(py_result);
return sass_result;
}
static void _add_custom_functions(
struct Sass_Options* options, PyObject* custom_functions
) {
Py_ssize_t i;
Sass_Function_List fn_list = sass_make_function_list(
PyList_Size(custom_functions)
);
for (i = 0; i < PyList_GET_SIZE(custom_functions); i += 1) {
PyObject* sass_function = PyList_GET_ITEM(custom_functions, i);
PyObject* signature = PySass_Object_Bytes(sass_function);
Sass_Function_Entry fn = sass_make_function(
PySass_Bytes_AS_STRING(signature),
_call_py_f,
sass_function
);
sass_function_set_list_entry(fn_list, i, fn);
}
sass_option_set_c_functions(options, fn_list);
}
static Sass_Import_List _call_py_importer_f(
const char* path, Sass_Importer_Entry cb, struct Sass_Compiler* comp
) {
PyObject* pyfunc = (PyObject*)sass_importer_get_cookie(cb);
PyObject* py_result = NULL;
Sass_Import_List sass_imports = NULL;
Py_ssize_t i;
py_result = PyObject_CallFunction(pyfunc, PySass_IF_PY3("y", "s"), path);
/* Handle importer throwing an exception */
if (!py_result) goto done;
/* Could return None indicating it could not handle the import */
if (py_result == Py_None) {
Py_XDECREF(py_result);
return NULL;
}
/* Otherwise, we know our importer is well formed (because we wrap it)
* The return value will be a tuple of 1, 2, or 3 tuples */
sass_imports = sass_make_import_list(PyTuple_GET_SIZE(py_result));
for (i = 0; i < PyTuple_GET_SIZE(py_result); i += 1) {
char* path_str = NULL; /* XXX: Memory leak? */
char* source_str = NULL;
char* sourcemap_str = NULL;
PyObject* tup = PyTuple_GET_ITEM(py_result, i);
Py_ssize_t size = PyTuple_GET_SIZE(tup);
if (size == 1) {
PyArg_ParseTuple(tup, PySass_IF_PY3("y", "s"), &path_str);
} else if (size == 2) {
PyArg_ParseTuple(
tup, PySass_IF_PY3("yy", "ss"), &path_str, &source_str
);
} else if (size == 3) {
PyArg_ParseTuple(
tup, PySass_IF_PY3("yyy", "sss"),
&path_str, &source_str, &sourcemap_str
);
}
/* We need to give copies of these arguments; libsass handles
* deallocation of them later, whereas path_str is left flapping
* in the breeze -- it's treated const, so that's okay. */
if (source_str) source_str = strdup(source_str);
if (sourcemap_str) sourcemap_str = strdup(sourcemap_str);
sass_imports[i] = sass_make_import_entry(
path_str, source_str, sourcemap_str
);
}
done:
if (sass_imports == NULL) {
sass_imports = _exception_to_sass_import_error(path);
}
Py_XDECREF(py_result);
return sass_imports;
}
static void _add_custom_importers(
struct Sass_Options* options, PyObject* custom_importers
) {
Py_ssize_t i;
Sass_Importer_List importer_list;
if (custom_importers == Py_None) {
return;
}
importer_list = sass_make_importer_list(PyTuple_GET_SIZE(custom_importers));
for (i = 0; i < PyTuple_GET_SIZE(custom_importers); i += 1) {
PyObject* item = PyTuple_GET_ITEM(custom_importers, i);
int priority = 0;
PyObject* import_function = NULL;
PyArg_ParseTuple(item, "iO", &priority, &import_function);
importer_list[i] = sass_make_importer(
_call_py_importer_f, priority, import_function
);
}
sass_option_set_c_importers(options, importer_list);
}
static PyObject *
PySass_compile_string(PyObject *self, PyObject *args) {
struct Sass_Context *ctx;
struct Sass_Data_Context *context;
struct Sass_Options *options;
char *string, *include_paths;
const char *error_message, *output_string;
Sass_Output_Style output_style;
int source_comments, error_status, precision, indented;
PyObject *custom_functions;
PyObject *custom_importers;
PyObject *result;
if (!PyArg_ParseTuple(args,
PySass_IF_PY3("yiiyiOiO", "siisiOiO"),
&string, &output_style, &source_comments,
&include_paths, &precision,
&custom_functions, &indented, &custom_importers)) {
return NULL;
}
context = sass_make_data_context(strdup(string));
options = sass_data_context_get_options(context);
sass_option_set_output_style(options, output_style);
sass_option_set_source_comments(options, source_comments);
sass_option_set_include_path(options, include_paths);
sass_option_set_precision(options, precision);
sass_option_set_is_indented_syntax_src(options, indented);
_add_custom_functions(options, custom_functions);
_add_custom_importers(options, custom_importers);
sass_compile_data_context(context);
ctx = sass_data_context_get_context(context);
error_status = sass_context_get_error_status(ctx);
error_message = sass_context_get_error_message(ctx);
output_string = sass_context_get_output_string(ctx);
result = Py_BuildValue(
PySass_IF_PY3("hy", "hs"),
(short int) !error_status,
error_status ? error_message : output_string
);
sass_delete_data_context(context);
return result;
}
static PyObject *
PySass_compile_filename(PyObject *self, PyObject *args) {
struct Sass_Context *ctx;
struct Sass_File_Context *context;
struct Sass_Options *options;
char *filename, *include_paths;
const char *error_message, *output_string, *source_map_string;
Sass_Output_Style output_style;
int source_comments, error_status, precision;
PyObject *source_map_filename, *custom_functions, *custom_importers,
*result;
if (!PyArg_ParseTuple(args,
PySass_IF_PY3("yiiyiOOO", "siisiOOO"),
&filename, &output_style, &source_comments,
&include_paths, &precision,
&source_map_filename, &custom_functions,
&custom_importers)) {
return NULL;
}
context = sass_make_file_context(filename);
options = sass_file_context_get_options(context);
if (PySass_Bytes_Check(source_map_filename)) {
size_t source_map_file_len = PySass_Bytes_GET_SIZE(source_map_filename);
if (source_map_file_len) {
char *source_map_file = (char *) malloc(source_map_file_len + 1);
strncpy(
source_map_file,
PySass_Bytes_AS_STRING(source_map_filename),
source_map_file_len + 1
);
sass_option_set_source_map_file(options, source_map_file);
}
}
sass_option_set_output_style(options, output_style);
sass_option_set_source_comments(options, source_comments);
sass_option_set_include_path(options, include_paths);
sass_option_set_precision(options, precision);
_add_custom_functions(options, custom_functions);
_add_custom_importers(options, custom_importers);
sass_compile_file_context(context);
ctx = sass_file_context_get_context(context);
error_status = sass_context_get_error_status(ctx);
error_message = sass_context_get_error_message(ctx);
output_string = sass_context_get_output_string(ctx);
source_map_string = sass_context_get_source_map_string(ctx);
result = Py_BuildValue(
PySass_IF_PY3("hyy", "hss"),
(short int) !error_status,
error_status ? error_message : output_string,
error_status || source_map_string == NULL ? "" : source_map_string
);
sass_delete_file_context(context);
return result;
}
static PyMethodDef PySass_methods[] = {
{"compile_string", PySass_compile_string, METH_VARARGS,
"Compile a SASS string."},
{"compile_filename", PySass_compile_filename, METH_VARARGS,
"Compile a SASS file."},
{NULL, NULL, 0, NULL}
};
static char PySass_doc[] = "The thin binding of libsass for Python.";
PyObject* PySass_make_enum_dict() {
PyObject* dct = PyDict_New();
PyDict_SetItemString(dct, "nested", PySass_Int_FromLong(SASS_STYLE_NESTED));
PyDict_SetItemString(dct, "expanded", PySass_Int_FromLong(SASS_STYLE_EXPANDED));
PyDict_SetItemString(dct, "compact", PySass_Int_FromLong(SASS_STYLE_COMPACT));
PyDict_SetItemString(dct, "compressed", PySass_Int_FromLong(SASS_STYLE_COMPRESSED));
return dct;
}
void PySass_init_module(PyObject *module) {
PyModule_AddObject(module, "OUTPUT_STYLES", PySass_make_enum_dict());
PyModule_AddObject(module, "libsass_version", PyUnicode_FromString(libsass_version()));
}
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef sassmodule = {
PyModuleDef_HEAD_INIT,
"_sass",
PySass_doc,
-1,
PySass_methods
};
PyMODINIT_FUNC
PyInit__sass()
{
PyObject *module = PyModule_Create(&sassmodule);
if (module != NULL) {
PySass_init_module(module);
}
return module;
}
#else
PyMODINIT_FUNC
init_sass()
{
PyObject *module;
module = Py_InitModule3("_sass", PySass_methods, PySass_doc);
if (module != NULL) {
PySass_init_module(module);
}
}
#endif
#ifdef __cplusplus
}
#endif
libsass-python-0.11.0/requirements-dev.txt 0000664 0000000 0000000 00000000114 12674562234 0020617 0 ustar 00root root 0000000 0000000 -e .
coverage
coverage-enable-subprocess
flake8>=2.4.0
pytest
werkzeug>=0.9
libsass-python-0.11.0/sass.py 0000664 0000000 0000000 00000072221 12674562234 0016112 0 ustar 00root root 0000000 0000000 """:mod:`sass` --- Binding of ``libsass``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This simple C extension module provides a very simple binding of ``libsass``,
which is written in C/C++. It contains only one function and one exception
type.
>>> import sass
>>> sass.compile(string='a { b { color: blue; } }')
'a b {\n color: blue; }\n'
"""
from __future__ import absolute_import
import collections
import functools
import inspect
from io import open
import os
import os.path
import re
import sys
import warnings
from six import string_types, text_type, PY2, PY3
import _sass
__all__ = (
'MODES', 'OUTPUT_STYLES', 'SOURCE_COMMENTS', 'CompileError', 'SassColor',
'SassError', 'SassFunction', 'SassList', 'SassMap', 'SassNumber',
'SassWarning', 'and_join', 'compile', 'libsass_version',
)
__version__ = '0.11.0'
libsass_version = _sass.libsass_version
#: (:class:`collections.Mapping`) The dictionary of output styles.
#: Keys are output name strings, and values are flag integers.
OUTPUT_STYLES = _sass.OUTPUT_STYLES
#: (:class:`collections.Mapping`) The dictionary of source comments styles.
#: Keys are mode names, and values are corresponding flag integers.
#:
#: .. versionadded:: 0.4.0
#:
#: .. deprecated:: 0.6.0
SOURCE_COMMENTS = {'none': 0, 'line_numbers': 1, 'default': 1, 'map': 2}
#: (:class:`collections.Set`) The set of keywords :func:`compile()` can take.
MODES = set(['string', 'filename', 'dirname'])
def to_native_s(s):
if isinstance(s, bytes) and PY3: # pragma: no cover (py3)
s = s.decode('UTF-8')
elif isinstance(s, text_type) and PY2: # pragma: no cover (py2)
s = s.encode('UTF-8')
return s
class CompileError(ValueError):
"""The exception type that is raised by :func:`compile()`.
It is a subtype of :exc:`exceptions.ValueError`.
"""
def __init__(self, msg):
super(CompileError, self).__init__(to_native_s(msg))
def mkdirp(path):
try:
os.makedirs(path)
except OSError:
if os.path.isdir(path):
return
raise
class SassFunction(object):
"""Custom function for Sass. It can be instantiated using
:meth:`from_lambda()` and :meth:`from_named_function()` as well.
:param name: the function name
:type name: :class:`str`
:param arguments: the argument names
:type arguments: :class:`collections.Sequence`
:param callable_: the actual function to be called
:type callable_: :class:`collections.Callable`
.. versionadded:: 0.7.0
"""
__slots__ = 'name', 'arguments', 'callable_'
@classmethod
def from_lambda(cls, name, lambda_):
"""Make a :class:`SassFunction` object from the given ``lambda_``
function. Since lambda functions don't have their name, it need
its ``name`` as well. Arguments are automatically inspected.
:param name: the function name
:type name: :class:`str`
:param lambda_: the actual lambda function to be called
:type lambda_: :class:`types.LambdaType`
:returns: a custom function wrapper of the ``lambda_`` function
:rtype: :class:`SassFunction`
"""
argspec = inspect.getargspec(lambda_)
if argspec.varargs or argspec.keywords or argspec.defaults:
raise TypeError(
'functions cannot have starargs or defaults: {0} {1}'.format(
name, lambda_
)
)
return cls(name, argspec.args, lambda_)
@classmethod
def from_named_function(cls, function):
"""Make a :class:`SassFunction` object from the named ``function``.
Function name and arguments are automatically inspected.
:param function: the named function to be called
:type function: :class:`types.FunctionType`
:returns: a custom function wrapper of the ``function``
:rtype: :class:`SassFunction`
"""
if not getattr(function, '__name__', ''):
raise TypeError('function must be named')
return cls.from_lambda(function.__name__, function)
def __init__(self, name, arguments, callable_):
if not isinstance(name, string_types):
raise TypeError('name must be a string, not ' + repr(name))
elif not isinstance(arguments, collections.Sequence):
raise TypeError('arguments must be a sequence, not ' +
repr(arguments))
elif not callable(callable_):
raise TypeError(repr(callable_) + ' is not callable')
self.name = name
self.arguments = tuple(
arg if arg.startswith('$') else '$' + arg
for arg in arguments
)
self.callable_ = callable_
@property
def signature(self):
"""Signature string of the function."""
return '{0}({1})'.format(self.name, ', '.join(self.arguments))
def __call__(self, *args, **kwargs):
return self.callable_(*args, **kwargs)
def __str__(self):
return self.signature
def _normalize_importer_return_value(result):
# An importer must return an iterable of iterables of 1-3 stringlike
# objects
if result is None:
return result
def _to_importer_result(single_result):
single_result = tuple(single_result)
if len(single_result) not in (1, 2, 3):
raise ValueError(
'Expected importer result to be a tuple of length (1, 2, 3) '
'but got {0}: {1!r}'.format(len(single_result), single_result)
)
def _to_bytes(obj):
if not isinstance(obj, bytes):
return obj.encode('UTF-8')
else:
return obj
return tuple(_to_bytes(s) for s in single_result)
return tuple(_to_importer_result(x) for x in result)
def _importer_callback_wrapper(func):
@functools.wraps(func)
def inner(path):
ret = func(path.decode('UTF-8'))
return _normalize_importer_return_value(ret)
return inner
def _validate_importers(importers):
"""Validates the importers and decorates the callables with our output
formatter.
"""
# They could have no importers, that's chill
if importers is None:
return None
def _to_importer(priority, func):
assert isinstance(priority, int), priority
assert callable(func), func
return (priority, _importer_callback_wrapper(func))
# Our code assumes tuple of tuples
return tuple(_to_importer(priority, func) for priority, func in importers)
def _raise(e):
raise e
def compile_dirname(
search_path, output_path, output_style, source_comments, include_paths,
precision, custom_functions, importers
):
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
for dirpath, _, filenames in os.walk(search_path, onerror=_raise):
filenames = [
filename for filename in filenames
if filename.endswith(('.scss', '.sass')) and
not filename.startswith('_')
]
for filename in filenames:
input_filename = os.path.join(dirpath, filename)
relpath_to_file = os.path.relpath(input_filename, search_path)
output_filename = os.path.join(output_path, relpath_to_file)
output_filename = re.sub('.s[ac]ss$', '.css', output_filename)
input_filename = input_filename.encode(fs_encoding)
s, v, _ = _sass.compile_filename(
input_filename, output_style, source_comments, include_paths,
precision, None, custom_functions, importers
)
if s:
v = v.decode('UTF-8')
mkdirp(os.path.dirname(output_filename))
with open(output_filename, 'w',
encoding="UTF-8") as output_file:
output_file.write(v)
else:
return False, v
return True, None
def _check_no_remaining_kwargs(func, kwargs):
if kwargs:
raise TypeError(
'{0}() got unexpected keyword argument(s) {1}'.format(
func.__name__,
', '.join("'{0}'".format(arg) for arg in sorted(kwargs)),
)
)
def compile(**kwargs):
"""There are three modes of parameters :func:`compile()` can take:
``string``, ``filename``, and ``dirname``.
The ``string`` parameter is the most basic way to compile SASS.
It simply takes a string of SASS code, and then returns a compiled
CSS string.
:param string: SASS source code to compile. it's exclusive to
``filename`` and ``dirname`` parameters
:type string: :class:`str`
:param output_style: an optional coding style of the compiled result.
choose one of: ``'nested'`` (default), ``'expanded'``,
``'compact'``, ``'compressed'``
:type output_style: :class:`str`
:param source_comments: whether to add comments about source lines.
:const:`False` by default
:type source_comments: :class:`bool`
:param include_paths: an optional list of paths to find ``@import``\ ed
SASS/CSS source files
:type include_paths: :class:`collections.Sequence`, :class:`str`
:param precision: optional precision for numbers. :const:`5` by default.
:type precision: :class:`int`
:param custom_functions: optional mapping of custom functions.
see also below `custom functions
`_ description
:type custom_functions: :class:`collections.Set`,
:class:`collections.Sequence`,
:class:`collections.Mapping`
:param indented: optional declaration that the string is SASS, not SCSS
formatted. :const:`False` by default
:type indented: :class:`bool`
:returns: the compiled CSS string
:param importers: optional callback functions.
see also below `importer callbacks
`_ description
:type importers: :class:`collections.Callable`
:rtype: :class:`str`
:raises sass.CompileError: when it fails for any reason
(for example the given SASS has broken syntax)
The ``filename`` is the most commonly used way. It takes a string of
SASS filename, and then returns a compiled CSS string.
:param filename: the filename of SASS source code to compile.
it's exclusive to ``string`` and ``dirname`` parameters
:type filename: :class:`str`
:param output_style: an optional coding style of the compiled result.
choose one of: ``'nested'`` (default), ``'expanded'``,
``'compact'``, ``'compressed'``
:type output_style: :class:`str`
:param source_comments: whether to add comments about source lines.
:const:`False` by default
:type source_comments: :class:`bool`
:param source_map_filename: use source maps and indicate the source map
output filename. :const:`None` means not
using source maps. :const:`None` by default.
:type source_map_filename: :class:`str`
:param include_paths: an optional list of paths to find ``@import``\ ed
SASS/CSS source files
:type include_paths: :class:`collections.Sequence`, :class:`str`
:param precision: optional precision for numbers. :const:`5` by default.
:type precision: :class:`int`
:param custom_functions: optional mapping of custom functions.
see also below `custom functions
`_ description
:type custom_functions: :class:`collections.Set`,
:class:`collections.Sequence`,
:class:`collections.Mapping`
:param importers: optional callback functions.
see also below `importer callbacks
`_ description
:type importers: :class:`collections.Callable`
:returns: the compiled CSS string, or a pair of the compiled CSS string
and the source map string if ``source_map_filename`` is set
:rtype: :class:`str`, :class:`tuple`
:raises sass.CompileError: when it fails for any reason
(for example the given SASS has broken syntax)
:raises exceptions.IOError: when the ``filename`` doesn't exist or
cannot be read
The ``dirname`` is useful for automation. It takes a pair of paths.
The first of the ``dirname`` pair refers the source directory, contains
several SASS source files to compiled. SASS source files can be nested
in directories. The second of the pair refers the output directory
that compiled CSS files would be saved. Directory tree structure of
the source directory will be maintained in the output directory as well.
If ``dirname`` parameter is used the function returns :const:`None`.
:param dirname: a pair of ``(source_dir, output_dir)``.
it's exclusive to ``string`` and ``filename``
parameters
:type dirname: :class:`tuple`
:param output_style: an optional coding style of the compiled result.
choose one of: ``'nested'`` (default), ``'expanded'``,
``'compact'``, ``'compressed'``
:type output_style: :class:`str`
:param source_comments: whether to add comments about source lines.
:const:`False` by default
:type source_comments: :class:`bool`
:param include_paths: an optional list of paths to find ``@import``\ ed
SASS/CSS source files
:type include_paths: :class:`collections.Sequence`, :class:`str`
:param precision: optional precision for numbers. :const:`5` by default.
:type precision: :class:`int`
:param custom_functions: optional mapping of custom functions.
see also below `custom functions
`_ description
:type custom_functions: :class:`collections.Set`,
:class:`collections.Sequence`,
:class:`collections.Mapping`
:raises sass.CompileError: when it fails for any reason
(for example the given SASS has broken syntax)
.. _custom-functions:
The ``custom_functions`` parameter can take three types of forms:
:class:`~collections.Set`/:class:`~collections.Sequence` of \
:class:`SassFunction`\ s
It is the most general form. Although pretty verbose, it can take
any kind of callables like type objects, unnamed functions,
and user-defined callables.
.. code-block:: python
sass.compile(
...,
custom_functions={
sass.SassFunction('func-name', ('$a', '$b'), some_callable),
...
}
)
:class:`~collections.Mapping` of names to functions
Less general, but easier-to-use form. Although it's not it can take
any kind of callables, it can take any kind of *functions* defined
using :keyword:`def`/:keyword:`lambda` syntax.
It cannot take callables other than them since inspecting arguments
is not always available for every kind of callables.
.. code-block:: python
sass.compile(
...,
custom_functions={
'func-name': lambda a, b: ...,
...
}
)
:class:`~collections.Set`/:class:`~collections.Sequence` of \
named functions
Not general, but the easiest-to-use form for *named* functions.
It can take only named functions, defined using :keyword:`def`.
It cannot take lambdas sinc names are unavailable for them.
.. code-block:: python
def func_name(a, b):
return ...
sass.compile(
...,
custom_functions={func_name}
)
.. _importer-callbacks:
Newer versions of ``libsass`` allow developers to define callbacks to be
called and given a chance to process ``@import`` directives. You can
define yours by passing in a list of callables via the ``importers``
parameter. The callables must be passed as 2-tuples in the form:
.. code-block:: python
(priority_int, callback_fn)
A priority of zero is acceptable; priority determines the order callbacks
are attempted.
These callbacks must accept a single string argument representing the path
passed to the ``@import`` directive, and either return ``None`` to
indicate the path wasn't handled by that callback (to continue with others
or fall back on internal ``libsass`` filesystem behaviour) or a list of
one or more tuples, each in one of three forms:
* A 1-tuple representing an alternate path to handle internally; or,
* A 2-tuple representing an alternate path and the content that path
represents; or,
* A 3-tuple representing the same as the 2-tuple with the addition of a
"sourcemap".
All tuple return values must be strings. As a not overly realistic
example:
.. code-block:: python
def my_importer(path):
return [(path, '#' + path + ' { color: red; }')]
sass.compile(
...,
importers=[(0, my_importer)]
)
Now, within the style source, attempting to ``@import 'button';`` will
instead attach ``color: red`` as a property of an element with the
imported name.
.. versionadded:: 0.4.0
Added ``source_comments`` and ``source_map_filename`` parameters.
.. versionchanged:: 0.6.0
The ``source_comments`` parameter becomes to take only :class:`bool`
instead of :class:`str`.
.. deprecated:: 0.6.0
Values like ``'none'``, ``'line_numbers'``, and ``'map'`` for
the ``source_comments`` parameter are deprecated.
.. versionadded:: 0.7.0
Added ``precision`` parameter.
.. versionadded:: 0.7.0
Added ``custom_functions`` parameter.
.. versionadded:: 0.11.0
``source_map_filename`` no longer implies ``source_comments``.
"""
modes = set()
for mode_name in MODES:
if mode_name in kwargs:
modes.add(mode_name)
if not modes:
raise TypeError('choose one at least in ' + and_join(MODES))
elif len(modes) > 1:
raise TypeError(and_join(modes) + ' are exclusive each other; '
'cannot be used at a time')
precision = kwargs.pop('precision', 5)
output_style = kwargs.pop('output_style', 'nested')
if not isinstance(output_style, string_types):
raise TypeError('output_style must be a string, not ' +
repr(output_style))
try:
output_style = OUTPUT_STYLES[output_style]
except KeyError:
raise CompileError('{0} is unsupported output_style; choose one of {1}'
''.format(output_style, and_join(OUTPUT_STYLES)))
source_comments = kwargs.pop('source_comments', False)
if source_comments in SOURCE_COMMENTS:
if source_comments == 'none':
deprecation_message = ('you can simply pass False to '
"source_comments instead of 'none'")
source_comments = False
elif source_comments in ('line_numbers', 'default'):
deprecation_message = ('you can simply pass True to '
"source_comments instead of " +
repr(source_comments))
source_comments = True
else:
deprecation_message = ("you don't have to pass 'map' to "
'source_comments but just need to '
'specify source_map_filename')
source_comments = False
warnings.warn(
"values like 'none', 'line_numbers', and 'map' for "
'the source_comments parameter are deprecated; ' +
deprecation_message,
DeprecationWarning
)
if not isinstance(source_comments, bool):
raise TypeError('source_comments must be bool, not ' +
repr(source_comments))
fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
source_map_filename = kwargs.pop('source_map_filename', None)
if not (source_map_filename is None or
isinstance(source_map_filename, string_types)):
raise TypeError('source_map_filename must be a string, not ' +
repr(source_map_filename))
elif isinstance(source_map_filename, text_type):
source_map_filename = source_map_filename.encode(fs_encoding)
if not ('filename' in modes or source_map_filename is None):
raise CompileError('source_map_filename is only available with '
'filename= keyword argument since it has to be '
'aware of it')
try:
include_paths = kwargs.pop('include_paths') or b''
except KeyError:
include_paths = b''
else:
if isinstance(include_paths, collections.Sequence):
include_paths = os.pathsep.join(include_paths)
elif not isinstance(include_paths, string_types):
raise TypeError('include_paths must be a sequence of strings, or '
'a colon-separated (or semicolon-separated if '
'Windows) string, not ' + repr(include_paths))
if isinstance(include_paths, text_type):
include_paths = include_paths.encode(fs_encoding)
custom_functions = kwargs.pop('custom_functions', ())
if isinstance(custom_functions, collections.Mapping):
custom_functions = [
SassFunction.from_lambda(name, lambda_)
for name, lambda_ in custom_functions.items()
]
elif isinstance(custom_functions, (collections.Set, collections.Sequence)):
custom_functions = [
func if isinstance(func, SassFunction)
else SassFunction.from_named_function(func)
for func in custom_functions
]
else:
raise TypeError(
'custom_functions must be one of:\n'
'- a set/sequence of {0.__module__}.{0.__name__} objects,\n'
'- a mapping of function name strings to lambda functions,\n'
'- a set/sequence of named functions,\n'
'not {1!r}'.format(SassFunction, custom_functions)
)
importers = _validate_importers(kwargs.pop('importers', None))
if 'string' in modes:
string = kwargs.pop('string')
if isinstance(string, text_type):
string = string.encode('utf-8')
indented = kwargs.pop('indented', False)
if not isinstance(indented, bool):
raise TypeError('indented must be bool, not ' +
repr(source_comments))
_check_no_remaining_kwargs(compile, kwargs)
s, v = _sass.compile_string(
string, output_style, source_comments, include_paths, precision,
custom_functions, indented, importers,
)
if s:
return v.decode('utf-8')
elif 'filename' in modes:
filename = kwargs.pop('filename')
if not isinstance(filename, string_types):
raise TypeError('filename must be a string, not ' + repr(filename))
elif not os.path.isfile(filename):
raise IOError('{0!r} seems not a file'.format(filename))
elif isinstance(filename, text_type):
filename = filename.encode(fs_encoding)
_check_no_remaining_kwargs(compile, kwargs)
s, v, source_map = _sass.compile_filename(
filename, output_style, source_comments, include_paths, precision,
source_map_filename, custom_functions, importers,
)
if s:
v = v.decode('utf-8')
if source_map_filename:
source_map = source_map.decode('utf-8')
if os.sep != '/' and os.altsep:
# Libsass has a bug that produces invalid JSON string
# literals which contain unescaped backslashes for
# "sources" paths on Windows e.g.:
#
# {
# "version": 3,
# "file": "",
# "sources": ["c:\temp\tmpj2ac07\test\b.scss"],
# "names": [],
# "mappings": "AAAA,EAAE;EAEE,WAAW"
# }
#
# To workaround this bug without changing libsass'
# internal behavior, we replace these backslashes with
# slashes e.g.:
#
# {
# "version": 3,
# "file": "",
# "sources": ["c:/temp/tmpj2ac07/test/b.scss"],
# "names": [],
# "mappings": "AAAA,EAAE;EAEE,WAAW"
# }
source_map = re.sub(
r'"sources":\s*\[\s*"[^"]*"(?:\s*,\s*"[^"]*")*\s*\]',
lambda m: m.group(0).replace(os.sep, os.altsep),
source_map
)
v = v, source_map
return v
elif 'dirname' in modes:
try:
search_path, output_path = kwargs.pop('dirname')
except ValueError:
raise ValueError('dirname must be a pair of (source_dir, '
'output_dir)')
_check_no_remaining_kwargs(compile, kwargs)
s, v = compile_dirname(
search_path, output_path, output_style, source_comments,
include_paths, precision, custom_functions, importers,
)
if s:
return
else:
raise TypeError('something went wrong')
assert not s
raise CompileError(v)
def and_join(strings):
"""Join the given ``strings`` by commas with last `' and '` conjuction.
>>> and_join(['Korea', 'Japan', 'China', 'Taiwan'])
'Korea, Japan, China, and Taiwan'
:param strings: a list of words to join
:type string: :class:`collections.Sequence`
:returns: a joined string
:rtype: :class:`str`, :class:`basestring`
"""
last = len(strings) - 1
if last == 0:
return strings[0]
elif last < 0:
return ''
iterator = enumerate(strings)
return ', '.join('and ' + s if i == last else s for i, s in iterator)
"""
This module provides datatypes to be used in custom sass functions.
The following mappings from sass types to python types are used:
SASS_NULL: ``None``
SASS_BOOLEAN: ``True`` or ``False``
SASS_STRING: class:`str`
SASS_NUMBER: class:`SassNumber`
SASS_COLOR: class:`SassColor`
SASS_LIST: class:`SassList`
SASS_MAP: class:`dict` or class:`SassMap`
SASS_ERROR: class:`SassError`
SASS_WARNING: class:`SassWarning`
"""
class SassNumber(collections.namedtuple('SassNumber', ('value', 'unit'))):
def __new__(cls, value, unit):
value = float(value)
if not isinstance(unit, text_type):
unit = unit.decode('UTF-8')
return super(SassNumber, cls).__new__(cls, value, unit)
class SassColor(collections.namedtuple('SassColor', ('r', 'g', 'b', 'a'))):
def __new__(cls, r, g, b, a):
r = float(r)
g = float(g)
b = float(b)
a = float(a)
return super(SassColor, cls).__new__(cls, r, g, b, a)
SASS_SEPARATOR_COMMA = collections.namedtuple('SASS_SEPARATOR_COMMA', ())()
SASS_SEPARATOR_SPACE = collections.namedtuple('SASS_SEPARATOR_SPACE', ())()
SEPARATORS = frozenset((SASS_SEPARATOR_COMMA, SASS_SEPARATOR_SPACE))
class SassList(collections.namedtuple('SassList', ('items', 'separator'))):
def __new__(cls, items, separator):
items = tuple(items)
assert separator in SEPARATORS
return super(SassList, cls).__new__(cls, items, separator)
class SassError(collections.namedtuple('SassError', ('msg',))):
def __new__(cls, msg):
if not isinstance(msg, text_type):
msg = msg.decode('UTF-8')
return super(SassError, cls).__new__(cls, msg)
class SassWarning(collections.namedtuple('SassWarning', ('msg',))):
def __new__(cls, msg):
if not isinstance(msg, text_type):
msg = msg.decode('UTF-8')
return super(SassWarning, cls).__new__(cls, msg)
class SassMap(collections.Mapping):
"""Because sass maps can have mapping types as keys, we need an immutable
hashable mapping type.
.. versionadded:: 0.7.0
"""
__slots__ = '_dict', '_hash'
def __init__(self, *args, **kwargs):
self._dict = dict(*args, **kwargs)
# An assertion that all things are hashable
self._hash = hash(frozenset(self._dict.items()))
# Mapping interface
def __getitem__(self, key):
return self._dict[key]
def __iter__(self):
return iter(self._dict)
def __len__(self):
return len(self._dict)
# Our interface
def __repr__(self):
return '{0}({1})'.format(type(self).__name__, frozenset(self.items()))
def __hash__(self):
return self._hash
def _immutable(self, *_):
raise TypeError('SassMaps are immutable.')
__setitem__ = __delitem__ = _immutable
libsass-python-0.11.0/sassc.py 0000775 0000000 0000000 00000014477 12674562234 0016271 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
""":mod:`sassc` --- SassC compliant command line interface
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This provides SassC_ compliant CLI executable named :program:`sassc`:
.. sourcecode:: console
$ sassc
Usage: sassc [options] SCSS_FILE [CSS_FILE]
There are options as well:
.. option:: -t