https://t.me/RX1948
Server : Apache
System : Linux iad1-shared-b8-43 6.6.49-grsec-jammy+ #10 SMP Thu Sep 12 23:23:08 UTC 2024 x86_64
User : dh_edsupp ( 6597262)
PHP Version : 8.2.26
Disable Function : NONE
Directory :  /lib/python3/dist-packages/trac/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //lib/python3/dist-packages/trac/__pycache__/env.cpython-310.pyc
o

�k�`Ѱ�@sdZddlmZddlZddlZddlZddlZddlZddl	Z	ddl
mZddlm
Z
mZddlmZddlmZddlmZdd	lmZmZmZdd
lmZmZddlmZmZddlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&dd
l'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-ddl.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?ddl@mAZAddlBmCZCddlDmEZEddlFmGZGmHZHmIZImJZJmKZKmLZLddlMmNZNmOZOddlPmQZQddlRmSZSgd�ZTdZUGdd�de+eV�ZWGdd�de(e)�ZXiZYeC�Z�Z[d$d d!�Z\Gd"d#�d#e(�Z]dS)%z(Trac Environment model and related APIs.�)�contextmanagerN)�RawConfigParser)�PIPE�Popen)�mkdtemp)�urlsplit)�log)�AdminCommandError�IAdminCommandProvider�get_dir_list)�IEnvironmentSetupParticipant�ISystemInfoProvider)�CacheManager�cached)�
BoolOption�ChoiceOption�
ConfigSection�
Configuration�	IntOption�Option�
PathOption)�	Component�ComponentManager�ExtensionPoint�
TracBaseError�	TracError�
implements)�DatabaseManager�QueryContextManager�TransactionContextManager�parse_connection_uri)�copy_tables)�load_components)�as_bool�backup_config_file�copytree�create_file�get_pkginfo�
is_path_below�lazy�makedirs)�	close_fds)�	threading)�pytz)�exception_to_unicode�path_to_unicode�printerr�	printferr�	printfout�printout)�_�N_)�Chrome)�Href)�Environmentr�open_environmentzTrac Environment Version 1c@seZdZdZdS)�BackupErrorz<Exception raised during an upgrade when the DB backup fails.N)�__name__�
__module__�__qualname__�__doc__�r?r?�*/usr/lib/python3/dist-packages/trac/env.pyr:>sr:cseZdZdZee�dZee�Zee	�Z
edd�Ze
dddd�Zed	d
dd�Zed	dd
d�Zed	dd
d�Zed	ddd�Zedddd�Zedddd�Zedddd�Zedddd�Zeddd d!�Zedd"ed#�d$�Zedd%d&d'�Zed(d)ej ej!d*d
d+�Z"ed(d,d-d.�Z#ed(d/ej$ej%d0d
d+�Z&ed(d1d2d3�Z'd
gdfd4d5�Z(d6d7�Z)e*d8d9��Z+e,d:d;��Z-e,d<d=��Z.d>d?�Z/d@dA�Z0dBdC�Z1e*dDdE��Z2dFdG�Z3�fdHdI�Z4e5d�dJdK��Z6dLdM�Z7e*dNdO��Z8e,dPdQ��Z9e,dRdS��Z:d�dTdU�Z;gdfdVdW�Z<e*dXdY��Z=e*dZd[��Z>e*d\d]��Z?d^d_�Z@e*d`da��ZAe*dbdc��ZBddde�ZCe*dfdg��ZDe*dhdi��ZEe*djdk��ZFe*dldm��ZGe*dndo��ZHe*dpdq��ZIe*drds��ZJdtdu�ZKdvdw�ZLd�dxdy�ZMeNdzd{��ZOeNd|d}��ZPd~d�ZQd�d�d��ZRd�d��ZSd�d�d��ZTe*d�d���ZUe*d�d���ZVd�d��ZW�ZXS)�r8a�Trac environment manager.

    Trac stores project information in a Trac environment. It consists
    of a directory structure containing among other things:

    * a configuration file,
    * project-specific templates and plugins,
    * the wiki and ticket attachments files,
    * the SQLite database file (stores tickets, wiki pages...)
      in case the database backend is SQLite

    T�
