Ejemplo n.º 1
0
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 io.open(
                        output_filename,
                        'w',
                        encoding='UTF-8',
                        newline='',
                ) as output_file:
                    output_file.write(v)
            else:
                return False, v
    return True, None
Ejemplo n.º 2
0
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 io.open(
                    output_filename, 'w', encoding='UTF-8', newline='',
                ) as output_file:
                    output_file.write(v)
            else:
                return False, v
    return True, None
Ejemplo n.º 3
0
def compile_dirname(
    search_path,
    output_path,
    output_style,
    source_comments,
    include_paths,
    precision,
    custom_functions,
    importers,
    source_map_contents,
    source_map_embed,
    omit_source_map_url,
    source_map_root,
):
    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,
                None,
                source_map_contents,
                source_map_embed,
                omit_source_map_url,
                source_map_root,
            )
            if s:
                v = v.decode("UTF-8")
                mkdirp(os.path.dirname(output_filename))
                with io.open(
                    output_filename, "w", encoding="UTF-8", newline="",
                ) as output_file:
                    output_file.write(v)
            else:
                return False, v
    return True, None
Ejemplo n.º 4
0
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
                             <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
                     <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
                             <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
                     <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
                             <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')
                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)
Ejemplo n.º 5
0
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
                             <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
                     <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
                             <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
                     <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
                             <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')
                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)
Ejemplo n.º 6
0
def compile(**kwargs):
    r"""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 source_map_contents: embed include contents in map
    :type source_map_contents: :class:`bool`
    :param source_map_embed: embed sourceMappingUrl as data URI
    :type source_map_embed: :class:`bool`
    :param omit_source_map_url: omit source map URL comment from output
    :type omit_source_map_url: :class:`bool`
    :param source_map_root: base path, will be emitted in source map as is
    :type source_map_root: :class:`str`
    :param include_paths: an optional list of paths to find ``@import``\ ed
                          Sass/CSS source files
    :type include_paths: :class:`collections.abc.Sequence`
    :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
                             <custom-functions_>`_ description
    :type custom_functions: :class:`set`,
                            :class:`collections.abc.Sequence`,
                            :class:`collections.abc.Mapping`
    :param custom_import_extensions: (ignored, for backward compatibility)
    :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
                     <importer-callbacks_>`_ description
    :type importers: :class:`collections.abc.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 source_map_contents: embed include contents in map
    :type source_map_contents: :class:`bool`
    :param source_map_embed: embed sourceMappingUrl as data URI
    :type source_map_embed: :class:`bool`
    :param omit_source_map_url: omit source map URL comment from output
    :type omit_source_map_url: :class:`bool`
    :param source_map_root: base path, will be emitted in source map as is
    :type source_map_root: :class:`str`
    :param include_paths: an optional list of paths to find ``@import``\ ed
                          Sass/CSS source files
    :type include_paths: :class:`collections.abc.Sequence`
    :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
                             <custom-functions_>`_ description
    :type custom_functions: :class:`set`,
                            :class:`collections.abc.Sequence`,
                            :class:`collections.abc.Mapping`
    :param custom_import_extensions: (ignored, for backward compatibility)
    :param importers: optional callback functions.
                     see also below `importer callbacks
                     <importer-callbacks_>`_ description
    :type importers: :class:`collections.abc.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 source_map_contents: embed include contents in map
    :type source_map_contents: :class:`bool`
    :param source_map_embed: embed sourceMappingUrl as data URI
    :type source_map_embed: :class:`bool`
    :param omit_source_map_url: omit source map URL comment from output
    :type omit_source_map_url: :class:`bool`
    :param source_map_root: base path, will be emitted in source map as is
    :type source_map_root: :class:`str`
    :param include_paths: an optional list of paths to find ``@import``\ ed
                          Sass/CSS source files
    :type include_paths: :class:`collections.abc.Sequence`
    :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
                             <custom-functions_>`_ description
    :type custom_functions: :class:`set`,
                            :class:`collections.abc.Sequence`,
                            :class:`collections.abc.Mapping`
    :param custom_import_extensions: (ignored, for backward compatibility)
    :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:`~set`/:class:`~collections.abc.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.abc.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:`~set`/:class:`~collections.abc.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 can accept one or two string arguments. The first argument
    is the path that was passed to the ``@import`` directive; the second
    (optional) argument is the previous resolved path, where the ``@import``
    directive was found. The callbacks must 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, prev):
            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``.

    .. versionadded:: 0.17.0
       Added ``source_map_contents``, ``source_map_embed``,
       ``omit_source_map_url``, and ``source_map_root`` parameters.

    .. versionadded:: 0.18.0
        The importer callbacks can now take a second argument, the previously-
        resolved path, so that importers can do relative path resolution.

    """
    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(
            "{} is unsupported output_style; choose one of {}"
            "".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,
            FutureWarning,
        )
    if not isinstance(source_comments, bool):
        raise TypeError("source_comments must be bool, not " + repr(source_comments),)
    fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()

    def _get_file_arg(key):
        ret = kwargs.pop(key, None)
        if ret is not None and not isinstance(ret, string_types):
            raise TypeError("{} must be a string, not {!r}".format(key, ret))
        elif isinstance(ret, text_type):
            ret = ret.encode(fs_encoding)
        if ret and "filename" not in modes:
            raise CompileError(
                "{} is only available with filename= keyword argument since "
                "has to be aware of it".format(key),
            )
        return ret

    source_map_filename = _get_file_arg("source_map_filename")
    output_filename_hint = _get_file_arg("output_filename_hint")

    source_map_contents = kwargs.pop("source_map_contents", False)
    source_map_embed = kwargs.pop("source_map_embed", False)
    omit_source_map_url = kwargs.pop("omit_source_map_url", False)
    source_map_root = kwargs.pop("source_map_root", None)

    if isinstance(source_map_root, text_type):
        source_map_root = source_map_root.encode("utf-8")

    # #208: cwd is always included in include paths
    include_paths = (os.getcwd(),)
    include_paths += tuple(kwargs.pop("include_paths", ()) or ())
    include_paths = os.pathsep.join(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_abc.Mapping):
        custom_functions = [
            SassFunction.from_lambda(name, lambda_)
            for name, lambda_ in custom_functions.items()
        ]
    elif isinstance(custom_functions, (collections_abc.Set, collections_abc.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),
        )

    if kwargs.pop("custom_import_extensions", None) is not None:
        warnings.warn(
            "`custom_import_extensions` has no effect and will be removed in "
            "a future version.",
            FutureWarning,
        )

    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,
            source_map_contents,
            source_map_embed,
            omit_source_map_url,
            source_map_root,
        )
        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("{!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,
            output_filename_hint,
            source_map_contents,
            source_map_embed,
            omit_source_map_url,
            source_map_root,
        )
        if s:
            v = v.decode("utf-8")
            if source_map_filename:
                source_map = source_map.decode("utf-8")
                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,
            source_map_contents,
            source_map_embed,
            omit_source_map_url,
            source_map_root,
        )
        if s:
            return
    else:
        raise TypeError("something went wrong")
    assert not s
    raise CompileError(v)
