Source code for ciowarehouse2.handlers.config

"""A file handler 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.handler import LAYOUT_VIEW_PT, CHRYSALIO_JS, Handler
from ..lib.i18n import _

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


# =============================================================================
[docs] def includeme(configurator: Configurator): """Function to include a configuration handler. :type configurator: pyramid.config.Configurator :param configurator: Object used to do configuration declaration within the application. """ Handler.register(configurator, HandlerConfig)
# =============================================================================
[docs] class HandlerConfig(Handler): """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.handler.Handler.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['handlers'][self.uid]['viewing'], 'content': Literal(content) })