componentsa
Enable or disable components provided by Trac and plugins.
        The component to enable/disable is specified by the option name.
        The enabled state is determined by the option value: setting
        the value to `enabled` or `on` will enable the component, any
        other value (typically `disabled` or `off`) will disable the
        component.

        The option name is either the fully qualified name of the
        component or the module/package prefix of the component. The
        former enables/disables a specific component, while the latter
        enables/disables any component in the specified package/module.

        Consider the following configuration snippet:
        {{{#!ini
        [components]
        trac.ticket.report.ReportModule = disabled
        acct_mgr.* = enabled
        }}}

        The first option tells Trac to disable the
        [TracReports report module].
        The second option instructs Trac to enable all components in
        the `acct_mgr` package. The trailing wildcard is required for
        module/package matching.

        To view the list of active components, go to the ''Plugins''
        section of ''About Trac'' (requires `CONFIG_VIEW`
        [TracPermissions permission]).

        See also: TracPlugins
        �inherit�plugins_dir�a+Path to the //shared plugins directory//.

        Plugins in that directory are loaded in addition to those in
        the directory of the environment `plugins`, with this one
        taking precedence.

        Non-absolute paths are relative to the Environment `conf`
        directory.
        �trac�base_urlz�Base URL of the Trac site.

        This is used to produce documents outside of the web browsing
        context, such as URLs in notification e-mails that point to
        Trac resources.
        �use_base_url_for_redirectFa�Optionally use `[trac] base_url` for redirects.

        In some configurations, usually involving running Trac behind
        a HTTP proxy, Trac can't automatically reconstruct the URL
        that is used to access it. You may need to use this option to
        force Trac to use the `base_url` setting also for
        redirects. This introduces the obvious limitation that this
        environment will only be usable when accessible from that URL,
        as redirects are frequently used.
        �secure_cookiesz�Restrict cookies to HTTPS connections.

        When true, set the `secure` flag on all cookies so that they
        are only sent to the server on HTTPS connections. Use this if
        your Trac instance is only accessible through HTTPS.
        �anonymous_session_lifetime�90z�Lifetime of the anonymous session, in days.

        Set the option to 0 to disable purging old anonymous sessions.
        (''since 1.0.17'')�project�namez
My ProjectzName of the project.�descrzMy example projectz!Short description of the project.�urlawURL of the project web site.

        This is usually the domain in which the `base_url` resides.
        For example, the project URL might be !https://myproject.com,
        with the Trac site (`base_url`) residing at either
        !https://trac.myproject.com or !https://myproject.com/trac.
        The project URL is added to the footer of notification e-mails.
        �adminz.E-Mail address of the project's administrator.�admin_trac_url�.z�Base URL of a Trac instance where errors in this Trac
        should be reported.

        This can be an absolute or relative URL, or '.' to reference
        this Trac instance. An empty value will disable the reporting
        buttons.
        �footerznVisit the Trac open source project at<br /><a href="https://trac.edgewall.org/">https://trac.edgewall.org/</a>z!Page footer text (right-aligned).�iconzcommon/trac.icozURL of the icon of the project.�logging�log_typezbLogging facility to use.

        Should be one of (`none`, `file`, `stderr`, `syslog`, `winlog`).)�case_sensitive�log_fileztrac.logz�If `log_type` is `file`, this should be a path to the
        log-file.  Relative paths are resolved relative to the `log`
        directory of the environment.�	log_levelzpLevel of verbosity in log.

        Should be one of (`CRITICAL`, `ERROR`, `WARNING`, `INFO`, `DEBUG`).
        �
log_formatNa�Custom logging format.

        If nothing is set, the following will be used:

        `Trac[$(module)s] $(levelname)s: $(message)s`

        In addition to regular key names supported by the
        [http://docs.python.org/library/logging.html Python logger library]
        one could use:

        - `$(path)s`     the path for the current environment
        - `$(basename)s` the last path component of the current environment
        - `$(project)s`  the project name

        Note the usage of `$(...)s` instead of `%(...)s` as the latter form
        would be interpreted by the !ConfigParser itself.

        Example:
        `($(thread)d) Trac[$(basename)s:$(module)s] $(levelname)s: $(message)s`
        cCsht�|�tj�tj�|��|_d|_d|_|r*|�||�|j	D]}|�
�q!dS|��|��dS)aInitialize the Trac environment.

        :param path:   the absolute path to the Trac environment
        :param create: if `True`, the environment is created and otherwise,
                       the environment is expected to already exist.
        :param options: A list of `(section, name, value)` tuples that
                        define configuration options
        :param default_data: if `True` (the default), the environment is
                             populated with default data when created.
        N)
