<commit_before>"""Utilities to start a server process."""
import warnings
import sys
import os
import logging
from distutils.version import Version


try:
    import openerp
except ImportError:
    warnings.warn("This must be imported with a buildout openerp recipe "
                  "driven sys.path", RuntimeWarning)
else:
    try:
        from openerp.cli import server as startup
    except ImportError:
        from .backports.cli import server as startup
    from openerp.tools import config
    from openerp import SUPERUSER_ID
    from openerp.tools.parse_version import parse_version

from optparse import OptionParser  # we support python >= 2.6

logger = logging.getLogger(__name__)

DEFAULT_VERSION_PARAMETER = 'buildout.db_version'

DEFAULT_VERSION_FILE = 'VERSION.txt'


class OpenERPVersion(Version):
    """Odoo idea of version, wrapped in a class.

    This is based on :meth:`openerp.tools.parse_version`, and
    Provides straight-ahead comparison with tuples of integers, or
    distutils Version classes.
    """

    def parse(self, incoming):
        if isinstance(incoming, OpenERPVersion):
            self.vstring = incoming.vstring
            self.components = incoming.components
        else:
            self.vstring = incoming
            self.components = parse_version(incoming)

    def __str__(self):
        return self.vstring

    def __repr__(self):
        return 'OpenERPVersion(%r)' % str(self)

    def __cmp__(self, other):
        if isinstance(other, tuple):
            other = '.'.join(str(s) for s in other)
        elif not isinstance(other, self.__class__):
            other = str(other)  # Works with distutils' Version classes

        other = self.__class__(other)
        return cmp(self.components, other.components)


class Session(object):
    """A class to give server-level access to one database.

    There should be exactly one instance of this class per process.
    It can be used for any kind of script involving Odoo API, and provides
    facilities for upgrade scripts (see also
    :mod:anybox.recipe.odoo.runtime.upgrade)

    Before actual use, call :meth:`open`.
    Then you'll have useful attributes and methods reminiscent of the unit test
    classes:

    * :attr:`cr`: a cursor
    * :attr:`uid`: user id
    * :attr:`registry`: access to model objects
    * :attr:`is_initialization`: True if and only if the database was not
      initialized before the call to :meth:`open`

    Example application code::

       session.open(db_name="my_db")
       admin = session.registry('res_users').browse(session.cr, session.uid, 1)
       (...)
       session.cr.commit()
       session.close()

    Transaction management is up to user code

    Upgrade scripts writers should check the version handling properties:

    * :meth:`db_version`
    * :meth:`package_version`

    Instantiation is done by passing the path to Odoo main
    configuration file and the path of the buildout directory.

    Usually, instantiation code is written by the recipe in the body of the
    executable "Odoo scripts" it produces.
    Script writers provide a callable that takes a
    :class:`.Session` object argument and declare it as a console script entry
    point in their distribution.
    End users can reference such entry points in their buildout configurations
    to have buildout produce the actual executable. See :doc:`/scripts`
    for details.

    Upgrade scripts are a special case of that process, in which the entry
    point is actually provided by the recipe and rewraps a user-level
    source script.

    Later versions of the recipe may find a way to pass the whole buildout
    configuration (recall that this is to be used in a separate process in
    which the buildout configuration has not been parsed).
    """

    def __init__(self, conffile, buildout_dir, parse_config=True):
        self.buildout_dir = buildout_dir
        self.openerp_config_file = conffile

        self._registry = self.cr = None
        if parse_config:
            config.parse_config(['-c', conffile])

    def ready(self):
        return self._registry is not None

    def open(self, db=None, with_demo=False):
        """Load the database

        Loading an empty database in Odoo has the side effect of installing
        the ``base`` module. Whether to loading demo data or not has therefore
        to be decided right away.

        :param db: database name. If not specified, the same cascading of
                   defaults as Odoo mainstream will be applied:
                   configuration file, psycopg2/lipq defaults.
        :param with_demo: controls the loading of demo data for all
                          module installations triggered by this call to
                          :meth:`open` and further uses of :meth:`load_modules`
                          on this :class:`Session` instance:

                          * if ``True``, demo data will uniformly be loaded
                          * if ``False``, no demo data will be loaded
                          * if ``None``, demo data will be loaded according to
                            the value of ``without_demo`` in configuration

                          In all cases, the behaviour will stay consistent
                          until the next call of ``open()``, but the
                          implementation does not protect against any race
                          conditions in Odoo internals.
        """
        if db is None:
            db = config['db_name']
        if not db:
            db = ''  # expected value expected by Odoo to start defaulting.

        cnx = openerp.sql_db.db_connect(db)
        cr = cnx.cursor()
        self.is_initialization = not(openerp.modules.db.is_initialized(cr))
        cr.close()

        startup.check_root_user()
        startup.check_postgres_user()
        openerp.netsvc.init_logger()

        saved_without_demo = config['without_demo']
        if with_demo is None:
            with_demo = config['without_demo']

        config['without_demo'] = not with_demo
        self.with_demo = with_demo

        self._registry = openerp.modules.registry.RegistryManager.get(
            db, update_module=False)
        config['without_demo'] = saved_without_demo
        self.init_cursor()
        self.uid = SUPERUSER_ID
        self.init_environments()
        self.context = self.registry('res.users').context_get(self.cr, self.uid)
        if hasattr(openerp, 'api'):
            self.env = openerp.api.Environment(self.cr, self.uid, self.context)

    def init_environments(self):
        """Enter the environments context manager, but don't leave it

        Automatically called by :meth:`open` and registry altering methods.
        See :class:``openerp.api.Environment`` for explanations about
        environments.

        For OpenERP/Odoo versions prior to the new style API merge, this
        is a no-op.

        This thread-local ``environments`` is initialized and cleaned with
        each request in the normal usage of the framework.
        That's why is is provided as a context manager.

        Therefore, user code probably needs in some case to clean it to avoid
        side effects. This can be done by calling :meth:`clean_environments`.
        """
        try:
            gen_factory = openerp.api.Environment.manage
        except AttributeError:
            return

        self._environments_gen_context = gen_factory().gen
        self._environments_gen_context.next()

    def clean_environments(self, reinit=True):<commit_msg>Very minor flake8 error<commit_after>"""Utilities to start a server process."""
