<commit_before># -*- coding: utf-8 -*-
#
# Copyright (C) 2016 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

"""
Plantweb main rendering module.
"""

from __future__ import unicode_literals, absolute_import
from __future__ import print_function, division

import logging
from hashlib import sha256
from distutils.dir_util import mkpath
from os.path import basename, splitext, isfile, expanduser, join

from .plantuml import plantuml
from .defaults import read_defaults


log = logging.getLogger(__name__)


WRAP_STR = {
    'plantuml': 'uml',
    'ditaa': 'ditaa',
    'graphviz': 'dot'
}
"""
Map between the name of the engine and the wrap string used in the
``@startXXX`` directive.
"""


def determine_engine(content):
    """
    Determine the engine used in the given content.

    The engine is determined by the ``@startXXX`` used at the beginning of the
    file. Possible values are:

    ::

        @startuml --> plantuml
        @startdot --> graphviz
        @startditaa --> ditaa

    :param str content: Content to analyze.
    :return: The name of the engine found, or None.
    :rtype: str
    """
    if content.startswith('@startuml'):
        return 'plantuml'
    if content.startswith('@startdot'):
        return 'graphviz'
    if content.startswith('@startditaa'):
        return 'ditaa'
    return None


def render_cached(
        server, format, content,
        use_cache=None, cache_dir=None):
    """
    Render given content in the PlantUML server or fetch it from cache.

    :param str server: URL to PlantUML server.
    :param str format: File format to render the content. One of the supported
     by the PlantUML server (``svg`` or ``png``).
    :param str content: Content to render with mandatory ``@startxxx`` tags.
    :param bool use_cache: Use local cache to avoid requesting the server for
     already rendered diagrams. If ``None``, the default value will be used.
    :param str cache_dir: Directory to store the cached diagrams. If ``None``
     the default value will be used.

    :return: A tuple of ``(content, sha)`` with the bytes of the rendered
     content and a string of the sha256 identifying the content for cache.
     Note that ``sha`` can be None if ``use_cache`` is ``False``.
    :rtype: tuple
    """

    if use_cache is None:
        use_cache = read_defaults()['use_cache']

    if not use_cache:
        return (
            plantuml(server, format, content),
            None
        )

    if cache_dir is None:
        cache_dir = read_defaults()['cache_dir']
    cache_dir = expanduser(cache_dir)

    sha = sha256(content.encode('utf-8')).hexdigest()

    cache_file = join(
        cache_dir, '{}.{}'.format(sha, format)
    )

    # Use cache if available
    log.debug('Trying to load cache file {} ...'.format(cache_file))<commit_msg>fix: dev: Better always return the sha of the rendered content even if cache wasn't used.<commit_after># -*- coding: utf-8 -*-
#
# Copyright (C) 2016 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.

"""
Plantweb main rendering module.
"""

from __future__ import unicode_literals, absolute_import
from __future__ import print_function, division

import logging
from hashlib import sha256
from distutils.dir_util import mkpath
from os.path import basename, splitext, isfile, expanduser, join

from .plantuml import plantuml
from .defaults import read_defaults


log = logging.getLogger(__name__)


WRAP_STR = {
    'plantuml': 'uml',
    'ditaa': 'ditaa',
    'graphviz': 'dot'
}
"""
Map between the name of the engine and the wrap string used in the
``@startXXX`` directive.
"""


def determine_engine(content):
    """
    Determine the engine used in the given content.

    The engine is determined by the ``@startXXX`` used at the beginning of the
    file. Possible values are:

    ::

        @startuml --> plantuml
        @startdot --> graphviz
        @startditaa --> ditaa

    :param str content: Content to analyze.
    :return: The name of the engine found, or None.
    :rtype: str
    """
    if content.startswith('@startuml'):
        return 'plantuml'
    if content.startswith('@startdot'):
        return 'graphviz'
    if content.startswith('@startditaa'):
        return 'ditaa'
    return None


def render_cached(
        server, format, content,
        use_cache=None, cache_dir=None):
    """
    Render given content in the PlantUML server or fetch it from cache.

    :param str server: URL to PlantUML server.
    :param str format: File format to render the content. One of the supported
     by the PlantUML server (``svg`` or ``png``).
    :param str content: Content to render with mandatory ``@startxxx`` tags.
    :param bool use_cache: Use local cache to avoid requesting the server for
     already rendered diagrams. If ``None``, the default value will be used.
    :param str cache_dir: Directory to store the cached diagrams. If ``None``
     the default value will be used.

    :return: A tuple of ``(content, sha)`` with the bytes of the rendered
     content and a sha256 hash string identifying the content.
    :rtype: tuple
    """
    sha = sha256(content.encode('utf-8')).hexdigest()

    if use_cache is None:
        use_cache = read_defaults()['use_cache']

    if not use_cache:
        return (
            plantuml(server, format, content),
            sha
        )

    if cache_dir is None:
        cache_dir = read_defaults()['cache_dir']
    cache_dir = expanduser(cache_dir)

    cache_file = join(
        cache_dir, '{}.{}'.format(sha, format)
    )

    # Use cache if available
    log.debug('Trying to load cache file {} ...'.format(cache_file))
{'fraction_non_alphanumeric': 0.09680819030412527, 'fraction_numerical': 0.0057211683227943394, 'mean_word_length': 3.133789670192906, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6850001', 'n_tokens_mistral': 1963, 'n_tokens_neox': 1886, 'n_words': 771}