Skip to content

Commit a9ce49b

Browse files
committed
Added center_text() utility function for centering text in a terminal along with unit tests for it
This function isn't used yet, but I have plans to use it when improving the output of transcript testing
1 parent c08f48e commit a9ce49b

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

cmd2/utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import glob
66
import os
77
import re
8+
import shutil
89
import subprocess
910
import sys
1011
import threading
@@ -377,6 +378,21 @@ def get_exes_in_path(starts_with: str) -> List[str]:
377378
return list(exes_set)
378379

379380

381+
def center_text(msg: str, *, pad: str = ' ') -> str:
382+
"""Centers text horizontally for display within the current terminal, optionally padding both sides.
383+
384+
:param msg: message to display in the center
385+
:param pad: (optional) if provided, the first character will be used to pad both sides of the message
386+
:return: centered message, optionally padded on both sides with pad_char
387+
"""
388+
term_width = shutil.get_terminal_size().columns
389+
surrounded_msg = ' {} '.format(msg)
390+
if not pad:
391+
pad = ' '
392+
fill_char = pad[:1]
393+
return surrounded_msg.center(term_width, fill_char)
394+
395+
380396
class StdSim(object):
381397
"""
382398
Class to simulate behavior of sys.stdout or sys.stderr.

tests/test_utils.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -276,3 +276,26 @@ def test_context_flag_bool(context_flag):
276276
def test_context_flag_exit_err(context_flag):
277277
with pytest.raises(ValueError):
278278
context_flag.__exit__()
279+
280+
281+
def test_center_text_pad_none():
282+
msg = 'foo'
283+
centered = cu.center_text(msg, pad=None)
284+
expected_center = ' ' + msg + ' '
285+
assert expected_center in centered
286+
letters_in_centered = set(centered)
287+
letters_in_msg = set(msg)
288+
assert len(letters_in_centered) == len(letters_in_msg) + 1
289+
290+
def test_center_text_pad_equals():
291+
msg = 'foo'
292+
pad = '='
293+
centered = cu.center_text(msg, pad=pad)
294+
expected_center = ' ' + msg + ' '
295+
assert expected_center in centered
296+
assert centered.startswith(pad)
297+
assert centered.endswith(pad)
298+
letters_in_centered = set(centered)
299+
letters_in_msg = set(msg)
300+
assert len(letters_in_centered) == len(letters_in_msg) + 2
301+

0 commit comments

Comments
 (0)