<commit_before>
"""
The Glashammer Application.
"""

import os

from werkzeug import ClosingIterator, SharedDataMiddleware
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound

from glashammer.utils.config import Configuration

from glashammer.utils.templating import create_template_environment

from glashammer.utils import local, local_manager, EventManager, emit_event, \
    url_for, sibpath, Request



def default_setup_func(app):
    app.add_template_searchpath(sibpath(__file__, 'templates'))


class GlashammerApplication(object):
    """WSGI Application"""

    default_setup = default_setup_func

    def __init__(self, setup_func, instance_dir=None):
        # just for playing in the shell
        local.application = self

        self.finalized = False

        # Start the setup
        if instance_dir is None:
            instance_dir = os.path.dirname(__file__)

        self.instance_dir = os.path.abspath(instance_dir)

        self.config_file = os.path.join(self.instance_dir, 'config.ini')

        if not os.path.exists(self.instance_dir):
            raise RuntimeError('Application instance directory missing')

        self.conf = self.cfg = Configuration(self.config_file)

        self.map = Map()
        self.views = {}
        self.controllers = {}
        self.events = EventManager(self)

        # Temporary variables for collecting setup information

        # Template stuff
        self._template_searchpaths = []
        self._template_globals = {}
        self._template_filters = {}
        self._layout_template = None

        # shared
        self._shared_exports = {}

        # Setup functions (basically plugins)
        self._setup_funcs = set()
        self._osetup_funcs = []

        # Data initialization functions
        self._data_funcs = set()
        self._odata_funcs = []

        # setup the default stuff
        self.default_setup()

        # setup the application
        setup_func(self)

        # run the additional setup funcions
        for setup_func, args in self._osetup_funcs:
            setup_func(self, *args)

        del self._setup_funcs

        # Now the database


        for data_func in self._odata_funcs:
            data_func(self)

        del self._data_funcs



        self._template_globals.update({
            'url_for': url_for,
            'layout_template': local('layout_template'),
            'cfg': self.cfg,
            'request':local('request'),
            'emit_event':self.events.template_emit
        })

        self._template_filters.update({
        })

        # create the template environment
        self.template_env = create_template_environment(
            searchpaths=self._template_searchpaths,
            globals=self._template_globals,
            filters=self._template_filters,
        )

        del self._template_searchpaths
        del self._layout_template


        # now add the middleware for static file serving
        self.add_shared('glashammer', sibpath(__file__, 'shared'))
        self.add_middleware(SharedDataMiddleware, self._shared_exports)

        del self._shared_exports

        # finalize the setup
        self.finalized = True
        # create the template environment
        emit_event('app-setup', self)

    def __call__(self, environ, start_response):
        return ClosingIterator(self.dispatch_request(environ, start_response),
                               [local_manager.cleanup])

    def dispatch_request(self, environ, start_response):
        local.application = self
        local.url_adapter = adapter = self.map.bind_to_environ(environ)
        local.request = request = Request(self, environ)
        emit_event('request-start', request)
        try:
            endpoint, values = adapter.match()
            request.endpoint = endpoint
            request.values = values
            emit_event('request-end', request)
            response = self.get_view(request, endpoint, values)
        except HTTPException, e:
            response = e
        emit_event('response-start', response)
        resp = response(environ, start_response)
        emit_event('response-end', response)
        return resp

    def get_view(self, request, endpoint, values):
        # try looking up by view first
        view = self.views.get(endpoint)
        if view:
            return view(request, **values)
        elif '/' in endpoint:
            # fallback to controller->view
            base, target = endpoint.split('/', 1)
            controller = self.controllers.get(base)
            if controller is not None and hasattr(controller, target):
                return getattr(controller, target)(request, **values)
        return NotFound()


    def _prefinalize_only(f):
        def _decorated(self, *args, **kw):
            if self.finalized:
                raise RuntimeError('Already Finalized')
            return f(self, *args, **kw)
        _decorated.__doc__ = f.__doc__
        _decorated.__name__ = f.__name__
        _decorated.__module__ = f.__module__
        return _decorated

    def add_setup(self, setup_func, *args):
        """Add a setup callable to be called on startup by the application.

        `setup_func`
            The callable to be called during application setup.

        `*args`
            Arguments that will be passed to the setup function

        This method is used to add pluggable capability to the application.
        For example, plugin A can load plugin B by importing and adding it's
        setup func like so::

            >>> from a import setup
            >>> app.add_setup(a)

        Or in a real example::

            >>> from glashammer.bundles.auth import setup_app
            >>> app.add_setup(setup_app)

        Will initialize the auth bundle for the application.
        """
        vals = (setup_func, args)
        if vals not in self._setup_funcs:
            self._setup_funcs.add(vals)
            self._osetup_funcs.append(vals)

    @_prefinalize_only<commit_msg>[project @ <EMAIL>-20080729182234-voe4z0bephzz1p2u] typo in docstring<commit_after>
"""
The Glashammer Application.
"""

import os