import warnings
import sys
import os
import logging
from distutils.version import Version


try:
    import openerp
except ImportError:
    warnings.warn("This must be imported with a buildout openerp recipe "
                  "driven sys.path", RuntimeWarning)
else:
    try:
        from openerp.cli import server as startup
    except ImportError:
        from .backports.cli import server as startup
    from openerp.tools import config
    from openerp import SUPERUSER_ID
    from openerp.tools.parse_version import parse_version

from optparse import OptionParser  # we support python >= 2.6

logger = logging.getLogger(__name__)

DEFAULT_VERSION_PARAMETER = 'buildout.db_version'

DEFAULT_VERSION_FILE = 'VERSION.txt'


class OpenERPVersion(Version):
    """Odoo idea of version, wrapped in a class.

    This is based on :meth:`openerp.tools.parse_version`, and
    Provides straight-ahead comparison with tuples of integers, or
    distutils Version classes.
    """

    def parse(self, incoming):
        if isinstance(incoming, OpenERPVersion):
            self.vstring = incoming.vstring
            self.components = incoming.components
        else:
            self.vstring = incoming
            self.components = parse_version(incoming)

    def __str__(self):
        return self.vstring

    def __repr__(self):
        return 'OpenERPVersion(%r)' % str(self)

    def __cmp__(self, other):
        if isinstance(other, tuple):
            other = '.'.join(str(s) for s in other)
        elif not isinstance(other, self.__class__):
            other = str(other)  # Works with distutils' Version classes

        other = self.__class__(other)
        return cmp(self.components, other.components)