r�__init__�os�path�normpath�normcaser�config�create�setup_participants�environment_created�verify�setup_config)�selfr\r`�options�default_data�setup_participantr?r?r@rZ�s


�zEnvironment.__init__cCsd|jj|jfS)Nz<%s %r>)�	__class__r;r\�rer?r?r@�__repr__szEnvironment.__repr__cCstj�|j�S)z3The environment name.

        :since: 1.2
        )r[r\�basenamerjr?r?r@rL�zEnvironment.namecCs|S)z�Property returning the `Environment` object, which is often
        required for functions and methods that take a `Component` instance.
        r?rjr?r?r@�envszEnvironment.envcCs6g}|jD]}|�|��pg�qtt|�dd�d�S)z�List of `(name, version)` tuples describing the name and
        version information of external packages used by Trac and plugins.
        cSs|ddk|d��fS)Nr�Trac)�lower)�argsr?r?r@�<lambda>*sz)Environment.system_info.<locals>.<lambda>)�key)�system_info_providers�extend�get_system_info�sorted�set)re�info�providerr?r?r@�system_info!s
�zEnvironment.system_infoccsZ�d|jfVdtjfVdtjfVtdurdtjfVt|d�r+|j|jfVdSdS)Nro�Python�
setuptoolsr-�webfrontend_version)	�trac_version�sys�versionr}�__version__r-�hasattr�webfrontendr~rjr?r?r@rv.s�
�zEnvironment.get_system_infocCs||_|j|_|j|_dS)aInitialize additional member variables for components.

        Every component activated through the `Environment` object
        gets three member variables: `env` (the environment object),
        `config` (the environment configuration) and `log` (a logger
        object).N)rnr_r)re�	componentr?r?r@�component_activated7szEnvironment.component_activatedcCs&|}t|t�s|jd|j}|��S)NrQ)�
isinstance�strr<r;rp)re�
name_or_classrLr?r?r@�_component_nameBs
zEnvironment._component_namecCs6i}|j��D]\}}|�d���}t|�||<q|S)Nz.*)�components_sectionrf�rstriprpr#)re�_rulesrL�valuer?r?r@�_component_rulesHs
zEnvironment._component_rulescCsx|�|�}|j}|}|r)|�|�}|dur|S|�d�}|dkr!n|d|�}|s|�d�r:|�d�r:|�d�p;dS)a�Implemented to only allow activation of components that are
        not disabled in the configuration.

        This is called by the `ComponentManager` base class when a
        component is about to be activated. If this method returns
        `False`, the component does not get activated. If it returns
        `None`, the component only gets activated if it is located in
        the `plugins` directory of the environment.
        NrQr�trac.z
trac.test.ztrac.tests.)r�r��get�rfind�
startswith)re�cls�component_name�rules�cname�enabled�idxr?r?r@�is_component_enabledPs&



�

�
��z Environment.is_component_enabledcs d|j|�|�<t��|�dS)zEnable a component or module.TN)r�r��super�enable_component�rer��rir?r@r�mszEnvironment.enable_componentccs��zdVWdSty'}z|j�d|t|��|r�WYd}~dSd}~wtyH}z|j�d|t|dd��|r=�WYd}~dSd}~ww)amTraps any runtime exception raised when working with a component
        and logs the error.

        :param component: the component responsible for any error that
                          could happen inside the context
        :param reraise: if `True`, an error is logged but not suppressed.
                        By default, errors are suppressed.

        NzComponent %s failed with %sT��	traceback)rr�warningr.�	Exception�error)rer��reraise�er?r?r@�component_guardrs(����

����zEnvironment.component_guardc
Cs�z$ttj�|jd�dd��}|����}Wd�n1swYWnty<}zttd|jt	|�d���d}~ww|t
krIttd|d���dS)	zSVerify that the provided path points to a valid Trac environment
        directory.�VERSION�utf-8��encodingNz+No Trac environment found at %(path)s
%(e)s)r\r�z(Unknown Trac environment type '%(type)s')�type)�openr[r\�join�readliner�r�rr4r.�_VERSION)re�f�tagr�r?r?r@rc�s&���
�����zEnvironment.verifycCst|���S)a�Return an object (typically a module) containing all the
        backend-specific exception types as attributes, named
        according to the Python Database API
        (http://www.python.org/dev/peps/pep-0249/).

        To catch a database exception, use the following pattern::

            try:
                with env.db_transaction as db:
                    ...
            except env.db_exc.IntegrityError as e:
                ...
        )r�get_exceptionsrjr?r?r@�db_exc�szEnvironment.db_exccC�t|�S)aReturn a context manager
        (`~trac.db.api.QueryContextManager`) which can be used to
        obtain a read-only database connection.

        Example::

            with env.db_query as db:
                cursor = db.cursor()
                cursor.execute("SELECT ...")
                for row in cursor.fetchall():
                    ...

        Note that a connection retrieved this way can be "called"
        directly in order to execute a query::

            with env.db_query as db:
                for row in db("SELECT ..."):
                    ...

        :warning: after a `with env.db_query as db` block, though the
          `db` variable is still defined, you shouldn't use it as it
          might have been closed when exiting the context, if this
          context was the outermost context (`db_query` or
          `db_transaction`).

        If you don't need to manipulate the connection itself, this
        can even be simplified to::

            for row in env.db_query("SELECT ..."):
                ...

        )rrjr?r?r@�db_query�s"zEnvironment.db_querycCr�)adReturn a context manager
        (`~trac.db.api.TransactionContextManager`) which can be used
        to obtain a writable database connection.

        Example::

            with env.db_transaction as db:
                cursor = db.cursor()
                cursor.execute("UPDATE ...")

        Upon successful exit of the context, the context manager will
        commit the transaction. In case of nested contexts, only the
        outermost context performs a commit. However, should an
        exception happen, any context manager will perform a rollback.
        You should *not* call `commit()` yourself within such block,
        as this will force a commit even if that transaction is part
        of a larger transaction.

        Like for its read-only counterpart, you can directly execute a
        DML query on the `db`::

            with env.db_transaction as db:
                db("UPDATE ...")

        :warning: after a `with env.db_transaction` as db` block,
          though the `db` variable is still available, you shouldn't
          use it as it might have been closed when exiting the
          context, if this context was the outermost context
          (`db_query` or `db_transaction`).

        If you don't need to manipulate the connection itself, this
        can also be simplified to::

            env.db_transaction("UPDATE ...")

        )rrjr?r?r@�db_transaction�s&zEnvironment.db_transactioncCsDddlm}||��|�t|��|�|dur t�|j�dSdS)zClose the environment.r)�RepositoryManagerN)�trac.versioncontrol.apir��shutdownrr)re�tidr�r?r?r@r��s�zEnvironment.shutdownc	Csptj�|j�}tj�|�sttd|d���tj�|j�r(t�|j�r(ttd���tj�|j�s5t�|j�t�|j�t�|j	�t�|j
�t�|j�ttj�
|jd�td�ttj�
|jd�d�t�|j�t|j�}|D]\}}}|�|||�qr|��|��tdd	�|D��s�|j�|�|j��t|jd
�|��t|�}|��|r�|��dSdS)a�Create the basic directory structure of the environment,
        initialize the database and populate the configuration file
        with default values.

        If options contains ('inherit', 'file'), default values will
        not be loaded; they are expected to be provided by that file
        or other options.

        :raises TracError: if the base directory of `path` does not exist.
        :raises TracError: if `path` exists and is not empty.
        zDBase directory '%(env)s' does not exist. Please create it and retry.)rnz"Directory exists and is not empty.r��
