<commit_before>from cherrypy import _cpconfig, _cplogging, _cpwsgi


class Application(object):
    """A CherryPy Application.
    
    An instance of this class may also be used as a WSGI callable
    (WSGI application object) for itself.
    
    root: the top-most container of page handlers for this app.
    script_name: the URL "mount point" for this app; for example,
        if script_name is "/my/cool/app", then the URL
        "http://my.domain.tld/my/cool/app/page1" might be handled
        by a "page1" method on the root object. If script_name is
        explicitly set to None, then CherryPy will attempt to provide
        it each time from request.wsgi_environ['SCRIPT_NAME'].
    conf: a dict of {path: pathconf} pairs, where 'pathconf' is itself
        a dict of {key: value} pairs.
    """
    
    def __init__(self, root, script_name="", conf=None):
        self.log = _cplogging.LogManager(id(self))
        self.root = root
        self.script_name = script_name
        self.namespaces = {"log": lambda k, v: setattr(self.log, k, v),
                           }
        self.conf = {}
        if conf:
            self.merge(conf)
    
    def _get_script_name(self):
        if self._script_name is None:
            # None signals that the script name should be pulled from WSGI environ.
            import cherrypy
            return cherrypy.request.wsgi_environ['SCRIPT_NAME']
        return self._script_name
    def _set_script_name(self, value):
        self._script_name = value
    script_name = property(fget=_get_script_name, fset=_set_script_name)
    
    def merge(self, conf):
        """Merge the given config into self.config."""
        _cpconfig.merge(self.conf, conf)
        
        # Create log handlers as specified in config.
        rootconf = self.conf.get("/", {})
        for k, v in rootconf.iteritems():
            atoms = k.split(".", 1)
            namespace = atoms[0]
            if namespace in self.namespaces:
                self.namespaces[namespace](atoms[1], v)
    
    def guess_abs_path(self):
        """Guess the absolute URL from server.socket_host and script_name.
        
        When inside a request, the abs_path can be formed via:
            cherrypy.request.base + (cherrypy.request.app.script_name or "/")
        
        However, outside of the request we must guess, hoping the deployer
        set socket_host and socket_port correctly.
        """
        port = cherrypy.server.socket_port
        if port in (443, 8443):
            scheme = "https://"
        else:
            scheme = "http://"
        host = cherrypy.server.socket_host
        if port != 80:
            host += ":%s" % port
        return scheme + host + self.script_name
    
    def __call__(self, environ, start_response):
        return _cpwsgi._wsgi_callable(environ, start_response, app=self)


class Tree(object):
    """A registry of CherryPy applications, mounted at diverse points.
    
    An instance of this class may also be used as a WSGI callable
    (WSGI application object), in which case it dispatches to all
    mounted apps.
    
    apps: a dict of the form {script name: application}, where "script name"
        is a string declaring the URL mount point (no trailing slash),
        and "application" is an instance of cherrypy.Application (or an
        arbitrary WSGI callable if you happen to be using a WSGI server).
    """
    
    def __init__(self):
        self.apps = {}
    
    def mount(self, root, script_name="", conf=None):
        """Mount a new app from a root object, script_name, and conf."""
        # Next line both 1) strips trailing slash and 2) maps "/" -> "".
        script_name = script_name.rstrip("/")
        app = Application(root, script_name, conf)
        self.apps[script_name] = app
        
        # If mounted at "", add favicon.ico
        if script_name == "" and root and not hasattr(root, "favicon_ico"):
            import os
            from cherrypy import tools
            favicon = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                   "favicon.ico")
            root.favicon_ico = tools.staticfile.handler(favicon)
        
        return app
    
    def graft(self, wsgi_callable, script_name=""):
        """Mount a wsgi callable at the given script_name."""
        # Next line both 1) strips trailing slash and 2) maps "/" -> "".
        script_name = script_name.rstrip("/")
        self.apps[script_name] = wsgi_callable
    
    def script_name(self, path=None):
        """The script_name of the app at the given path, or None.
        
        If path is None, cherrypy.request.path is used.
        """
        
        if path is None:
            try:
                import cherrypy
                path = cherrypy.request.path
            except AttributeError:<commit_msg>Moved merge out of {{{Application.__init__}}} so custom namespaces can be defined per-app. Also allow Tree.mount to accept an Application instance (instead of a root which gets wrapped in an Application).<commit_after>from cherrypy import _cpconfig, _cplogging, _cpwsgi


