<commit_before>import os
import warnings

import six
from six.moves import builtins

import cherrypy


class Checker(object):

    """A checker for CherryPy sites and their mounted applications.

    When this object is called at engine startup, it executes each
    of its own methods whose names start with ``check_``. If you wish
    to disable selected checks, simply add a line in your global
    config which sets the appropriate method to False::

        [global]
        checker.check_skipped_app_config = False

    You may also dynamically add or replace ``check_*`` methods in this way.
    """

    on = True
    """If True (the default), run all checks; if False, turn off all checks."""

    def __init__(self):
        self._populate_known_types()

    def __call__(self):
        """Run all check_* methods."""
        if self.on:
            oldformatwarning = warnings.formatwarning
            warnings.formatwarning = self.formatwarning
            try:
                for name in dir(self):
                    if name.startswith('check_'):
                        method = getattr(self, name)
                        if method and hasattr(method, '__call__'):
                            method()
            finally:
                warnings.formatwarning = oldformatwarning

    def formatwarning(self, message, category, filename, lineno, line=None):
        """Function to format a warning."""
        return 'CherryPy Checker:\n%s\n\n' % message

    # This value should be set inside _cpconfig.
    global_config_contained_paths = False

    def check_app_config_entries_dont_start_with_script_name(self):
        """Check for Application config with sections that repeat script_name.
        """
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                continue
            if sn == '':
                continue
            sn_atoms = sn.strip('/').split('/')
            for key in app.config.keys():
                key_atoms = key.strip('/').split('/')
                if key_atoms[:len(sn_atoms)] == sn_atoms:
                    warnings.warn(
                        'The application mounted at %r has config '
                        'entries that start with its script name: %r' % (sn,
                                                                         key))

    def check_site_config_entries_in_app_config(self):
        """Check for mounted Applications that have site-scoped config."""
        for sn, app in six.iteritems(cherrypy.tree.apps):
            if not isinstance(app, cherrypy.Application):
                continue

            msg = []
            for section, entries in six.iteritems(app.config):
                if section.startswith('/'):
                    for key, value in six.iteritems(entries):
                        for n in ('engine.', 'server.', 'tree.', 'checker.'):
                            if key.startswith(n):
                                msg.append('[%s] %s = %s' %
                                           (section, key, value))
            if msg:
                msg.insert(0,
                           'The application mounted at %r contains the '
                           'following config entries, which are only allowed '
                           'in site-wide config. Move them to a [global] '
                           'section and pass them to cherrypy.config.update() '
                           'instead of tree.mount().' % sn)
                warnings.warn(os.linesep.join(msg))

    def check_skipped_app_config(self):
        """Check for mounted Applications that have no config."""
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                msg = 'The Application mounted at %r has an empty config.' % sn
                if self.global_config_contained_paths:
                    msg += (' It looks like the config you passed to '
                            'cherrypy.config.update() contains application-'
                            'specific sections. You must explicitly pass '
                            'application config via '
                            'cherrypy.tree.mount(..., config=app_config)')
                warnings.warn(msg)
                return

    def check_app_config_brackets(self):
        """Check for Application config with extraneous brackets in section
        names.
        """
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                continue
            for key in app.config.keys():
                if key.startswith('[') or key.endswith(']'):
                    warnings.warn(
                        'The application mounted at %r has config '
                        'section names with extraneous brackets: %r. '
                        'Config *files* need brackets; config *dicts* '
                        '(e.g. passed to tree.mount) do not.' % (sn, key))

    def check_static_paths(self):
        """Check Application config for incorrect static paths."""
        # Use the dummy Request object in the main thread.
        request = cherrypy.request
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            request.app = app<commit_msg>Make cherrypy._cpchecker PEP257-compliant<commit_after>"""Checker for CherryPy sites and mounted apps."""
import os
import warnings

import six
from six.moves import builtins

import cherrypy