�READMEzcThis directory contains a Trac environment.
Visit https://trac.edgewall.org/ for more information.
css"�|]\}}}||fdkVqdS))rB�fileNr?)�.0�section�optionr�r?r?r@�	<genexpr>(s��z%Environment.create.<locals>.<genexpr>�.sampleN)r[r\�dirname�existsrr4�listdir�mkdir�
htdocs_dir�log_dirrC�
templates_dirr&r�r��conf_dirr�config_file_pathrx�saverd�anyr_�set_defaults�_update_sample_configr�init_db�insert_default_data)	rerfrg�base_dirr_r�rLr��dbmr?r?r@r`�sH��
�
�zEnvironment.createcC�t|��d�S)zLReturns the current version of the database.

        :since 1.0.2:
        �database_version�r�get_database_versionrjr?r?r@r�7s�zEnvironment.database_versioncCr�)z�Returns the version of the database at the time of creation.

        In practice, for a database created before 0.11, this will
        return `False` which is "older" than any db version number.

        :since 1.0.2:
        �initial_database_versionr�rjr?r?r@�database_initial_version@s	�z$Environment.database_initial_versioncCs ddlm}m}t|��d|�S)z9Returns the version of Trac.
        :since: 1.2
        r)�corer�r�)rEr�r�r'r�)rer�r�r?r?r@rLszEnvironment.trac_versioncCsPt|jd|ji�|_|jjsttd|jd���|��|j}t	||o$|f�dS)zLoad the configuration file.�envnamez/The configuration file is not found at %(path)s�r\N)
rr�rLr_r�rr4�	setup_log�shared_plugins_dirr")rerCr?r?r@rdTs��zEnvironment.setup_configcCstj�|jd�S)zPath of the trac.ini file.ztrac.ini)r[r\r�r�rjr?r?r@r�_szEnvironment.config_file_pathcCs&tj�|j�stj�|j|j�S|jS)zPath to the log file.)r[r\�isabsrWr�r�rjr?r?r@�
log_file_pathdszEnvironment.log_file_pathcGs2|j}|D]	}tj�||�}qtj�tj�|��S�N)r\r[r�r^�realpath)re�dirsr\�dirr?r?r@�_get_path_to_dirkszEnvironment._get_path_to_dircCs|�dd�S)zKAbsolute path to the attachments directory.

        :since: 1.3.1
        �files�attachments�r�rjr?r?r@�attachments_dirqszEnvironment.attachments_dircC�
|�d�S)zEAbsolute path to the conf directory.

        :since: 1.0.11
        �confr�rjr?r?r@r�y�
zEnvironment.conf_dircCr�)zEAbsolute path to the files directory.

        :since: 1.3.2
        r�r�rjr?r?r@�	files_dir�r�zEnvironment.files_dircCr�)zGAbsolute path to the htdocs directory.

        :since: 1.0.11
        �htdocsr�rjr?r?r@r��r�zEnvironment.htdocs_dircCr�)zDAbsolute path to the log directory.

        :since: 1.0.11
        rr�rjr?r?r@r��r�zEnvironment.log_dircCr�)zHAbsolute path to the plugins directory.

        :since: 1.0.11
        �pluginsr�rjr?r?r@rC�r�zEnvironment.plugins_dircCr�)zJAbsolute path to the templates directory.

        :since: 1.0.11
        �	templatesr�rjr?r?r@r��r�zEnvironment.templates_dircCs>|�|j|j|j|j�\|_}|j�|�|j�d|j�dS)z"Initialize the logging sub-system.z_-------------------------------- environment startup [Trac %s] --------------------------------N)	�
create_loggerrUr�rXrYr�
addHandlerryr)re�log_handlerr?r?r@r��s���zEnvironment.setup_logcCs\dt�|j�d����}|r$|�dd��d|j��d|j��d|j�}tj	|||||d�S)	NzTrac.%sr�z$(z%(z%(path)sz%(basename)sz%(project)s)�format)
�hashlib�sha1r\�encode�	hexdigest�replacerL�project_namer�logger_handler_factory)rerUrWrXrY�log_idr?r?r@r��s�



�
�zEnvironment.create_loggercCs|r|jSt|j�S)aReturns information about all known users, i.e. users that
        have logged in to this Trac environment and possibly set their
        name and email.

        By default this function returns an iterator that yields one
        tuple for every user, of the form (username, name, email),
        ordered alpha-numerically by username. When `as_dict` is `True`
        the function returns a dictionary mapping username to a
        (name, email) tuple.

        :since 1.2: the `as_dict` parameter is available.
        )�_known_users_dict�iter�_known_users)re�as_dictr?r?r@�get_known_users�s
zEnvironment.get_known_userscCr�)Na�
                SELECT DISTINCT s.sid, n.value, e.value
                FROM session AS s
                 LEFT JOIN session_attribute AS n ON (n.sid=s.sid
                  AND n.authenticated=1 AND n.name = 'name')
                 LEFT JOIN session_attribute AS e ON (e.sid=s.sid
                  AND e.authenticated=1 AND e.name = 'email')
                WHERE s.authenticated=1 ORDER BY s.sid
        )r�rjr?r?r@r��s
zEnvironment._known_userscCsdd�|jD�S)NcSs"i|]
}|d|d|df�qS)r��r?)r��ur?r?r@�
<dictcomp>�s"z1Environment._known_users_dict.<locals>.<dictcomp>)r�rjr?r?r@r��szEnvironment._known_users_dictcCs|`|`dS)zClear the known_users cache.N)r�r�rjr?r?r@�invalidate_known_users_cache�sz(Environment.invalidate_known_users_cachecCst|��|�S)z�Create a backup of the database.

        :param dest: Destination file; if not specified, the backup is
                     stored in a file called db_name.trac_version.bak
        )r�backup)re�destr?r?r@r�rmzEnvironment.backupcCs�|jD]M}z/|j|dd��|��r$|j�d|�	Wd�WdSWd�n1s.wYWqtyP}zttd|jj	|jj
t|�d���d}~wwdS)z4Return whether the environment needs to be upgraded.T�r�z,Component %s requires an environment upgradeNz;Unable to check for upgrade of %(module)s.%(name)s: %(err)s)�modulerL�errF)rar��environment_needs_upgraderr�r�rr4rir<r;r.)re�participantr�r?r?r@�
needs_upgrade�s,
�������zEnvironment.needs_upgradec
Csg}|jD]"}|j|dd��|��r|�|�Wd�n1s"wYq|s,dS|rGz|�|�WntyF}zt|�|�d}~ww|D]1}|j�d|�|j|dd��|�	�Wd�n1shwYt
|�}|jdkrz|��qI|�
�|`dS)z�Upgrade database.

        :param backup: whether or not to backup before upgrading
        :param backup_dest: name of the backup file
        :return: whether the upgrade was performed
        Tr	Nzupgrading %s...zsqlite::memory:)rar�r�appendrr�r:rry�upgrade_environmentr�connection_urir�r�r�)rer�backup_dest�	upgradersr
