[enh] add a msignal.file_display capability for cli

This commit is contained in:
Laurent Peuch 2021-01-02 01:30:33 +01:00
parent 201b033606
commit 1622cb1fdc
2 changed files with 39 additions and 1 deletions

View file

@ -307,7 +307,7 @@ class MoulinetteSignals(object):
# Signals definitions
"""The list of available signals"""
signals = {"authenticate", "prompt", "display"}
signals = {"authenticate", "prompt", "display", "file_display"}
def authenticate(self, authenticator):
"""Process the authentication
@ -368,6 +368,19 @@ class MoulinetteSignals(object):
except NotImplementedError:
pass
def file_display(self, file_path):
"""Display a message
Display the content of a file at file_path.
Keyword arguments:
- file_path -- The path to the file
"""
try:
self._file_display(file_path)
except NotImplementedError:
pass
@staticmethod
def _notimplemented(*args, **kwargs):
raise NotImplementedError("this signal is not handled")

View file

@ -5,6 +5,7 @@ import sys
import getpass
import locale
import logging
import subprocess
from argparse import SUPPRESS
from collections import OrderedDict
from datetime import date, datetime
@ -443,6 +444,7 @@ class Interface(BaseInterface):
if os.isatty(1):
msignals.set_handler("authenticate", self._do_authenticate)
msignals.set_handler("prompt", self._do_prompt)
msignals.set_handler("file_display", self._do_file_display)
self.actionsmap = ActionsMap(
ActionsMapParser(top_parser=top_parser),
@ -550,3 +552,26 @@ class Interface(BaseInterface):
print("{} {}".format(colorize(m18n.g("error"), "red"), message))
else:
print(message)
def _do_file_display(self, file_path):
"""Display the content of a file
Handle the core.MoulinetteSignals.file_display signal.
"""
# in python 3 we'll be able to uses shutil.get_terminal_size
rows, _ = subprocess.check_output("stty size", shell=True).strip().split(" ")
file_length = (
subprocess.check_output("wc -l %s" % file_path, shell=True)
.strip()
.split(" ")[0]
)
rows = int(rows)
file_length = int(file_length)
# 80% of file_length, we assume that above is too uncounfortable
if (file_length * 0.8) > rows:
os.system("less %s" % file_path)
else:
print(open(file_path).read())