Source code for ciowarehouse2.managers.config

"""A file manager for config files."""

from __future__ import annotations
from os.path import exists

from pygments import highlight
from pygments.lexers import guess_lexer_for_filename
from pygments.lexers.special import TextLexer
from pygments.formatters.html import HtmlFormatter
from pygments.util import ClassNotFound

from pyramid.config import Configurator
from pyramid.request import Request

from chrysalio.lib.utils import load_guessing_encoding
from chrysalio.helpers.literal import Literal
from ..lib.ciotype import CioType
from ..lib.ciopath import CioPath
from ..lib.warehouse import Warehouse
from ..lib.manager import LAYOUT_VIEW_PT, CHRYSALIO_JS, Manager
from ..lib.i18n import _

CONFIG_CSS = ('/ciowarehouse2/css/manager_config.css', )


# =============================================================================
[docs] def includeme(configurator: Configurator): """Function to include a configuration manager. :type configurator: pyramid.config.Configurator :param configurator: Object used to do configuration declaration within the application. """ Manager.register(configurator, ManagerConfig)
# =============================================================================
[docs] class ManagerConfig(Manager): """Class to manage a config config file.""" ciotype = CioType('config') label = _('Generic configuration handling') viewings = ( # yapf: disable {'name': 'config', 'label': _('Configuration'), 'template': LAYOUT_VIEW_PT, 'css': CONFIG_CSS, 'js': CHRYSALIO_JS},) # -------------------------------------------------------------------------
[docs] def view( self, request: Request, warehouse: Warehouse, ciopath: CioPath, ts_factory=None) -> str | None: """Return a string containing HTML to display the file. See: :meth:`.lib.manager.Manager.view` """ viewing = self.current_rendering(request, warehouse, 'viewing') abs_path = ciopath.absolute_path(warehouse.root) if viewing is None or not abs_path or not exists(abs_path): return None content = load_guessing_encoding(abs_path) if content is None: # pragma: nocover self._log_error(_('${p}: unknown encoding', {'p': ciopath})) content = request.localizer.translate( _('${p}: unknown encoding', {'p': ciopath})) try: lexer = guess_lexer_for_filename(abs_path, content) except ClassNotFound: lexer = TextLexer() content = highlight(content, lexer, HtmlFormatter()) return self._chameleon_render( request, warehouse, ciopath, viewing, ts_factory or _, { 'rendering_num': request.session['managers'][self.uid]['viewing'], 'content': Literal(content) })