Ejemplo n.º 7
0
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: an optional source comments mode of the compiled
                            result.  choose one of ``'none'`` (default) or
                            ``'line_numbers'``.  ``'map'`` is unavailable for
                            ``string``
    :type source_comments: :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 image_path: an optional path to find images
    :type image_path: :class:`str`
    :returns: the compiled CSS string
    :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: an optional source comments mode of the compiled
                            result.  choose one of ``'none'`` (default),
                            ``'line_numbers'``, ``'map'``.
                            if ``'map'`` is used it requires
                            ``source_map_filename`` argument as well and
                            returns a (compiled CSS string,
                            source map string) pair instead of a string
    :type source_comments: :class:`str`
    :param source_map_filename: indicate the source map output filename.
                                it's only available and required
                                when ``source_comments`` is ``'map'``.
                                note that it will ignore all other parts of
                                the path except for its basename
    :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 image_path: an optional path to find images
    :type image_path: :class:`str`
    :returns: the compiled CSS string, or a pair of the compiled CSS string
              and the source map string if ``source_comments='map'``
    :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: an optional source comments mode of the compiled
                            result.  choose one of ``'none'`` (default) or
                            ``'line_numbers'``.  ``'map'`` is unavailable for
                            ``dirname``
    :type source_comments: :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 image_path: an optional path to find images
    :type image_path: :class:`str`
    :raises sass.CompileError: when it fails for any reason
                               (for example the given SASS has broken syntax)

    .. versionadded:: 0.4.0
       Added ``source_comments`` and ``source_map_filename`` parameters.

    """
    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')
    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', 'none')
    if not isinstance(source_comments, string_types):
        raise TypeError('source_comments must be a string, not ' +
                        repr(source_comments))
    if 'filename' not in modes and source_comments == 'map':
        raise CompileError('source_comments="map" is only available with '
                           'filename= keyword argument since it has to be '
                           'aware of it')
    try:
        source_comments = SOURCE_COMMENTS[source_comments]
    except KeyError:
        raise CompileError(
            '{0} is unsupported source_comments; choose one of '
            '{1}'.format(source_comments, and_join(SOURCE_COMMENTS))
        )
    fs_encoding = sys.getfilesystemencoding() or sys.getdefaultencoding()
    try:
        source_map_filename = kwargs.pop('source_map_filename') or b''
    except KeyError:
        if source_comments == SOURCE_COMMENTS['map']:
            raise TypeError('source_comments="map" requires '
                            'source_map_filename argument')
        source_map_filename = b''
    else:
        if source_comments != SOURCE_COMMENTS['map']:
            raise TypeError('source_map_filename is available only with '
                            'source_comments="map"')
        elif not isinstance(source_map_filename, string_types):
            raise TypeError('source_map_filename must be a string, not ' +
                            repr(source_map_filename))
        if isinstance(source_map_filename, text_type):
            source_map_filename = source_map_filename.encode(fs_encoding)
    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)
    try:
        image_path = kwargs.pop('image_path')
    except KeyError:
        image_path = b'.'
    else:
        if not isinstance(image_path, string_types):
            raise TypeError('image_path must be a string, not ' +
                            repr(image_path))
        elif isinstance(image_path, text_type):
            image_path = image_path.encode(fs_encoding)
    if 'string' in modes:
        string = kwargs.pop('string')
        if isinstance(string, text_type):
            string = string.encode('utf-8')
        s, v = compile_string(string,
                              output_style, source_comments,
                              include_paths, image_path)
        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)
        s, v, source_map = compile_filename(
            filename,
            output_style, source_comments,
            include_paths, image_path, source_map_filename
        )
        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)')
        else:
            if isinstance(search_path, text_type):
                search_path = search_path.encode(fs_encoding)
            if isinstance(output_path, text_type):
                output_path = output_path.encode(fs_encoding)
        s, v = compile_dirname(search_path, output_path,
                               output_style, source_comments,
                               include_paths, image_path)
        if s:
            return
    else:
        raise TypeError('something went wrong')
    assert not s
    raise CompileError(v)
Ejemplo n.º 8
0
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
                             <custom-functions>`_ description
    :type custom_functions: :class:`collections.Set`,
                            :class:`collections.Sequence`,
                            :class:`collections.Mapping`
    :returns: the compiled CSS string
    :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.
                                note that it implies ``source_comments``
                                is also :const:`True`
    :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
                             <custom-functions>`_ description
    :type custom_functions: :class:`collections.Set`,
                            :class:`collections.Sequence`,
                            :class:`collections.Mapping`
    :returns: the compiled CSS string, or a pair of the compiled CSS string
              and the source map string if ``source_comments='map'``
    :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
                             <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}
          )

    .. 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.

    """
    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')
    if source_map_filename is not None:
        source_comments = True
    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)
        )

    if 'string' in modes:
        string = kwargs.pop('string')
        if isinstance(string, text_type):
            string = string.encode('utf-8')
        s, v = compile_string(
            string, output_style, source_comments, include_paths, precision,
            custom_functions,
        )
        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)
        s, v, source_map = compile_filename(
            filename, output_style, source_comments, include_paths, precision,
            source_map_filename, custom_functions,
        )
        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)')
        s, v = compile_dirname(
            search_path, output_path, output_style, source_comments,
            include_paths, precision, custom_functions,
        )
        if s:
            return
    else:
        raise TypeError('something went wrong')
    assert not s
    raise CompileError(v)
