]> jfr.im git - z_archive/twitter.git/commitdiff
Adding named colours.
authorHatem Nassrat <redacted>
Fri, 6 Mar 2009 13:15:49 +0000 (09:15 -0400)
committerHatem Nassrat <redacted>
Sun, 8 Mar 2009 21:45:39 +0000 (18:45 -0300)
Also:
    Added docstrings and module doc for ansi.
    Fixed a "bug" with the RESET command.

twitter/ansi.py

index 870dec2b5720fe3e98dd20a3adacb328eec7fc54..ae99ddb786daa09470fc05675bb62ead7c6a9f5d 100644 (file)
@@ -1,6 +1,17 @@
 """
 Support for ANSI colours in command-line client.
 
+.. data:: ESC
+    ansi escape character
+
+.. data:: RESET
+    ansi reset colour (ansi value)
+
+.. data:: COLOURS_NAMED
+    dict of colour names mapped to their ansi value
+
+.. data:: COLOURS_MIDS
+    A list of ansi values for Mid Spectrum Colours
 """
 
 import itertools
@@ -8,20 +19,51 @@ import itertools
 ESC = chr(0x1B)
 RESET = "0"
 
-COLOURS = [str(x) for x in range(31, 37)]
+COLOURS_NAMED = dict(zip(
+    ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'],
+    [str(x) for x in range(30, 38)]
+))
+COLOURS_MIDS = [
+    colour for name, colour in COLOURS_NAMED.items()
+    if name not in ('black', 'white')
+]
+
+class AnsiColourException(Exception):
+    ''' Exception while processing ansi colours '''
+    pass
 
 class ColourMap(object):
-    def __init__(self):
+    '''
+    Object that allows for mapping strings to ansi colour values.
+    '''
+    def __init__(self, colors=COLOURS_MIDS):
+        ''' uses the list of ansi `colors` values to initialize the map '''
         self._cmap = {}
-        self._colourIter = itertools.cycle(COLOURS)
-        
+        self._colourIter = itertools.cycle(colors)
+
     def colourFor(self, string):
+        '''
+        Returns an ansi colour value given a `string`.
+        The same ansi colour value is always returned for the same string
+        '''
         if not self._cmap.has_key(string):
             self._cmap[string] = self._colourIter.next()
         return self._cmap[string]
 
-def cmdReset():
-    return ESC + "[0m"
-
 def cmdColour(colour):
+    '''
+    Return the ansi cmd colour (i.e. escape sequence)
+    for the ansi `colour` value
+    '''
     return ESC + "[" + colour + "m"
+
+def cmdReset():
+    ''' Returns the ansi cmd colour for a RESET '''
+    return cmdColour(RESET)
+
+def cmdColourNamed(colour):
+    ''' Return the ansi cmdColour for a given named `colour` '''
+    try:
+        return cmdColour(COLOURS_NAMED[colour])
+    except KeyError:
+        raise AnsiColourException('Unknown Colour %s' %(colour))