from werkzeug import ClosingIterator, SharedDataMiddleware
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException, NotFound

from glashammer.utils.config import Configuration

from glashammer.utils.templating import create_template_environment

from glashammer.utils import local, local_manager, EventManager, emit_event, \
    url_for, sibpath, Request



def default_setup_func(app):
    app.add_template_searchpath(sibpath(__file__, 'templates'))


class GlashammerApplication(object):
    """WSGI Application"""

    default_setup = default_setup_func

    def __init__(self, setup_func, instance_dir=None):
        # just for playing in the shell
        local.application = self

        self.finalized = False

        # Start the setup
        if instance_dir is None:
            instance_dir = os.path.dirname(__file__)

        self.instance_dir = os.path.abspath(instance_dir)

        self.config_file = os.path.join(self.instance_dir, 'config.ini')

        if not os.path.exists(self.instance_dir):
            raise RuntimeError('Application instance directory missing')

        self.conf = self.cfg = Configuration(self.config_file)

        self.map = Map()
        self.views = {}
        self.controllers = {}
        self.events = EventManager(self)

        # Temporary variables for collecting setup information

        # Template stuff
        self._template_searchpaths = []
        self._template_globals = {}
        self._template_filters = {}
        self._layout_template = None

        # shared
        self._shared_exports = {}

        # Setup functions (basically plugins)
        self._setup_funcs = set()
        self._osetup_funcs = []

        # Data initialization functions
        self._data_funcs = set()
        self._odata_funcs = []

        # setup the default stuff
        self.default_setup()

        # setup the application
        setup_func(self)

        # run the additional setup funcions
        for setup_func, args in self._osetup_funcs:
            setup_func(self, *args)

        del self._setup_funcs

        # Now the database


        for data_func in self._odata_funcs:
            data_func(self)

        del self._data_funcs



        self._template_globals.update({
            'url_for': url_for,
            'layout_template': local('layout_template'),
            'cfg': self.cfg,
            'request':local('request'),
            'emit_event':self.events.template_emit
        })

        self._template_filters.update({
        })

        # create the template environment
        self.template_env = create_template_environment(
            searchpaths=self._template_searchpaths,
            globals=self._template_globals,
            filters=self._template_filters,
        )

        del self._template_searchpaths
        del self._layout_template


        # now add the middleware for static file serving
        self.add_shared('glashammer', sibpath(__file__, 'shared'))
        self.add_middleware(SharedDataMiddleware, self._shared_exports)

        del self._shared_exports

        # finalize the setup
        self.finalized = True
        # create the template environment
        emit_event('app-setup', self)

    def __call__(self, environ, start_response):
        return ClosingIterator(self.dispatch_request(environ, start_response),
                               [local_manager.cleanup])

    def dispatch_request(self, environ, start_response):
        local.application = self
        local.url_adapter = adapter = self.map.bind_to_environ(environ)
        local.request = request = Request(self, environ)
        emit_event('request-start', request)
        try:
            endpoint, values = adapter.match()
            request.endpoint = endpoint
            request.values = values
            emit_event('request-end', request)
            response = self.get_view(request, endpoint, values)
        except HTTPException, e:
            response = e
        emit_event('response-start', response)
        resp = response(environ, start_response)
        emit_event('response-end', response)
        return resp

    def get_view(self, request, endpoint, values):
        # try looking up by view first
        view = self.views.get(endpoint)
        if view:
            return view(request, **values)
        elif '/' in endpoint:
            # fallback to controller->view
            base, target = endpoint.split('/', 1)
            controller = self.controllers.get(base)
            if controller is not None and hasattr(controller, target):
                return getattr(controller, target)(request, **values)
        return NotFound()


    def _prefinalize_only(f):
        def _decorated(self, *args, **kw):
            if self.finalized:
                raise RuntimeError('Already Finalized')
            return f(self, *args, **kw)
        _decorated.__doc__ = f.__doc__
        _decorated.__name__ = f.__name__
        _decorated.__module__ = f.__module__
        return _decorated

    def add_setup(self, setup_func, *args):
        """Add a setup callable to be called on startup by the application.

        `setup_func`
            The callable to be called during application setup.

        `*args`
            Arguments that will be passed to the setup function

        This method is used to add pluggable capability to the application.
        For example, plugin A can load plugin B by importing and adding it's
        setup func like so::

            >>> from a import setup
            >>> app.add_setup(setup)

        Or in a real example::

            >>> from glashammer.bundles.auth import setup_app
            >>> app.add_setup(setup_app)

        Will initialize the auth bundle for the application.
        """
        vals = (setup_func, args)
        if vals not in self._setup_funcs:
            self._setup_funcs.add(vals)
            self._osetup_funcs.append(vals)

    @_prefinalize_only
{'fraction_non_alphanumeric': 0.08196317000986518, 'fraction_numerical': 0.001644195988161789, 'mean_word_length': 2.278975741239892, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 30, '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': '207644', 'n_tokens_mistral': 3303, 'n_tokens_neox': 3202, 'n_words': 841}