Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
left_fill_width = 0
right_fill_width = total_fill_width
elif alignment == TextAlignment.CENTER:
left_fill_width = total_fill_width // 2
right_fill_width = total_fill_width - left_fill_width
else:
left_fill_width = total_fill_width
right_fill_width = 0
# Determine how many fill characters are needed to cover the width
left_fill = (left_fill_width // fill_char_width) * fill_char
right_fill = (right_fill_width // fill_char_width) * fill_char
# In cases where the fill character display width didn't divide evenly into
# the gaps being filled, pad the remainder with spaces.
left_fill += ' ' * (left_fill_width - ansi.ansi_safe_wcswidth(left_fill))
right_fill += ' ' * (right_fill_width - ansi.ansi_safe_wcswidth(right_fill))
text_buf.write(left_fill + line + right_fill)
return text_buf.getvalue()
right_fill_width = total_fill_width
elif alignment == TextAlignment.CENTER:
left_fill_width = total_fill_width // 2
right_fill_width = total_fill_width - left_fill_width
else:
left_fill_width = total_fill_width
right_fill_width = 0
# Determine how many fill characters are needed to cover the width
left_fill = (left_fill_width // fill_char_width) * fill_char
right_fill = (right_fill_width // fill_char_width) * fill_char
# In cases where the fill character display width didn't divide evenly into
# the gaps being filled, pad the remainder with spaces.
left_fill += ' ' * (left_fill_width - ansi.ansi_safe_wcswidth(left_fill))
right_fill += ' ' * (right_fill_width - ansi.ansi_safe_wcswidth(right_fill))
text_buf.write(left_fill + line + right_fill)
return text_buf.getvalue()
lines = text.splitlines()
else:
lines = ['']
if width is None:
width = shutil.get_terminal_size().columns
text_buf = io.StringIO()
for index, line in enumerate(lines):
if index > 0:
text_buf.write('\n')
# Use ansi_safe_wcswidth to support characters with display widths
# greater than 1 as well as ANSI escape sequences
line_width = ansi.ansi_safe_wcswidth(line)
if line_width == -1:
raise(ValueError("Text to align contains an unprintable character"))
# Check if line is wider than the desired final width
if width <= line_width:
text_buf.write(line)
continue
# Calculate how wide each side of filling needs to be
total_fill_width = width - line_width
if alignment == TextAlignment.LEFT:
left_fill_width = 0
right_fill_width = total_fill_width
elif alignment == TextAlignment.CENTER:
left_fill_width = total_fill_width // 2
@cmd2.with_argparser_and_unknown_args(mumble_parser)
def do_mumble(self, opts, arg):
"""Mumbles what you tell me to."""
repetitions = opts.repeat or 1
#arg = arg.split()
for _ in range(min(repetitions, self.maxrepeats)):
output = []
if random.random() < .33:
output.append(random.choice(self.MUMBLE_FIRST))
for word in arg:
if random.random() < .40:
output.append(random.choice(self.MUMBLES))
output.append(word)
if random.random() < .25:
output.append(random.choice(self.MUMBLE_LAST))
self.poutput(' '.join(output))
@cmd2.with_argument_list
def do_exit(self, arg_list) -> bool:
"""Exit the application with an optional exit code.
Usage: exit [exit_code]
Where:
* exit_code - integer exit code to return to the shell
"""
# If an argument was provided
if arg_list:
try:
self.exit_code = int(arg_list[0])
except ValueError:
self.perror("{} isn't a valid integer exit code".format(arg_list[0]))
self.exit_code = -1
# Return True to stop the command loop
@pytest.fixture
def helpcat_app():
app = HelpCategoriesApp()
return app
def test_help_cat_base(helpcat_app):
out, err = run_cmd(helpcat_app, 'help')
verify_help_text(helpcat_app, out)
def test_help_cat_verbose(helpcat_app):
out, err = run_cmd(helpcat_app, 'help --verbose')
verify_help_text(helpcat_app, out)
class SelectApp(cmd2.Cmd):
def do_eat(self, arg):
"""Eat something, with a selection of sauces to choose from."""
# Pass in a single string of space-separated selections
sauce = self.select('sweet salty', 'Sauce? ')
result = '{food} with {sauce} sauce, yum!'
result = result.format(food=arg, sauce=sauce)
self.stdout.write(result + '\n')
def do_study(self, arg):
"""Learn something, with a selection of subjects to choose from."""
# Pass in a list of strings for selections
subject = self.select(['math', 'science'], 'Subject? ')
result = 'Good luck learning {}!\n'.format(subject)
self.stdout.write(result)
def do_procrastinate(self, arg):
from .conftest import run_cmd
# Prefer statically linked gnureadline if available (for macOS compatibility due to issues with libedit)
try:
import gnureadline as readline
except ImportError:
# Try to import readline, but allow failure for convenience in Windows unit testing
# Note: If this actually fails, you should install readline on Linux or Mac or pyreadline on Windows
try:
# noinspection PyUnresolvedReferences
import readline
except ImportError:
pass
class ArgparseApp(cmd2.Cmd):
def __init__(self):
self.maxrepeats = 3
cmd2.Cmd.__init__(self)
def namespace_provider(self) -> argparse.Namespace:
ns = argparse.Namespace()
ns.custom_stuff = "custom"
return ns
say_parser = argparse.ArgumentParser()
say_parser.add_argument('-p', '--piglatin', action='store_true', help='atinLay')
say_parser.add_argument('-s', '--shout', action='store_true', help='N00B EMULATION MODE')
say_parser.add_argument('-r', '--repeat', type=int, help='output [n] times')
say_parser.add_argument('words', nargs='+', help='words to say')
@cmd2.with_argparser(say_parser)
def CreateOutsimApp():
c = cmd2.Cmd()
c.stdout = utils.StdSim(c.stdout)
return c
def test_history_file_permission_error(mocker, capsys):
mock_open = mocker.patch('builtins.open')
mock_open.side_effect = PermissionError
cmd2.Cmd(persistent_history_file='/tmp/doesntmatter')
out, err = capsys.readouterr()
assert not out
assert 'Can not read' in err
def choices_takes_arg_tokens(arg_tokens: argparse.Namespace) -> List[str]:
"""Choices function that receives arg_tokens from AutoCompleter"""
return [arg_tokens['parent_arg'][0], arg_tokens['subcommand'][0]]
def completer_takes_arg_tokens(text: str, line: str, begidx: int, endidx: int,
arg_tokens: argparse.Namespace) -> List[str]:
"""Completer function that receives arg_tokens from AutoCompleter"""
match_against = [arg_tokens['parent_arg'][0], arg_tokens['subcommand'][0]]
return basic_complete(text, line, begidx, endidx, match_against)
# noinspection PyMethodMayBeStatic,PyUnusedLocal
class AutoCompleteTester(cmd2.Cmd):
"""Cmd2 app that exercises AutoCompleter class"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
############################################################################################################
# Begin code related to help and command name completion
############################################################################################################
# Top level parser for music command
music_parser = Cmd2ArgumentParser(description='Manage music')
# Add subcommands to music
music_subparsers = music_parser.add_subparsers()
music_create_parser = music_subparsers.add_parser('create', help='create music')
# Add subcommands to music -> create
music_create_subparsers = music_create_parser.add_subparsers()