Source code for Muscat.Helpers.TextFormatHelper

# -*- coding: utf-8 -*-
#
# This file is subject to the terms and conditions defined in
# file 'LICENSE.txt', which is part of this source code package.
#
import sys
import os
import re
from typing import Any

strip_ANSI_escape_sequences_sub = re.compile(r"""
    \x1b     # literal ESC
    \[       # literal [
    [;\d]*   # zero or more digits or semicolons
    [A-Za-z] # a letter
    """, re.VERBOSE).sub


[docs] class TFormat(): """ Format Helper class (indentation, color and justification)""" __indentation:int = 0 __size:int = 2
[docs] @staticmethod def II() -> None: """Increase indentation level by one level""" TFormat.__indentation += 1
[docs] @staticmethod def DI() -> None: """Decrease indentation level by """ TFormat.__indentation -= 1
[docs] @staticmethod def GetIndent(): """Generate a string with the correct number on spaces """ return ' '*(TFormat.__indentation*TFormat.__size)
[docs] @staticmethod def Reset() -> None: """Reset the indentation state""" TFormat.__indentation = 0 TFormat.__size = 2
[docs] @staticmethod def GoodBad(text:Any, test:bool) -> str: """Return a string in color depending on the test variable Parameters ---------- text : Any text to add color test : bool test value Returns ------- str a ANSI green string if test is True a ANSI red string if test is False """ if test: return TFormat.InGreen(str(text)) else: return TFormat.InRed(str(text))
[docs] @staticmethod def InRed(text:str='') -> str: """Return the string in color Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text in color """ return TFormat.WithColor(text, '31')
[docs] @staticmethod def InGreen(text: str='') -> str: """Return the string in color Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text in color """ return TFormat.WithColor(text, '32')
[docs] @staticmethod def InYellow(text: str='') -> str: """Return the string in color Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text in color """ return TFormat.WithColor(text, '33')
[docs] @staticmethod def InBlue(text: str ='') -> str: """Return the string in color Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text in color """ return TFormat.WithColor(text, '34')
[docs] @staticmethod def InPurple(text: str='') -> str: """Return the string in color Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text in color """ return TFormat.WithColor(text, '35')
[docs] @staticmethod def InGrey(text: str='') -> str: """Return the string in color Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text in color """ return TFormat.WithColor(text, '39')
[docs] @staticmethod def InRedBackGround(text: str='') -> str: """Return the string with a color background Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text with colored background """ return TFormat.WithColor(text, '41')
[docs] @staticmethod def InGreenBackGround(text: str='') -> str: """Return the string with a color background Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text with colored background """ return TFormat.WithColor(text, '42')
[docs] @staticmethod def InYellowBackGround(text: str='') -> str: """Return the string with a color background Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text with colored background """ return TFormat.WithColor(text, '43')
[docs] @staticmethod def InBlueBackGround(text=''): """Return the string with a color background Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text with colored background """ return TFormat.WithColor(text, '44')
[docs] @staticmethod def InPurpleBackGround(text=''): """Return the string with a color background Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text with colored background """ return TFormat.WithColor(text, '45')
[docs] @staticmethod def InGreyBackGround(text=''): """Return the string with a color background Parameters ---------- text : str, optional the string to add color, by default '' Returns ------- str the text with colored background """ return TFormat.WithColor(text, '40')
[docs] @staticmethod def WithColor(text:str, color:str) -> str: """Add color to a string usings ANSI code Parameters ---------- text : str the text to add color color : str ANSI color in str Returns ------- str the text in color """ if TFormat.SupportsColor(): if len(text): return '\x1b['+color+';1m' + text + TFormat.CleanFormat() else: return '\x1b['+color+';1m' else: return text # pragma: no cover
[docs] @staticmethod def WithUnderline(text:str ='') -> str: """return the text with ANSI underline Parameters ---------- text : str; the text to add underline Returns ------- str underlined text """ if TFormat.SupportsColor(): if len(text): return '\033[4m' + text + TFormat.CleanFormat() else: return '\033[4m' else: return text # pragma: no cover
[docs] @staticmethod def WithItalic(text: str='') -> str: """Return the text in italic font (ANSI code) Parameters ---------- text : str, optional the test to treat, by default '' Returns ------- str the text in italic """ if TFormat.SupportsColor(): if len(text): return '\033[3m' + text + TFormat.CleanFormat() else: return '\033[3m' else: return text # pragma: no cover
[docs] @staticmethod def CleanFormat() -> str: """Return the ANSI string for clean forma. Return an empty string if the current console does not support ANSI codes Returns ------- str Clean format string """ if TFormat.SupportsColor(): return '\x1b[0m' else: return '' # pragma: no cover
[docs] @staticmethod def Left(text :str, fill:str="*", width:int=60) -> str: """Return a text (text) left justified with width (width) and filling the empty spaces with the fill char. Parameters ---------- text : str the test to justified fill : str, optional the filling char, by default "*" width : int, optional the width of the justification, by default 60 Returns ------- str the input string left justified """ return text + fill*(width-len(text))
[docs] @staticmethod def Center(text: str, fill:str="*", width:int=60): """Return a text (text) centered with width (width) and filling the empty spaces with the fill char. Parameters ---------- text : str the test to justified fill : str, optional the filling char, by default "*" width : int, optional the width of the justification, by default 60 Returns ------- str the input string centered """ if fill != " ": if len(text): if (width - TFormat.__nonAnsiStringLen(text)) > 0: text = ' ' + text if (width - TFormat.__nonAnsiStringLen(text)) > 0: text = text + ' ' lt = TFormat.__nonAnsiStringLen(text) fwidth = width - lt rfw = max(fwidth//2, 0) lfw = max(width - lt - rfw, 0) return fill*(lfw) + text + fill*(rfw)
@staticmethod def __nonAnsiStringLen(text:str) -> int: """Return the length of text after removing all the ANSI codes Parameters ---------- text : str string to treat Returns ------- int Number of char in text after removing all the ANSI code """ return len(strip_ANSI_escape_sequences_sub("", text))
[docs] @staticmethod def InIPython() -> bool: """Function to try to detect if console is a IPython console Returns ------- bool true if variable __IPYTHON__ is defined (in locals()) """ return "__IPYTHON__" in locals()
[docs] @staticmethod def SupportsColor() -> bool: """Try to detect the color support of the current console .. note:: from https://github.com/django/django/blob/master/django/core/management/color.py Returns ------- bool Returns True if the running system's terminal supports color, and False otherwise. """ plat = sys.platform supported_platform = plat != 'Pocket PC' and (plat != 'win32' or 'ANSICON' in os.environ) # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() # hack for spyder in IPython if TFormat.InIPython(): # pragma no coverage return True # hack for spyder if 'SPYDER_SHELL_ID' in os.environ: # pragma no coverage return True if hasattr(sys.stdout, 'color'): # pragma: no cover return sys.stdout.color if os.environ.get("COLORTERM", "False") == "truecolor": return True if not supported_platform or not is_a_tty: # pragma: no cover return False return True # pragma: no cover
[docs] def CheckIntegrity(GUI:bool=False): TFormat.Reset() TFormat.II() TFormat.II() assert(TFormat._TFormat__indentation == 2) TFormat.DI() assert(TFormat.GetIndent() == " ") assert(TFormat._TFormat__indentation == 1) TFormat.Reset() assert(TFormat._TFormat__indentation == 0) print(TFormat.InGreenBackGround(TFormat.InRed("InRed with green background"))) r = TFormat.InRedBackGround(TFormat.InGreen("InGreen with red background")) + '\n' r += TFormat.InBlueBackGround(TFormat.InYellow("InYellow with blue background")) + '\n' r += TFormat.InYellowBackGround(TFormat.InBlue('InBlue with yellow background')) + '\n' r += TFormat.InGreyBackGround(TFormat.InPurple('InPurple with grey background')) + '\n' r += TFormat.InPurpleBackGround(TFormat.InGrey('InGrey with purple background')) + '\n' r += '\n' r += TFormat.InRed(TFormat.Center("toto"))+'-\n' r += TFormat.Center(TFormat.InRed("toto"))+'-\n' r += '-'+TFormat.InBlue(TFormat.Center("toto", width=8)) + '-\n' r += ' '+TFormat.WithUnderline('^ 8 ^') + '\n\n' r += '-'+TFormat.InBlue(TFormat.Center("toto", width=7)) + '-\n' r += ' '+TFormat.WithUnderline('^ 7 ^') + '\n\n' r += '-'+TFormat.InBlue(TFormat.Center("toto", width=6)) + '-\n' r += ' '+TFormat.WithUnderline('^ 6 ^') + '\n\n' r += '-'+TFormat.InBlue(TFormat.Center("toto", width=5)) + '-\n' r += ' '+TFormat.WithUnderline('^ 5 ^') + '\n\n' r += '-'+TFormat.InBlue(TFormat.Center("toto", width=4)) + '-\n' r += ' '+TFormat.WithUnderline('^ 4^') + '\n\n' r += '-'+TFormat.InBlue(TFormat.Center("toto", width=3)) + '-\n' r += ' '+TFormat.WithUnderline('^3^') + '\n\n' r += '-'+TFormat.InBlue(TFormat.Left("toto", width=5)) + '-\n' r += ' '+TFormat.WithUnderline('^5^') + '\n\n' TFormat.II() r += TFormat.GetIndent() + 'One Level Of Indentations \n' TFormat.II() r += TFormat.GetIndent() + 'Two Level Of Indentations \n' TFormat.DI() r += TFormat.GetIndent() + 'One Level Of Indentations \n' TFormat.DI() r += TFormat.GetIndent() + 'Root Level Of Indentations \n' print(r) print(TFormat.GoodBad("This is a good result : "+str(1), 1 < 10)) print("This is a bad result : " + TFormat.GoodBad(10, 10 < 1)) print(TFormat.WithUnderline("This is a message using WithUnderline")) print(TFormat.WithItalic("This is a message using WithItalic")) print("Warning about the formatting :") print(TFormat.WithUnderline() + 'WithUnderline ' + TFormat.InRed()+"Red/WithUnderline" + TFormat.WithItalic()) print("you must clean the format at the end " + TFormat.CleanFormat() + " Good") print(TFormat.InIPython()) return 'ok'
if __name__ == '__main__': CheckIntegrity() # pragma: no cover