class Application(object):
    """A CherryPy Application.
    
    An instance of this class may also be used as a WSGI callable
    (WSGI application object) for itself.
    
    root: the top-most container of page handlers for this app.
    script_name: the URL "mount point" for this app; for example,
        if script_name is "/my/cool/app", then the URL
        "http://my.domain.tld/my/cool/app/page1" might be handled
        by a "page1" method on the root object. If script_name is
        explicitly set to None, then CherryPy will attempt to provide
        it each time from request.wsgi_environ['SCRIPT_NAME'].
    conf: a dict of {path: pathconf} pairs, where 'pathconf' is itself
        a dict of {key: value} pairs.
    """
    
    def __init__(self, root, script_name=""):
        self.log = _cplogging.LogManager(id(self))
        self.root = root
        self.script_name = script_name
        self.namespaces = {"log": lambda k, v: setattr(self.log, k, v),
                           }
        self.conf = {}
    
    def _get_script_name(self):
        if self._script_name is None:
            # None signals that the script name should be pulled from WSGI environ.
            import cherrypy
            return cherrypy.request.wsgi_environ['SCRIPT_NAME']
        return self._script_name
    def _set_script_name(self, value):
        self._script_name = value
    script_name = property(fget=_get_script_name, fset=_set_script_name)
    
    def merge(self, conf):
        """Merge the given config into self.config."""
        _cpconfig.merge(self.conf, conf)
        
        # Handle namespaces specified in config.
        rootconf = self.conf.get("/", {})
        for k, v in rootconf.iteritems():
            atoms = k.split(".", 1)
            namespace = atoms[0]
            if namespace in self.namespaces:
                self.namespaces[namespace](atoms[1], v)
    
    def guess_abs_path(self):
        """Guess the absolute URL from server.socket_host and script_name.
        
        When inside a request, the abs_path can be formed via:
            cherrypy.request.base + (cherrypy.request.app.script_name or "/")
        
        However, outside of the request we must guess, hoping the deployer
        set socket_host and socket_port correctly.
        """
        port = cherrypy.server.socket_port
        if port in (443, 8443):
            scheme = "https://"
        else:
            scheme = "http://"
        host = cherrypy.server.socket_host
        if port != 80:
            host += ":%s" % port
        return scheme + host + self.script_name
    
    def __call__(self, environ, start_response):
        return _cpwsgi._wsgi_callable(environ, start_response, app=self)


class Tree(object):
    """A registry of CherryPy applications, mounted at diverse points.
    
    An instance of this class may also be used as a WSGI callable
    (WSGI application object), in which case it dispatches to all
    mounted apps.
    
    apps: a dict of the form {script name: application}, where "script name"
        is a string declaring the URL mount point (no trailing slash),
        and "application" is an instance of cherrypy.Application (or an
        arbitrary WSGI callable if you happen to be using a WSGI server).
    """
    
    def __init__(self):
        self.apps = {}
    
    def mount(self, root, script_name="", conf=None):
        """Mount a new app from a root object, script_name, and conf."""
        # Next line both 1) strips trailing slash and 2) maps "/" -> "".
        script_name = script_name.rstrip("/")
        
        if isinstance(root, Application):
            app = root
        else:
            app = Application(root, script_name)
            
            # If mounted at "", add favicon.ico
            if script_name == "" and root and not hasattr(root, "favicon_ico"):
                import os
                from cherrypy import tools
                favicon = os.path.join(os.getcwd(), os.path.dirname(__file__),
                                       "favicon.ico")
                root.favicon_ico = tools.staticfile.handler(favicon)
        
        if conf:
            app.merge(conf)
        
        self.apps[script_name] = app
        
        return app
    
    def graft(self, wsgi_callable, script_name=""):
        """Mount a wsgi callable at the given script_name."""
        # Next line both 1) strips trailing slash and 2) maps "/" -> "".
        script_name = script_name.rstrip("/")
        self.apps[script_name] = wsgi_callable
    
    def script_name(self, path=None):
        """The script_name of the app at the given path, or None.
        
        If path is None, cherrypy.request.path is used.
        """
        
        if path is None:
            try:
                import cherrypy
                path = cherrypy.request.path
            except AttributeError:
{'fraction_non_alphanumeric': 0.09042023501294563, 'fraction_numerical': 0.0035849432383987254, 'mean_word_length': 2.0609570252971654, 'pattern_counts': {'":': 4, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7418213', 'n_tokens_mistral': 2900, 'n_tokens_neox': 2797, 'n_words': 964}