"""A file manager for text 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 _
TEXT_CSS = ('/ciowarehouse2/css/manager_text.css', )
# =============================================================================
[docs]
def includeme(configurator: Configurator):
"""Function to include a text manager.
:type configurator: pyramid.config.Configurator
:param configurator:
Object used to do configuration declaration within the application.
"""
Manager.register(configurator, ManagerText)
# =============================================================================
[docs]
class ManagerText(Manager):
"""Class to manage a text file."""
ciotype = CioType('text')
label = _('Generic text file handling')
viewings = ( # yapf: disable
{'name': 'text',
'label': _('Text'),
'template': LAYOUT_VIEW_PT,
'css': TEXT_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)
})