Add random and rainbow

Use "random" as a color or a style to pick a random one for each pattern.
Use "rainbow" as a color to alternate colors in rainbow gradient.
Fix #1
This commit is contained in:
Johann Dreo 2013-03-01 00:10:56 +01:00
commit 119bba5bb5
2 changed files with 38 additions and 12 deletions

View file

@ -19,11 +19,11 @@ with commas. If you indicate more colors than groups, the last ones will be igno
If you ask for less colors, the last one will be duplicated across remaining
groups.
Available colors are: blue, black, yellow, cyan, green, magenta, white, red or
any number between 0 and 255.
Available colors are: blue, black, yellow, cyan, green, magenta, white, red,
rainbow, random, or any number between 0 and 255.
Available styles are: normal, bold, faint, italic, underline, blink,
rapid_blink, reverse, conceal.
Available styles are: normal, bold, faint, italic, underline, blink,
rapid_blink, reverse, conceal or random.
When not specified, a *COLOR* defaults to _red_ and a *STYLE* defaults to _bold_.
@ -56,6 +56,9 @@ special characters that would be recognize by your shell.
* Color in bold violet home directories in _/etc/passwd_:
`colout /home/[a-z]+ 135 < /etc/passwd`
* Use a different color for each line of the auth log
`grep user /var/log/auth.log | colout "^.*$" rainbow`
* Color in yellow user/groups id, in bold green name and in bold red home directories in _/etc/passwd_:
`colout :x:\([0-9]+:[0-9]+\):\([a-z]+\).*\(/home/[a-z]+\) yellow,green,red normal,bold < /etc/passwd`

39
colout.py Normal file → Executable file
View file

@ -3,10 +3,10 @@
# Color Up Arbitrary Command Ouput
# Licensed under the GPL version 3
# 2012 (c) nojhan <nojhan@gmail.com>
# 2012 (c) nojhan <nojhan@nojhan.net>
import re
import random
###########
# Library #
@ -25,6 +25,9 @@ colors = {
"magenta":5, "cyan":6, "white":7
}
rainbow = [ "red", "yellow", "green", "cyan", "blue", "magenta" ]
rainbow_idx = 0
# Escaped end markers for given color modes
endmarks = {8:";", 256:";38;5;"}
@ -45,22 +48,42 @@ def colorin( text, color = "red", style = "normal" ):
# Special characters.
start = "\033["
stop = "\033[0m"
# Convert the style code
assert( style in styles )
if style == "random":
style = random.choice(list(styles.keys()))
else:
assert( style in styles)
style_code = str(styles[style])
if color == "random":
mode = 8
color_code = random.choice(list(colors.values()))
color_code = str( 30 + color_code )
elif color == "rainbow":
global rainbow_idx
mode = 8
color = rainbow[rainbow_idx]
color_code = str( 30 + colors[color] )
if rainbow_idx < len(rainbow)-1:
rainbow_idx += 1
else:
rainbow_idx = 0
# 8 colors modes
if color in colors:
elif color in colors:
mode = 8
color_code = str( 30 + colors[color] )
# 256 colors mode
else:
else:
mode = 256
color_nb = int( color )
assert( 0 <= color_nb <= 255 )
color_code = str( color )
color_code = str( color )
return start + style_code + endmarks[mode] + color_code + "m" + text + stop