<commit_before>import os

from jinja2 import Environment, FileSystemLoader

from .apptemplate import TemplateFile
from .utils import chdir


class ContextMutator:
    """Mutator applying additional transformations to template get_context."""

    def __init__(self, maker):
        """
        :param AppMaker maker:
        """
        self._maker = maker
        self._context = maker.settings

    def get_app_title_rst(self, continuation=''):
        """Returns application title for RST."""

        if continuation:
            continuation = ' ' + continuation

        title = self._context['app_name'] + continuation
        title = '%s\n%s' % (title, '=' * len(title))

        return title

    def get_context(self):
        maker = self._maker
        context = dict(self._context)

        license_tuple = maker.LICENSES.get(context['license'], maker.LICENSES[maker.default_license])

        context.update({
            'get_app_title_rst': self.get_app_title_rst,
            'license_title': license_tuple[0],
            'license_title_pypi': license_tuple[1],
            'python_version_major': context['python_version'].split('.')[0],
            'module_name_capital': context['module_name'].capitalize(),
        })

        return context


class Renderer:
    """Performs file rendering."""

    def __init__(self, maker, paths):
        self.context_mutator = ContextMutator(maker=maker)

        paths = paths[:]
        paths.extend([
            # self.path_templates_license,
            '.',  # Use current working dir.
        ])

        self.env = Environment(
            loader=DynamicParentLoader(paths),
            keep_trailing_newline=True,
            trim_blocks=True,
        )

    def render(self, filename):
        """Renders file contents with settings as get_context.

        :param str|TemplateFile filename:
        :rtype: str
        """
        context = self.context_mutator.get_context()

        filename_ = '%s' % filename

        with chdir(os.path.dirname(filename_)):
            template = self.env.get_template(os.path.basename(filename_))

        if isinstance(filename, TemplateFile):
            # Let's compute template inheritance hierarchy for `parent_template`
            # context dynamic variable.
            parent_paths = filename.parent_paths

            if parent_paths:
                parent_template = DynamicParentTemplate(parent_paths)

            else:
                parent_template = 'unset_for_%s' % filename.path_rel

            context['parent_template'] = parent_template

        rendered = template.render(**context)

        return rendered


class DynamicParentTemplate:
    """Represents jinja dynamic `parent_template` variable."""

    def __init__(self, parents):
        parents = parents[::-1]
        self.parents = parents
        self.parents_initial = parents[:]

    @property
    def current(self):

        try:
            current = self.parents.pop()

        except IndexError:
            # Mostly for template inheritance debug purposes.
            raise IndexError('No more parents to pop. Initial parents: %s' % self.parents_initial)

        return current

    def __repr__(self):<commit_msg>Rendering search paths change.<commit_after>import os

from jinja2 import Environment, FileSystemLoader

from .apptemplate import TemplateFile
from .utils import chdir


class ContextMutator:
    """Mutator applying additional transformations to template get_context."""

    def __init__(self, maker):
        """
        :param AppMaker maker:
        """
        self._maker = maker
        self._context = maker.settings

    def get_app_title_rst(self, continuation=''):
        """Returns application title for RST."""

        if continuation:
            continuation = ' ' + continuation

        title = self._context['app_name'] + continuation
        title = '%s\n%s' % (title, '=' * len(title))

        return title

    def get_context(self):
        maker = self._maker
        context = dict(self._context)

        license_tuple = maker.LICENSES.get(context['license'], maker.LICENSES[maker.default_license])

        context.update({
            'get_app_title_rst': self.get_app_title_rst,
            'license_title': license_tuple[0],
            'license_title_pypi': license_tuple[1],
            'python_version_major': context['python_version'].split('.')[0],
            'module_name_capital': context['module_name'].capitalize(),
        })

        return context


class Renderer:
    """Performs file rendering."""

    def __init__(self, maker, paths):
        self.context_mutator = ContextMutator(maker=maker)

        paths = list({}.fromkeys(paths).keys())  # Unique.
        paths.insert(0, '.')  # Use current working dir.

        self.env = Environment(
            loader=DynamicParentLoader(paths),
            keep_trailing_newline=True,
            trim_blocks=True,
        )

    def render(self, filename):
        """Renders file contents with settings as get_context.

        :param str|TemplateFile filename:
        :rtype: str
        """
        context = self.context_mutator.get_context()

        filename_ = '%s' % filename

        with chdir(os.path.dirname(filename_)):
            template = self.env.get_template(os.path.basename(filename_))

        if isinstance(filename, TemplateFile):
            # Let's compute template inheritance hierarchy for `parent_template`
            # context dynamic variable.
            parent_paths = filename.parent_paths

            if parent_paths:
                parent_template = DynamicParentTemplate(parent_paths)

            else:
                parent_template = 'no-parent-for/%s' % filename.path_rel

            context['parent_template'] = parent_template

        rendered = template.render(**context)

        return rendered


class DynamicParentTemplate:
    """Represents jinja dynamic `parent_template` variable."""

    def __init__(self, parents):
        parents = parents[::-1]
        self.parents = parents
        self.parents_initial = parents[:]

    @property
    def current(self):

        try:
            current = self.parents.pop()

        except IndexError:
            # Mostly for template inheritance debug purposes.
            raise IndexError('No more parents to pop. Initial parents: %s' % self.parents_initial)

        return current

    def __repr__(self):
{'fraction_non_alphanumeric': 0.10115157173980703, 'fraction_numerical': 0.0017117958294428882, 'mean_word_length': 2.3719832109129064, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '5284334', 'n_tokens_mistral': 1744, 'n_tokens_neox': 1648, 'n_words': 398}