Source code for ciowarehouse2.managers.code

"""A file manager for files of code (language, regex...)."""

from __future__ import annotations
from os.path import splitext, exists

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

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

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 _

CODE_CSS = ('/ciowarehouse2/css/manager_code.css', )


# =============================================================================
[docs] def includeme(configurator: Configurator): """Function to include a code manager. :type configurator: pyramid.config.Configurator :param configurator: Object used to do configuration declaration within the application. """ Manager.register(configurator, ManagerCode)
# =============================================================================
[docs] class ManagerCode(Manager): """Class to manage a code file.""" ciotype = CioType('code') label = _('Generic code file handling') viewings = ( # yapf: disable {'name': 'code', 'label': _('Code'), 'template': LAYOUT_VIEW_PT, 'css': CODE_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 = IniLexer() \ if splitext(ciopath.path)[1] == '.regex' else 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) })