Ejemplo n.º 9
0
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 image_path: an optional path to find images
    :type image_path: :class:`str`
    :returns: the compiled CSS string
    :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.
                                note that it implies ``source_comments``
                                is also :const:`True`
    :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 image_path: an optional path to find images
    :type image_path: :class:`str`
    :returns: the compiled CSS string, or a pair of the compiled CSS string
              and the source map string if ``source_comments='map'``
    :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 image_path: an optional path to find images
    :type image_path: :class:`str`
    :raises sass.CompileError: when it fails for any reason
                               (for example the given SASS has broken syntax)

    .. 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.

    """
    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')
    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')
    if source_map_filename is not None:
        source_comments = True
    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)
    try:
        image_path = kwargs.pop('image_path')
    except KeyError:
        image_path = b'.'
    else:
        if not isinstance(image_path, string_types):
            raise TypeError('image_path must be a string, not ' +
                            repr(image_path))
        elif isinstance(image_path, text_type):
            image_path = image_path.encode(fs_encoding)
    if 'string' in modes:
        string = kwargs.pop('string')
        if isinstance(string, text_type):
            string = string.encode('utf-8')
        s, v = compile_string(string, output_style, source_comments,
                              include_paths, image_path)
        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)
        s, v, source_map = compile_filename(filename, output_style,
                                            source_comments, include_paths,
                                            image_path, source_map_filename)
        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)')
        else:
            if isinstance(search_path, text_type):
                search_path = search_path.encode(fs_encoding)
            if isinstance(output_path, text_type):
                output_path = output_path.encode(fs_encoding)
        s, v = compile_dirname(search_path, output_path, output_style,
                               source_comments, include_paths, image_path)
        if s:
            return
    else:
        raise TypeError('something went wrong')
    assert not s
    raise CompileError(v)