class Checker(object):
    """A checker for CherryPy sites and their mounted applications.

    When this object is called at engine startup, it executes each
    of its own methods whose names start with ``check_``. If you wish
    to disable selected checks, simply add a line in your global
    config which sets the appropriate method to False::

        [global]
        checker.check_skipped_app_config = False

    You may also dynamically add or replace ``check_*`` methods in this way.
    """

    on = True
    """If True (the default), run all checks; if False, turn off all checks."""

    def __init__(self):
        """Initialize Checker instance."""
        self._populate_known_types()

    def __call__(self):
        """Run all check_* methods."""
        if self.on:
            oldformatwarning = warnings.formatwarning
            warnings.formatwarning = self.formatwarning
            try:
                for name in dir(self):
                    if name.startswith('check_'):
                        method = getattr(self, name)
                        if method and hasattr(method, '__call__'):
                            method()
            finally:
                warnings.formatwarning = oldformatwarning

    def formatwarning(self, message, category, filename, lineno, line=None):
        """Function to format a warning."""
        return 'CherryPy Checker:\n%s\n\n' % message

    # This value should be set inside _cpconfig.
    global_config_contained_paths = False

    def check_app_config_entries_dont_start_with_script_name(self):
        """Check for App config with sections that repeat script_name."""
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                continue
            if sn == '':
                continue
            sn_atoms = sn.strip('/').split('/')
            for key in app.config.keys():
                key_atoms = key.strip('/').split('/')
                if key_atoms[:len(sn_atoms)] == sn_atoms:
                    warnings.warn(
                        'The application mounted at %r has config '
                        'entries that start with its script name: %r' % (sn,
                                                                         key))

    def check_site_config_entries_in_app_config(self):
        """Check for mounted Applications that have site-scoped config."""
        for sn, app in six.iteritems(cherrypy.tree.apps):
            if not isinstance(app, cherrypy.Application):
                continue

            msg = []
            for section, entries in six.iteritems(app.config):
                if section.startswith('/'):
                    for key, value in six.iteritems(entries):
                        for n in ('engine.', 'server.', 'tree.', 'checker.'):
                            if key.startswith(n):
                                msg.append('[%s] %s = %s' %
                                           (section, key, value))
            if msg:
                msg.insert(0,
                           'The application mounted at %r contains the '
                           'following config entries, which are only allowed '
                           'in site-wide config. Move them to a [global] '
                           'section and pass them to cherrypy.config.update() '
                           'instead of tree.mount().' % sn)
                warnings.warn(os.linesep.join(msg))

    def check_skipped_app_config(self):
        """Check for mounted Applications that have no config."""
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                msg = 'The Application mounted at %r has an empty config.' % sn
                if self.global_config_contained_paths:
                    msg += (' It looks like the config you passed to '
                            'cherrypy.config.update() contains application-'
                            'specific sections. You must explicitly pass '
                            'application config via '
                            'cherrypy.tree.mount(..., config=app_config)')
                warnings.warn(msg)
                return

    def check_app_config_brackets(self):
        """Check for App config with extraneous brackets in section names."""
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            if not app.config:
                continue
            for key in app.config.keys():
                if key.startswith('[') or key.endswith(']'):
                    warnings.warn(
                        'The application mounted at %r has config '
                        'section names with extraneous brackets: %r. '
                        'Config *files* need brackets; config *dicts* '
                        '(e.g. passed to tree.mount) do not.' % (sn, key))

    def check_static_paths(self):
        """Check Application config for incorrect static paths."""
        # Use the dummy Request object in the main thread.
        request = cherrypy.request
        for sn, app in cherrypy.tree.apps.items():
            if not isinstance(app, cherrypy.Application):
                continue
            request.app = app
{'fraction_non_alphanumeric': 0.08838496562806893, 'fraction_numerical': 0.0004463887152932774, 'mean_word_length': 1.5540355677154583, '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': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6777056', 'n_tokens_mistral': 2782, 'n_tokens_neox': 2623, 'n_words': 911}