r�r�r?r?r@�upgrade�s:

���
��
�
�zEnvironment.upgradecCstt|jj�j�S)zThe application root path)r7r�abs_href�baser\rjr?r?r@�hrefszEnvironment.hrefcCs|js	|j�d�t|j�S)zThe application URLzQ[trac] base_url option not set in configuration, generated links may be incorrect)rFrr�r7rjr?r?r@r"s
zEnvironment.abs_hrefcCs�tj�|jd�}tj�|�sdSt|�}|��z|��Wnty>}z|j	�
d|t|dd��WYd}~dSd}~ww|j	�d|�dS)Nr�z/Couldn't write sample configuration file (%s)%sTr�zRWrote sample configuration file with the new settings and their default values: %s)
r[r\r�r��isfilerr�r��EnvironmentErrorrr�r.ry)re�filenamer_r�r?r?r@r�*s ����z!Environment._update_sample_config)Fr�)FN)Yr;r<r=r>rr
�requiredrrtrrarr�rr�rrFr�base_url_for_redirectrHrrIr��project_description�project_url�
project_admin�project_admin_trac_urlr5�project_footer�project_iconrr�	LOG_TYPES�LOG_TYPE_ALIASESrUrW�
LOG_LEVELS�LOG_LEVEL_ALIASESrXrYrZrkr)rL�propertyrnr{rvr�r�r�r�r�rr�rcr�r�r�r�r`r�r�rrdr�r�r�r�r�r�r�r�rCr�r�r�rrr�r�rrrrrrr��
__classcell__r?r?r�r@r8Bs
�!���
�����
��	��
��
��


	


#

'9











	




"

r8Fc
Cs@|st�d�}|sttd���|r\t�?t�|�}|r/|j��r/|j	�
d�|��t|=d}|dur<t�|t
|��}nt|���Wd�|SWd�|S1sUwY|St|�}z|��}Wn-ty|}z
|j	�dt|���d}~wty�}z|j	�dt|dd���d}~ww|r�ttd|d	���|S)
a�Open an existing environment object, and verify that the database is up
    to date.

    :param env_path: absolute path to the environment directory; if
                     omitted, the value of the `TRAC_ENV` environment
                     variable is used
    :param use_cache: whether the environment should be cached for
                      subsequent invocations of this function
    :return: the `Environment` object
    �TRAC_ENVzjMissing environment variable "TRAC_ENV". Trac requires this variable to point to a valid Trac environment.z1Reloading environment due to configuration changeNz/Exception caught while checking for upgrade: %sTr�zPThe Trac Environment needs to be upgraded. Run:

  trac-admin "%(path)s" upgrader�)r[�getenvrr4�env_cache_lock�	env_cacher�r_�parse_if_neededrryr��
setdefaultr9r�reset_metadatar8rr�r.r�)�env_path�	use_cachernrr�r?r?r@r9?sZ

�
�!�
�!�!���
����r9c@sveZdZdZee�dd�Zddd�Zdd�Zd	d
�Z	ddd�Z
dd
d�Zdd�Zdd�Z
dd�Zdd�Zdd�ZdS)�EnvironmentAdminz;trac-admin command provider for environment administration.ccsP�ddd|j|jfVdddd|jfVddd	d|jfVd
ddd|jfVdS)
N�
convert_dbz<dburi> [new_env]aConvert database

               Converts the database backend in the environment in which
               the command is run (in-place), or in a new copy of the
               environment. For an in-place conversion, the data is
               copied to the database specified in <dburi> and the
               [trac] database setting is changed to point to the new
               database. The new database must be empty, which for an
               SQLite database means the file should not exist. The data
               in the existing database is left unmodified.

               For a database conversion in a new copy of the environment,
               the environment in which the command is executed is copied
               and the [trac] database setting is changed in the new
               environment. The existing environment is left unmodified.

               Be sure to create a backup (see `hotcopy`) before converting
               the database, particularly when doing an in-place conversion.
               �deployz<directory>z2Extract static resources from Trac and all plugins�hotcopyz<backupdir> [--no-database]z�Make a hot backup copy of an environment

               The database is backed up to the 'db' directory of the
               destination, unless the --no-database option is
               specified.
               rz
[--no-backup]a=Upgrade database to current version

               The database is backed up to the directory specified by [trac]
               backup_dir (the default is 'db'), unless the --no-backup
               option is specified. The shorthand alias -b can also be used
               to specify --no-backup.
               )�_complete_convert_db�_do_convert_db�
_do_deploy�_do_hotcopy�_do_upgraderjr?r?r@�get_admin_commands}s"����
�z#EnvironmentAdmin.get_admin_commandsNcCs|r|�||�S|�|�Sr�)�_do_convert_db_in_new_env�_do_convert_db_in_place)re�dburir0r?r?r@r7�s
zEnvironmentAdmin._do_convert_dbcCst|�dkrt|d�SdS)Nrr)�lenr)rerqr?r?r@r6�s�z%EnvironmentAdmin._complete_convert_dbc	Cs�tj�|�}tj�|d�}tj�|d�}t|j�}|jD]7}t|��p$g�}|s)q|D]'\}}	|	s2q+tj�|	�}
tj�||�}tj�	|
�rRt
||
�rRttd|
d���q+qt
|dd�t
|dd�ttd��|jD]A}t|��pqg�}|svqitd|j|jjf�|D]&\}}	|	s�q�tj�|	�}
td	|
�tj�	|
�r�tj�||�}t|
|dd�q�qit
|dd�ttd
��|jtjtd�}dD]8}tj�|d
|�}|jd|dd�}
|j|
|dd�}t|ddd��
}|�|�Wd�n1s�wYq�dS)Nr�zcgi-binz�Resources cannot be deployed to a target directory that is equal to or below the source directory '%(source)s'.

Please choose a different target directory and try again.)�sourceT)�	overwritezCopying resources from:z  %s.%sz   zCreating scripts.)rn�
executable�repr)�cgi�fcgi�wsgir�zdeploy_trac.)�text�wr�r�)r[r\r]r�r6rn�template_providers�list�get_htdocs_dirsr�r(r	r4r*r3r<rir;r%r�rBrC�
load_template�render_template_stringr��write)rer�target�
chrome_target�
script_target�chromerz�pathsrs�rootr@�data�script�templaterG�outr?r?r@r8�sj

����
�
��
���zEnvironmentAdmin._do_deploycCs�|dvrttd|d�dd��tj�|�rttdt|�d���ttdt|jj�t|�d	��|jj	�
d
d�}|�dd
�\}}g}|dkretj�|jjtj�
|��}|d|d|d|dg}|re|�|�|jj�y}|d|�d�d�zt|jj|d
|d�Wn;tjy�}z.d
}	ttd��|jdD]\}
}}|
|vr�td|�q�td|t|
�f�q�WYd}~nd}~wwd}	|dkr�|s�ttd��tj�|dd|�}
|j�|
�Wd�n1s�wYttd��|	S)N)Nz
--no-databasezInvalid argument '%(arg)s')�argT��
show_usagez+hotcopy can't overwrite existing '%(dest)s')rz!Hotcopying %(src)s to %(dst)s ...)�src�dstrE�database�:r�sqlitez-journalz	-stmtjrnlz-shmz-walzUPDATE �systemz! SET name=NULL WHERE name IS NULL)�symlinks�skipz<The following errors happened while copying the environment:rz  %sz
  %s: '%s'zBacking up database ...�dbz%s-db-backup.sqlz
Hotcopy done.)r	r4r[r\r�rr/r3rnr_r��splitr�r]rr��quoter%�shutil�Errorr0rqr)rer�no_db�db_str�prefix�db_pathrcrdr��retvalr\r]r�
sql_backupr?r?r@r9�sb��
��

����

���zEnvironmentAdmin._do_hotcopyc
Cs�|dvrttd�dd��|j��sttd��dSz|jj|dud�Wn$ty;}zttd��|jd�d}~wt	yHttd	���wttd
t
|jj�d��dS)N)Nz-bz--no-backupzInvalid argumentsTrZz-Database is up to date, no upgrade necessary.)rzTThe pre-upgrade backup failed.
Use '--no-backup' to upgrade without doing a backup.
rz8The upgrade failed. Please fix the issue and try again.
zsUpgrade done.

You may want to upgrade the Trac documentation now by running:

  trac-admin "%(path)s" wiki upgrader�)r	r4rnrr3rr:r0rqr�r/r\)re�	no_backupr�r?r?r@r:s$

��
�zEnvironmentAdmin._do_upgradecCs�zt�|�Wn	tyYnwtj�|�stj�|�r$td|�dS|�||�}t|j	�}|j
}|��}t|���}|�|||||�|�
|�dS)Nz/Cannot create Trac environment: %s: File existsr)r[�rmdir�OSErrorr\r��lexistsr1�_create_envrrnr�get_connection�_copy_tables�_copy_directories)re�	dst_dburir0�dst_envr��	src_dburi�src_db�dst_dbr?r?r@r<7s"��
z*EnvironmentAdmin._do_convert_db_in_new_envc	Cs8t|j�}|j}||krtd|�dStdtj�|jj�d�}z[|�||�}|�	�}t|��	�}|�
|||||�~~|��d}t|�\}}	|dkrttj�
|jj|	d�}
tj�|
�}tj�|�sgt�|�t�tj�
||	d�|
�Wt�|�nt�|�wt|jdtt����|j�dd	|�|j��dS)
Nz9Source database and destination database are the same: %srzconvert_db-)rkr�r`r\z.convert_db-%drEr^)rrnrr1rr[r\r�rsrtrur�r r��isdirr*rg�copy�rmtreer$�int�timer_rxr�)rerwr�ryr0rxrzr{�schema�params�dbpath�dbdirr?r?r@r=Is>
��
�z(EnvironmentAdmin._do_convert_db_in_placec	st����|jjd�t�fdd����D��}||d<tdd�|��D��}Gdd�dt�}||d|d	�}|�	�t
�|j�t
�|jj|j�ttjd
d|dfttttd
��}|jdd�\}}Wd�n1skwY|jdkr}td||f��t|�S)Nr�c3s0�|]}��|�D]\}}||f|fVq	qdSr�)�items�r�r�rLr���parserr?r@r�ms���z/EnvironmentAdmin._create_env.<locals>.<genexpr>)rEr^css"�|]\\}}}|||fVqdSr�r?r�r?r?r@r�qs� c@seZdZdZdZdd�ZdS)z8EnvironmentAdmin._create_env.<locals>.MigrateEnvironmentTFcs0|�|��t�fdd�dD��sdSt�||�S)Nc3s�|]}��|�VqdSr�)r�)r��mod�rLr?r@r�zs�z`EnvironmentAdmin._create_env.<locals>.MigrateEnvironment.is_component_enabled.<locals>.<genexpr>)r�ztracopt.F)r�r�r8r�r�r?r�r@r�xs
�zMEnvironmentAdmin._create_env.<locals>.MigrateEnvironment.is_component_enabledN)r;r<r=�abstractrr�r?r?r?r@�MigrateEnvironmenttsr�T)r`rfz-mztrac.admin.consoler)�stdin�stdout�stderrr+rD)�inputrz-upgrade command failed (stdout %r, stderr %r))r�readrnr��dict�sectionsrwr�r8r�r[rprCrgr%rr�rBrr+�communicate�
returncoder)	rer0r>rfr�rn�procr�r�r?r�r@rsjs8�����
�zEnvironmentAdmin._create_envcCst|j|||||�dSr�)r!rn)rerxrzr{ryrwr?r?r@ru�szEnvironmentAdmin._copy_tablescCs�td�|jj|jj|jj|jjfD]2}tj�|�}tj�	|j|�}td|dd�tj�
|�r4t�|�tj�
|�r@t�
||�td�qdS)NzCopying directories:z  %s directory... F)�newlinezdone.)r2rnr�r�r�rCr[r\rlr�r|rgr~r%)rerxr\rLr]r?r?r@rv�s�

�z"EnvironmentAdmin._copy_directoriesr�)r;r<r=r>rr
r;r7r6r8r9r:r<r=rsrurvr?r?r?r@r2vs
+
7
4!%r2)NF)^r>�
contextlibrr��os.pathr[r}rgr�r��configparserr�
subprocessrr�tempfiler�urllib.parserrEr�trac.admin.apir	r
r�trac.apirr
�
trac.cacherr�trac.configrrrrrrr�	trac.corerrrrrr�trac.db.apirrrr �trac.db.convertr!�trac.loaderr"�	trac.utilr#r$r%r&r'r(r)r*�trac.util.compatr+�trac.util.concurrencyr,�trac.util.datefmtr-�trac.util.textr.r/r0r1r2r3�trac.util.translationr4r5�trac.web.chromer6�
trac.web.hrefr7�__all__r��RuntimeErrorr:r8r,�Lockr+r9r2r?r?r?r@�<module>sT$ ( ~
7

https://t.me/RX1948 - 2025