class Session(object):
    """A class to give server-level access to one database.

    There should be exactly one instance of this class per process.
    It can be used for any kind of script involving Odoo API, and provides
    facilities for upgrade scripts (see also
    :mod:anybox.recipe.odoo.runtime.upgrade)

    Before actual use, call :meth:`open`.
    Then you'll have useful attributes and methods reminiscent of the unit test
    classes:

    * :attr:`cr`: a cursor
    * :attr:`uid`: user id
    * :attr:`registry`: access to model objects
    * :attr:`is_initialization`: True if and only if the database was not
      initialized before the call to :meth:`open`

    Example application code::

       session.open(db_name="my_db")
       admin = session.registry('res_users').browse(session.cr, session.uid, 1)
       (...)
       session.cr.commit()
       session.close()

    Transaction management is up to user code

    Upgrade scripts writers should check the version handling properties:

    * :meth:`db_version`
    * :meth:`package_version`

    Instantiation is done by passing the path to Odoo main
    configuration file and the path of the buildout directory.

    Usually, instantiation code is written by the recipe in the body of the
    executable "Odoo scripts" it produces.
    Script writers provide a callable that takes a
    :class:`.Session` object argument and declare it as a console script entry
    point in their distribution.
    End users can reference such entry points in their buildout configurations
    to have buildout produce the actual executable. See :doc:`/scripts`
    for details.

    Upgrade scripts are a special case of that process, in which the entry
    point is actually provided by the recipe and rewraps a user-level
    source script.

    Later versions of the recipe may find a way to pass the whole buildout
    configuration (recall that this is to be used in a separate process in
    which the buildout configuration has not been parsed).
    """

    def __init__(self, conffile, buildout_dir, parse_config=True):
        self.buildout_dir = buildout_dir
        self.openerp_config_file = conffile

        self._registry = self.cr = None
        if parse_config:
            config.parse_config(['-c', conffile])

    def ready(self):
        return self._registry is not None

    def open(self, db=None, with_demo=False):
        """Load the database

        Loading an empty database in Odoo has the side effect of installing
        the ``base`` module. Whether to loading demo data or not has therefore
        to be decided right away.

        :param db: database name. If not specified, the same cascading of
                   defaults as Odoo mainstream will be applied:
                   configuration file, psycopg2/lipq defaults.
        :param with_demo: controls the loading of demo data for all
                          module installations triggered by this call to
                          :meth:`open` and further uses of :meth:`load_modules`
                          on this :class:`Session` instance:

                          * if ``True``, demo data will uniformly be loaded
                          * if ``False``, no demo data will be loaded
                          * if ``None``, demo data will be loaded according to
                            the value of ``without_demo`` in configuration

                          In all cases, the behaviour will stay consistent
                          until the next call of ``open()``, but the
                          implementation does not protect against any race
                          conditions in Odoo internals.
        """
        if db is None:
            db = config['db_name']
        if not db:
            db = ''  # expected value expected by Odoo to start defaulting.

        cnx = openerp.sql_db.db_connect(db)
        cr = cnx.cursor()
        self.is_initialization = not(openerp.modules.db.is_initialized(cr))
        cr.close()

        startup.check_root_user()
        startup.check_postgres_user()
        openerp.netsvc.init_logger()

        saved_without_demo = config['without_demo']
        if with_demo is None:
            with_demo = config['without_demo']

        config['without_demo'] = not with_demo
        self.with_demo = with_demo

        self._registry = openerp.modules.registry.RegistryManager.get(
            db, update_module=False)
        config['without_demo'] = saved_without_demo
        self.init_cursor()
        self.uid = SUPERUSER_ID
        self.init_environments()
        self.context = self.registry('res.users').context_get(
            self.cr, self.uid)
        if hasattr(openerp, 'api'):
            self.env = openerp.api.Environment(self.cr, self.uid, self.context)

    def init_environments(self):
        """Enter the environments context manager, but don't leave it

        Automatically called by :meth:`open` and registry altering methods.
        See :class:``openerp.api.Environment`` for explanations about
        environments.

        For OpenERP/Odoo versions prior to the new style API merge, this
        is a no-op.

        This thread-local ``environments`` is initialized and cleaned with
        each request in the normal usage of the framework.
        That's why is is provided as a context manager.

        Therefore, user code probably needs in some case to clean it to avoid
        side effects. This can be done by calling :meth:`clean_environments`.
        """
        try:
            gen_factory = openerp.api.Environment.manage
        except AttributeError:
            return

        self._environments_gen_context = gen_factory().gen
        self._environments_gen_context.next()

    def clean_environments(self, reinit=True):
{'fraction_non_alphanumeric': 0.07189413391269998, 'fraction_numerical': 0.0005925340707090658, 'mean_word_length': 2.428120063191153, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, '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': '3295465', 'n_tokens_mistral': 4026, 'n_tokens_neox': 3865, 'n_words': 1485}