summaryrefslogtreecommitdiff
path: root/cmd2
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2019-06-26 02:33:18 -0400
committerKevin Van Brunt <kmvanbrunt@gmail.com>2019-06-26 02:33:18 -0400
commite34bba44ef53228aeba613ac6e928b2c315111cf (patch)
treea39a736c3a36426fe6c278105ce9f6ec5696d16c /cmd2
parente6f65e607c6ad2350dfce05f3d5080d0ffbe35f1 (diff)
downloadcmd2-git-e34bba44ef53228aeba613ac6e928b2c315111cf.tar.gz
Moved code related to ANSI escape codes to new file called ansi.py
Diffstat (limited to 'cmd2')
-rw-r--r--cmd2/ansi.py118
-rw-r--r--cmd2/argparse_completer.py2
-rw-r--r--cmd2/cmd2.py51
-rw-r--r--cmd2/constants.py70
-rw-r--r--cmd2/transcript.py10
-rw-r--r--cmd2/utils.py62
6 files changed, 154 insertions, 159 deletions
diff --git a/cmd2/ansi.py b/cmd2/ansi.py
new file mode 100644
index 00000000..889f1cb3
--- /dev/null
+++ b/cmd2/ansi.py
@@ -0,0 +1,118 @@
+# coding=utf-8
+"""Support for ANSI escape codes which are used for things like applying style to text"""
+import re
+from typing import Any
+
+import colorama
+from colorama import Fore, Back, Style
+from wcwidth import wcswidth
+
+# Regular expression to match ANSI escape codes
+ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
+
+# Foreground color presets
+FG_COLORS = {
+ 'black': Fore.BLACK,
+ 'red': Fore.RED,
+ 'green': Fore.GREEN,
+ 'yellow': Fore.YELLOW,
+ 'blue': Fore.BLUE,
+ 'magenta': Fore.MAGENTA,
+ 'cyan': Fore.CYAN,
+ 'white': Fore.WHITE,
+ 'gray': Fore.LIGHTBLACK_EX,
+ 'lightred': Fore.LIGHTRED_EX,
+ 'lightblue': Fore.LIGHTBLUE_EX,
+ 'lightgreen': Fore.LIGHTGREEN_EX,
+ 'lightyellow': Fore.LIGHTYELLOW_EX,
+ 'lightmagenta': Fore.LIGHTMAGENTA_EX,
+ 'lightcyan': Fore.LIGHTCYAN_EX,
+ 'lightwhite': Fore.LIGHTWHITE_EX,
+ 'reset': Fore.RESET,
+}
+
+# Background color presets
+BG_COLORS = {
+ 'black': Back.BLACK,
+ 'red': Back.RED,
+ 'green': Back.GREEN,
+ 'yellow': Back.YELLOW,
+ 'blue': Back.BLUE,
+ 'magenta': Back.MAGENTA,
+ 'cyan': Back.CYAN,
+ 'white': Back.WHITE,
+ 'gray': Back.LIGHTBLACK_EX,
+ 'lightred': Back.LIGHTRED_EX,
+ 'lightblue': Back.LIGHTBLUE_EX,
+ 'lightgreen': Back.LIGHTGREEN_EX,
+ 'lightyellow': Back.LIGHTYELLOW_EX,
+ 'lightmagenta': Back.LIGHTMAGENTA_EX,
+ 'lightcyan': Back.LIGHTCYAN_EX,
+ 'lightwhite': Back.LIGHTWHITE_EX,
+ 'reset': Back.RESET,
+}
+
+
+def strip_ansi(text: str) -> str:
+ """Strip ANSI escape codes from a string.
+
+ :param text: string which may contain ANSI escape codes
+ :return: the same string with any ANSI escape codes removed
+ """
+ return ANSI_ESCAPE_RE.sub('', text)
+
+
+def ansi_safe_wcswidth(text: str) -> int:
+ """
+ Wraps wcswidth to make it compatible with colored strings
+
+ :param text: the string being measured
+ """
+ # Strip ANSI escape codes since they cause wcswidth to return -1
+ return wcswidth(strip_ansi(text))
+
+
+def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, underline: bool = False) -> str:
+ """
+ Applies styles to text
+
+ :param text: Any object compatible with str.format()
+ :param fg: foreground color. Accepts color names like 'red' or 'blue'
+ :param bg: background color. Accepts color names like 'red' or 'blue'
+ :param bold: apply the bold style if True. Defaults to False.
+ :param underline: apply the underline style if True. Defaults to False.
+ """
+ values = []
+ text = "{}".format(text)
+
+ # Add styles
+ if fg:
+ try:
+ values.append(FG_COLORS[fg.lower()])
+ except KeyError:
+ raise ValueError('Color {} does not exist.'.format(fg))
+ if bg:
+ try:
+ values.append(BG_COLORS[bg.lower()])
+ except KeyError:
+ raise ValueError('Color {} does not exist.'.format(bg))
+ if bold:
+ values.append(Style.BRIGHT)
+ if underline:
+ underline_enable = colorama.ansi.code_to_chars(4)
+ values.append(underline_enable)
+
+ values.append(text)
+
+ # Remove styles
+ if fg:
+ values.append(FG_COLORS['reset'])
+ if bg:
+ values.append(BG_COLORS['reset'])
+ if bold:
+ values.append(Style.NORMAL)
+ if underline:
+ underline_disable = colorama.ansi.code_to_chars(24)
+ values.append(underline_disable)
+
+ return "".join(values)
diff --git a/cmd2/argparse_completer.py b/cmd2/argparse_completer.py
index 6b3f5298..c3f73552 100644
--- a/cmd2/argparse_completer.py
+++ b/cmd2/argparse_completer.py
@@ -68,8 +68,8 @@ from typing import List, Dict, Tuple, Callable, Union
from colorama import Fore
+from .ansi import ansi_safe_wcswidth
from .rl_utils import rl_force_redisplay
-from .utils import ansi_safe_wcswidth
# attribute that can optionally added to an argparse argument (called an Action) to
# define the completion choices for the argument. You may provide a Collection or a Function.
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 75cee55d..20e26e15 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -45,6 +45,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, Un
import colorama
from colorama import Fore
+from . import ansi
from . import constants
from . import plugin
from . import utils
@@ -374,7 +375,7 @@ class Cmd(cmd.Cmd):
self.quit_on_sigint = False # Quit the loop on interrupt instead of just resetting prompt
# Attributes which ARE dynamically settable at runtime
- self.colors = constants.COLORS_TERMINAL
+ self.colors = constants.ANSI_TERMINAL
self.continuation_prompt = '> '
self.debug = False
self.echo = False
@@ -559,7 +560,7 @@ class Cmd(cmd.Cmd):
:return: prompt stripped of any ANSI escape codes
"""
- return utils.strip_ansi(self.prompt)
+ return ansi.strip_ansi(self.prompt)
@property
def aliases(self) -> Dict[str, str]:
@@ -579,12 +580,11 @@ class Cmd(cmd.Cmd):
def _decolorized_write(self, fileobj: IO, msg: str) -> None:
"""Write a string to a fileobject, stripping ANSI escape sequences if necessary
- Honor the current colors setting, which requires us to check whether the
- fileobject is a tty.
+ Honor the current colors setting, which requires us to check whether the fileobject is a tty.
"""
- if self.colors.lower() == constants.COLORS_NEVER.lower() or \
- (self.colors.lower() == constants.COLORS_TERMINAL.lower() and not fileobj.isatty()):
- msg = utils.strip_ansi(msg)
+ if self.colors.lower() == constants.ANSI_NEVER.lower() or \
+ (self.colors.lower() == constants.ANSI_TERMINAL.lower() and not fileobj.isatty()):
+ msg = ansi.strip_ansi(msg)
fileobj.write(msg)
def poutput(self, msg: Any, *, end: str = '\n') -> None:
@@ -617,7 +617,7 @@ class Cmd(cmd.Cmd):
the message text already has the desired style. Defaults to True.
"""
if add_color:
- final_msg = utils.style(msg, fg='lightred')
+ final_msg = ansi.style(msg, fg='lightred')
else:
final_msg = "{}".format(msg)
self._decolorized_write(sys.stderr, final_msg + end)
@@ -640,11 +640,11 @@ class Cmd(cmd.Cmd):
final_msg = "{}".format(msg)
if add_color:
- final_msg = utils.style(final_msg, fg='lightred')
+ final_msg = ansi.style(final_msg, fg='lightred')
if not self.debug:
warning = "\nTo enable full traceback, run the following command: 'set debug true'"
- final_msg += utils.style(warning, fg="lightyellow")
+ final_msg += ansi.style(warning, fg="lightyellow")
# Set add_color to False since style has already been applied
self.perror(final_msg, end=end, add_color=False)
@@ -692,8 +692,8 @@ class Cmd(cmd.Cmd):
# Don't attempt to use a pager that can block if redirecting or running a script (either text or Python)
# Also only attempt to use a pager if actually running in a real fully functional terminal
if functional_terminal and not self._redirecting and not self._in_py and not self._script_dir:
- if self.colors.lower() == constants.COLORS_NEVER.lower():
- msg_str = utils.strip_ansi(msg_str)
+ if self.colors.lower() == constants.ANSI_NEVER.lower():
+ msg_str = ansi.strip_ansi(msg_str)
pager = self.pager
if chop:
@@ -1278,7 +1278,7 @@ class Cmd(cmd.Cmd):
longest_match_length = 0
for cur_match in matches_to_display:
- cur_length = utils.ansi_safe_wcswidth(cur_match)
+ cur_length = ansi.ansi_safe_wcswidth(cur_match)
if cur_length > longest_match_length:
longest_match_length = cur_length
else:
@@ -2750,7 +2750,7 @@ class Cmd(cmd.Cmd):
widest = 0
# measure the commands
for command in cmds:
- width = utils.ansi_safe_wcswidth(command)
+ width = ansi.ansi_safe_wcswidth(command)
if width > widest:
widest = width
# add a 4-space pad
@@ -3247,7 +3247,7 @@ class Cmd(cmd.Cmd):
if args.__statement__.command == "pyscript":
warning = ("pyscript has been renamed and will be removed in the next release, "
"please use run_pyscript instead\n")
- self.perror(utils.style(warning, fg="lightyellow"))
+ self.perror(ansi.style(warning, fg="lightyellow"))
return py_return
@@ -3556,7 +3556,7 @@ class Cmd(cmd.Cmd):
# Check if all commands ran
if commands_run < len(history):
warning = "Command {} triggered a stop and ended transcript generation early".format(commands_run)
- self.perror(utils.style(warning, fg="lightyellow"))
+ self.perror(ansi.style(warning, fg="lightyellow"))
# finally, we can write the transcript out to the file
try:
@@ -3676,7 +3676,7 @@ class Cmd(cmd.Cmd):
if args.__statement__.command == "load":
warning = ("load has been renamed and will be removed in the next release, "
"please use run_script instead\n")
- self.perror(utils.style(warning, fg="lightyellow"))
+ self.perror(ansi.style(warning, fg="lightyellow"))
# load has been deprecated
do_load = do_run_script
@@ -3703,7 +3703,7 @@ class Cmd(cmd.Cmd):
if args.__statement__.command == "_relative_load":
warning = ("_relative_load has been renamed and will be removed in the next release, "
"please use _relative_run_script instead\n")
- self.perror(utils.style(warning, fg="lightyellow"))
+ self.perror(ansi.style(warning, fg="lightyellow"))
file_path = args.file_path
# NOTE: Relative path is an absolute path, it is just relative to the current script directory
@@ -3724,7 +3724,6 @@ class Cmd(cmd.Cmd):
import time
import unittest
import cmd2
- from colorama import Style
from .transcript import Cmd2TestCase
class TestMyAppCase(Cmd2TestCase):
@@ -3740,12 +3739,12 @@ class Cmd(cmd.Cmd):
verinfo = ".".join(map(str, sys.version_info[:3]))
num_transcripts = len(transcripts_expanded)
plural = '' if len(transcripts_expanded) == 1 else 's'
- self.poutput(Style.BRIGHT + utils.center_text('cmd2 transcript test', pad='=') + Style.NORMAL)
+ self.poutput(ansi.style(utils.center_text('cmd2 transcript test', pad='='), bold=True))
self.poutput('platform {} -- Python {}, cmd2-{}, readline-{}'.format(sys.platform, verinfo, cmd2.__version__,
rl_type))
self.poutput('cwd: {}'.format(os.getcwd()))
self.poutput('cmd2 app: {}'.format(sys.argv[0]))
- self.poutput(Style.BRIGHT + 'collected {} transcript{}'.format(num_transcripts, plural) + Style.NORMAL)
+ self.poutput(ansi.style('collected {} transcript{}'.format(num_transcripts, plural), bold=True))
self.__class__.testfiles = transcripts_expanded
sys.argv = [sys.argv[0]] # the --test argument upsets unittest.main()
@@ -3758,8 +3757,8 @@ class Cmd(cmd.Cmd):
if test_results.wasSuccessful():
self._decolorized_write(sys.stderr, stream.read())
finish_msg = '{0} transcript{1} passed in {2:.3f} seconds'.format(num_transcripts, plural, execution_time)
- finish_msg = utils.style(utils.center_text(finish_msg, pad='='), fg="green")
- self.poutput(Style.BRIGHT + finish_msg + Style.NORMAL)
+ finish_msg = ansi.style(utils.center_text(finish_msg, pad='='), fg="green", bold=True)
+ self.poutput(finish_msg)
else:
# Strip off the initial traceback which isn't particularly useful for end users
error_str = stream.read()
@@ -3827,14 +3826,14 @@ class Cmd(cmd.Cmd):
# That will be included in the input lines calculations since that is where the cursor is.
num_prompt_terminal_lines = 0
for line in prompt_lines[:-1]:
- line_width = utils.ansi_safe_wcswidth(line)
+ line_width = ansi.ansi_safe_wcswidth(line)
num_prompt_terminal_lines += int(line_width / terminal_size.columns) + 1
# Now calculate how many terminal lines are take up by the input
last_prompt_line = prompt_lines[-1]
- last_prompt_line_width = utils.ansi_safe_wcswidth(last_prompt_line)
+ last_prompt_line_width = ansi.ansi_safe_wcswidth(last_prompt_line)
- input_width = last_prompt_line_width + utils.ansi_safe_wcswidth(readline.get_line_buffer())
+ input_width = last_prompt_line_width + ansi.ansi_safe_wcswidth(readline.get_line_buffer())
num_input_terminal_lines = int(input_width / terminal_size.columns) + 1
diff --git a/cmd2/constants.py b/cmd2/constants.py
index f0cdf816..ac8822c0 100644
--- a/cmd2/constants.py
+++ b/cmd2/constants.py
@@ -2,11 +2,6 @@
# coding=utf-8
"""Constants and definitions"""
-import re
-
-import colorama
-from colorama import Fore, Back
-
# Used for command parsing, output redirection, tab completion and word
# breaks. Do not change.
QUOTES = ['"', "'"]
@@ -18,66 +13,11 @@ REDIRECTION_TOKENS = [REDIRECTION_PIPE, REDIRECTION_OUTPUT, REDIRECTION_APPEND]
COMMENT_CHAR = '#'
MULTILINE_TERMINATOR = ';'
-# Regular expression to match ANSI escape codes
-ANSI_ESCAPE_RE = re.compile(r'\x1b[^m]*m')
-
LINE_FEED = '\n'
-# Values for colors setting
-COLORS_NEVER = 'Never'
-COLORS_TERMINAL = 'Terminal'
-COLORS_ALWAYS = 'Always'
-
-
-# Foreground color presets.
-FG_COLORS = {
- 'black': Fore.BLACK,
- 'red': Fore.RED,
- 'green': Fore.GREEN,
- 'yellow': Fore.YELLOW,
- 'blue': Fore.BLUE,
- 'magenta': Fore.MAGENTA,
- 'cyan': Fore.CYAN,
- 'white': Fore.WHITE,
- 'gray': Fore.LIGHTBLACK_EX,
- 'lightred': Fore.LIGHTRED_EX,
- 'lightblue': Fore.LIGHTBLUE_EX,
- 'lightgreen': Fore.LIGHTGREEN_EX,
- 'lightyellow': Fore.LIGHTYELLOW_EX,
- 'lightmagenta': Fore.LIGHTMAGENTA_EX,
- 'lightcyan': Fore.LIGHTCYAN_EX,
- 'lightwhite': Fore.LIGHTWHITE_EX,
- 'reset': Fore.RESET,
-}
-
-# Background color presets.
-BG_COLORS = {
- 'black': Back.BLACK,
- 'red': Back.RED,
- 'green': Back.GREEN,
- 'yellow': Back.YELLOW,
- 'blue': Back.BLUE,
- 'magenta': Back.MAGENTA,
- 'cyan': Back.CYAN,
- 'white': Back.WHITE,
- 'gray': Back.LIGHTBLACK_EX,
- 'lightred': Back.LIGHTRED_EX,
- 'lightblue': Back.LIGHTBLUE_EX,
- 'lightgreen': Back.LIGHTGREEN_EX,
- 'lightyellow': Back.LIGHTYELLOW_EX,
- 'lightmagenta': Back.LIGHTMAGENTA_EX,
- 'lightcyan': Back.LIGHTCYAN_EX,
- 'lightwhite': Back.LIGHTWHITE_EX,
- 'reset': Back.RESET,
-}
-
-
-# Underline style built upon Colorama class
-class UnderlineStyle(colorama.ansi.AnsiCodes):
- ENABLE = 4
- DISABLE = 24
-
-
-Underline = UnderlineStyle()
-
DEFAULT_SHORTCUTS = {'?': 'help', '!': 'shell', '@': 'run_script', '@@': '_relative_run_script'}
+
+# Values for cmd2 setting that determines when to allow ANSI escape codes
+ANSI_NEVER = 'Never'
+ANSI_TERMINAL = 'Terminal'
+ANSI_ALWAYS = 'Always'
diff --git a/cmd2/transcript.py b/cmd2/transcript.py
index 316592ce..25a79310 100644
--- a/cmd2/transcript.py
+++ b/cmd2/transcript.py
@@ -13,7 +13,7 @@ import re
import unittest
from typing import Tuple
-from . import utils
+from . import ansi, utils
class Cmd2TestCase(unittest.TestCase):
@@ -56,13 +56,13 @@ class Cmd2TestCase(unittest.TestCase):
def _test_transcript(self, fname: str, transcript):
line_num = 0
finished = False
- line = utils.strip_ansi(next(transcript))
+ line = ansi.strip_ansi(next(transcript))
line_num += 1
while not finished:
# Scroll forward to where actual commands begin
while not line.startswith(self.cmdapp.visible_prompt):
try:
- line = utils.strip_ansi(next(transcript))
+ line = ansi.strip_ansi(next(transcript))
except StopIteration:
finished = True
break
@@ -89,7 +89,7 @@ class Cmd2TestCase(unittest.TestCase):
result = self.cmdapp.stdout.read()
stop_msg = 'Command indicated application should quit, but more commands in transcript'
# Read the expected result from transcript
- if utils.strip_ansi(line).startswith(self.cmdapp.visible_prompt):
+ if ansi.strip_ansi(line).startswith(self.cmdapp.visible_prompt):
message = '\nFile {}, line {}\nCommand was:\n{}\nExpected: (nothing)\nGot:\n{}\n'.format(
fname, line_num, command, result)
self.assertTrue(not (result.strip()), message)
@@ -97,7 +97,7 @@ class Cmd2TestCase(unittest.TestCase):
self.assertFalse(stop, stop_msg)
continue
expected = []
- while not utils.strip_ansi(line).startswith(self.cmdapp.visible_prompt):
+ while not ansi.strip_ansi(line).startswith(self.cmdapp.visible_prompt):
expected.append(line)
try:
line = next(transcript)
diff --git a/cmd2/utils.py b/cmd2/utils.py
index a5b7f43f..812fa227 100644
--- a/cmd2/utils.py
+++ b/cmd2/utils.py
@@ -12,71 +12,9 @@ import threading
import unicodedata
from typing import Any, Iterable, List, Optional, TextIO, Union
-from colorama import Style
-from wcwidth import wcswidth
-
from . import constants
-def strip_ansi(text: str) -> str:
- """Strip ANSI escape codes from a string.
-
- :param text: string which may contain ANSI escape codes
- :return: the same string with any ANSI escape codes removed
- """
- return constants.ANSI_ESCAPE_RE.sub('', text)
-
-
-def ansi_safe_wcswidth(text: str) -> int:
- """
- Wraps wcswidth to make it compatible with colored strings
-
- :param text: the string being measured
- """
- # Strip ANSI escape codes since they cause wcswidth to return -1
- return wcswidth(strip_ansi(text))
-
-
-def style(text: Any, *, fg: str = '', bg: str = '', bold: bool = False, underline: bool = False) -> str:
- """
- Applies style to text
-
- :param text: Any object compatible with str.format()
- :param fg: foreground color. Accepts color names like 'red' or 'blue'
- :param bg: background color. Accepts color names like 'red' or 'blue'
- :param bold: apply the bold style if True. Defaults to False.
- :param underline: apply the underline style if True. Defaults to False.
- """
- values = []
- text = "{}".format(text)
- if fg:
- try:
- values.append(constants.FG_COLORS[fg.lower()])
- except KeyError:
- raise ValueError('Color {} does not exist.'.format(fg))
- if bg:
- try:
- values.append(constants.BG_COLORS[bg.lower()])
- except KeyError:
- raise ValueError('Color {} does not exist.'.format(bg))
- if bold:
- values.append(Style.BRIGHT)
- if underline:
- values.append(constants.Underline.ENABLE)
-
- values.append(text)
- if fg:
- values.append(constants.FG_COLORS['reset'])
- if bg:
- values.append(constants.BG_COLORS['reset'])
- if bold:
- values.append(Style.NORMAL)
- if underline:
- values.append(constants.Underline.DISABLE)
-
- return "".join(values)
-
-
def is_quoted(arg: str) -> bool:
"""
Checks if a string is quoted