1""" 2Functions used for CLI color themes. 3""" 4 5 6import logging 7import os 8 9from salt.utils.textformat import TextFormat 10 11log = logging.getLogger(__name__) 12 13 14def get_color_theme(theme): 15 """ 16 Return the color theme to use 17 """ 18 # Keep the heavy lifting out of the module space 19 import salt.utils.data 20 import salt.utils.files 21 import salt.utils.yaml 22 23 if not os.path.isfile(theme): 24 log.warning("The named theme %s if not available", theme) 25 26 try: 27 with salt.utils.files.fopen(theme, "rb") as fp_: 28 colors = salt.utils.data.decode(salt.utils.yaml.safe_load(fp_)) 29 ret = {} 30 for color in colors: 31 ret[color] = "\033[{}m".format(colors[color]) 32 if not isinstance(colors, dict): 33 log.warning("The theme file %s is not a dict", theme) 34 return {} 35 return ret 36 except Exception: # pylint: disable=broad-except 37 log.warning("Failed to read the color theme %s", theme) 38 return {} 39 40 41def get_colors(use=True, theme=None): 42 """ 43 Return the colors as an easy to use dict. Pass `False` to deactivate all 44 colors by setting them to empty strings. Pass a string containing only the 45 name of a single color to be used in place of all colors. Examples: 46 47 .. code-block:: python 48 49 colors = get_colors() # enable all colors 50 no_colors = get_colors(False) # disable all colors 51 red_colors = get_colors('RED') # set all colors to red 52 53 """ 54 55 colors = { 56 "BLACK": TextFormat("black"), 57 "DARK_GRAY": TextFormat("bold", "black"), 58 "RED": TextFormat("red"), 59 "LIGHT_RED": TextFormat("bold", "red"), 60 "GREEN": TextFormat("green"), 61 "LIGHT_GREEN": TextFormat("bold", "green"), 62 "YELLOW": TextFormat("yellow"), 63 "LIGHT_YELLOW": TextFormat("bold", "yellow"), 64 "BLUE": TextFormat("blue"), 65 "LIGHT_BLUE": TextFormat("bold", "blue"), 66 "MAGENTA": TextFormat("magenta"), 67 "LIGHT_MAGENTA": TextFormat("bold", "magenta"), 68 "CYAN": TextFormat("cyan"), 69 "LIGHT_CYAN": TextFormat("bold", "cyan"), 70 "LIGHT_GRAY": TextFormat("white"), 71 "WHITE": TextFormat("bold", "white"), 72 "DEFAULT_COLOR": TextFormat("default"), 73 "ENDC": TextFormat("reset"), 74 } 75 if theme: 76 colors.update(get_color_theme(theme)) 77 78 if not use: 79 for color in colors: 80 colors[color] = "" 81 if isinstance(use, str): 82 # Try to set all of the colors to the passed color 83 if use in colors: 84 for color in colors: 85 # except for color reset 86 if color == "ENDC": 87 continue 88 colors[color] = colors[use] 89 90 return colors 91