summaryrefslogtreecommitdiff
path: root/lib/spack/llnl/util/tty
diff options
context:
space:
mode:
Diffstat (limited to 'lib/spack/llnl/util/tty')
-rw-r--r--lib/spack/llnl/util/tty/__init__.py12
-rw-r--r--lib/spack/llnl/util/tty/colify.py32
-rw-r--r--lib/spack/llnl/util/tty/color.py29
-rw-r--r--lib/spack/llnl/util/tty/log.py16
4 files changed, 51 insertions, 38 deletions
diff --git a/lib/spack/llnl/util/tty/__init__.py b/lib/spack/llnl/util/tty/__init__.py
index ee81e11a20..db74aaba6b 100644
--- a/lib/spack/llnl/util/tty/__init__.py
+++ b/lib/spack/llnl/util/tty/__init__.py
@@ -36,6 +36,7 @@ _debug = False
_verbose = False
indent = " "
+
def is_verbose():
return _verbose
@@ -148,7 +149,8 @@ def get_yes_or_no(prompt, **kwargs):
elif default_value is False:
prompt += ' [y/N] '
else:
- raise ValueError("default for get_yes_no() must be True, False, or None.")
+ raise ValueError(
+ "default for get_yes_no() must be True, False, or None.")
result = None
while result is None:
@@ -174,8 +176,9 @@ def hline(label=None, **kwargs):
char = kwargs.pop('char', '-')
max_width = kwargs.pop('max_width', 64)
if kwargs:
- raise TypeError("'%s' is an invalid keyword argument for this function."
- % next(kwargs.iterkeys()))
+ raise TypeError(
+ "'%s' is an invalid keyword argument for this function."
+ % next(kwargs.iterkeys()))
rows, cols = terminal_size()
if not cols:
@@ -200,7 +203,8 @@ def terminal_size():
"""Gets the dimensions of the console: (rows, cols)."""
def ioctl_GWINSZ(fd):
try:
- rc = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
+ rc = struct.unpack('hh', fcntl.ioctl(
+ fd, termios.TIOCGWINSZ, '1234'))
except:
return
return rc
diff --git a/lib/spack/llnl/util/tty/colify.py b/lib/spack/llnl/util/tty/colify.py
index 81a83691d7..67acdfa517 100644
--- a/lib/spack/llnl/util/tty/colify.py
+++ b/lib/spack/llnl/util/tty/colify.py
@@ -27,15 +27,14 @@ Routines for printing columnar output. See colify() for more information.
"""
import os
import sys
-import fcntl
-import termios
-import struct
from StringIO import StringIO
from llnl.util.tty import terminal_size
from llnl.util.tty.color import clen, cextra
+
class ColumnConfig:
+
def __init__(self, cols):
self.cols = cols
self.line_length = 0
@@ -43,7 +42,8 @@ class ColumnConfig:
self.widths = [0] * cols # does not include ansi colors
def __repr__(self):
- attrs = [(a,getattr(self, a)) for a in dir(self) if not a.startswith("__")]
+ attrs = [(a, getattr(self, a))
+ for a in dir(self) if not a.startswith("__")]
return "<Config: %s>" % ", ".join("%s: %r" % a for a in attrs)
@@ -68,7 +68,7 @@ def config_variable_cols(elts, console_width, padding, cols=0):
max_cols = min(len(elts), max_cols)
# Range of column counts to try. If forced, use the supplied value.
- col_range = [cols] if cols else xrange(1, max_cols+1)
+ col_range = [cols] if cols else xrange(1, max_cols + 1)
# Determine the most columns possible for the console width.
configs = [ColumnConfig(c) for c in col_range]
@@ -106,7 +106,6 @@ def config_uniform_cols(elts, console_width, padding, cols=0):
# 'clen' ignores length of ansi color sequences.
max_len = max(clen(e) for e in elts) + padding
- max_clen = max(len(e) for e in elts) + padding
if cols == 0:
cols = max(1, console_width / max_len)
cols = min(len(elts), cols)
@@ -130,17 +129,19 @@ def colify(elts, **options):
output=<stream> A file object to write to. Default is sys.stdout.
indent=<int> Optionally indent all columns by some number of spaces.
padding=<int> Spaces between columns. Default is 2.
- width=<int> Width of the output. Default is 80 if tty is not detected.
+ width=<int> Width of the output. Default is 80 if tty not detected.
cols=<int> Force number of columns. Default is to size to terminal,
or single-column if no tty
tty=<bool> Whether to attempt to write to a tty. Default is to
- autodetect a tty. Set to False to force single-column output.
+ autodetect a tty. Set to False to force
+ single-column output.
- method=<string> Method to use to fit columns. Options are variable or uniform.
- Variable-width columns are tighter, uniform columns are all the
- same width and fit less data on the screen.
+ method=<string> Method to use to fit columns. Options are variable or
+ uniform. Variable-width columns are tighter, uniform
+ columns are all the same width and fit less data on
+ the screen.
"""
# Get keyword arguments or set defaults
cols = options.pop("cols", 0)
@@ -152,8 +153,9 @@ def colify(elts, **options):
console_cols = options.pop("width", None)
if options:
- raise TypeError("'%s' is an invalid keyword argument for this function."
- % next(options.iterkeys()))
+ raise TypeError(
+ "'%s' is an invalid keyword argument for this function."
+ % next(options.iterkeys()))
# elts needs to be an array of strings so we can count the elements
elts = [str(elt) for elt in elts]
@@ -167,7 +169,8 @@ def colify(elts, **options):
r, c = env_size.split('x')
console_rows, console_cols = int(r), int(c)
tty = True
- except: pass
+ except:
+ pass
# Use only one column if not a tty.
if not tty:
@@ -228,6 +231,7 @@ def colify_table(table, **options):
raise ValueError("Table is empty in colify_table!")
columns = len(table[0])
+
def transpose():
for i in xrange(columns):
for row in table:
diff --git a/lib/spack/llnl/util/tty/color.py b/lib/spack/llnl/util/tty/color.py
index 0abcb09b97..b0c00f1502 100644
--- a/lib/spack/llnl/util/tty/color.py
+++ b/lib/spack/llnl/util/tty/color.py
@@ -75,25 +75,27 @@ To output an @, use '@@'. To output a } inside braces, use '}}'.
import re
import sys
+
class ColorParseError(Exception):
"""Raised when a color format fails to parse."""
+
def __init__(self, message):
super(ColorParseError, self).__init__(message)
# Text styles for ansi codes
-styles = {'*' : '1', # bold
- '_' : '4', # underline
- None : '0' } # plain
+styles = {'*': '1', # bold
+ '_': '4', # underline
+ None: '0'} # plain
# Dim and bright ansi colors
-colors = {'k' : 30, 'K' : 90, # black
- 'r' : 31, 'R' : 91, # red
- 'g' : 32, 'G' : 92, # green
- 'y' : 33, 'Y' : 93, # yellow
- 'b' : 34, 'B' : 94, # blue
- 'm' : 35, 'M' : 95, # magenta
- 'c' : 36, 'C' : 96, # cyan
- 'w' : 37, 'W' : 97 } # white
+colors = {'k': 30, 'K': 90, # black
+ 'r': 31, 'R': 91, # red
+ 'g': 32, 'G': 92, # green
+ 'y': 33, 'Y': 93, # yellow
+ 'b': 34, 'B': 94, # blue
+ 'm': 35, 'M': 95, # magenta
+ 'c': 36, 'C': 96, # cyan
+ 'w': 37, 'W': 97} # white
# Regex to be used for color formatting
color_re = r'@(?:@|\.|([*_])?([a-zA-Z])?(?:{((?:[^}]|}})*)})?)'
@@ -104,6 +106,7 @@ _force_color = False
class match_to_ansi(object):
+
def __init__(self, color=True):
self.color = color
@@ -179,12 +182,14 @@ def cprint(string, stream=sys.stdout, color=None):
"""Same as cwrite, but writes a trailing newline to the stream."""
cwrite(string + "\n", stream, color)
+
def cescape(string):
"""Replace all @ with @@ in the string provided."""
return str(string).replace('@', '@@')
class ColorStream(object):
+
def __init__(self, stream, color=None):
self._stream = stream
self._color = color
@@ -196,7 +201,7 @@ class ColorStream(object):
color = self._color
if self._color is None:
if raw:
- color=True
+ color = True
else:
color = self._stream.isatty() or _force_color
raw_write(colorize(string, color=color))
diff --git a/lib/spack/llnl/util/tty/log.py b/lib/spack/llnl/util/tty/log.py
index ca82da7b17..b67edcf9cc 100644
--- a/lib/spack/llnl/util/tty/log.py
+++ b/lib/spack/llnl/util/tty/log.py
@@ -36,6 +36,7 @@ import llnl.util.tty.color as color
# Use this to strip escape sequences
_escape = re.compile(r'\x1b[^m]*m|\x1b\[?1034h')
+
def _strip(line):
"""Strip color and control characters from a line."""
return _escape.sub('', line)
@@ -58,10 +59,10 @@ class keyboard_input(object):
When the with block completes, this will restore settings before
canonical and echo were disabled.
"""
+
def __init__(self, stream):
self.stream = stream
-
def __enter__(self):
self.old_cfg = None
@@ -86,10 +87,9 @@ class keyboard_input(object):
# Apply new settings for terminal
termios.tcsetattr(fd, termios.TCSADRAIN, self.new_cfg)
- except Exception, e:
+ except Exception:
pass # Some OS's do not support termios, so ignore.
-
def __exit__(self, exc_type, exception, traceback):
# If termios was avaialble, restore old settings after the
# with block
@@ -114,6 +114,7 @@ class log_output(object):
Closes the provided stream when done with the block.
If echo is True, also prints the output to stdout.
"""
+
def __init__(self, stream, echo=False, force_color=False, debug=False):
self.stream = stream
@@ -122,7 +123,7 @@ class log_output(object):
self.force_color = force_color
self.debug = debug
- # Default is to try file-descriptor reassignment unless the system
+ # Default is to try file-descriptor reassignment unless the system
# out/err streams do not have an associated file descriptor
self.directAssignment = False
@@ -130,7 +131,6 @@ class log_output(object):
"""Jumps to __exit__ on the child process."""
raise _SkipWithBlock()
-
def __enter__(self):
"""Redirect output from the with block to a file.
@@ -154,7 +154,8 @@ class log_output(object):
with self.stream as log_file:
with keyboard_input(sys.stdin):
while True:
- rlist, w, x = select.select([read_file, sys.stdin], [], [])
+ rlist, w, x = select.select(
+ [read_file, sys.stdin], [], [])
if not rlist:
break
@@ -211,7 +212,6 @@ class log_output(object):
if self.debug:
tty._debug = True
-
def __exit__(self, exc_type, exception, traceback):
"""Exits on child, handles skipping the with block on parent."""
# Child should just exit here.
@@ -235,7 +235,7 @@ class log_output(object):
sys.stderr = self._stderr
else:
os.dup2(self._stdout, sys.stdout.fileno())
- os.dup2(self._stderr, sys.stderr.fileno())
+ os.dup2(self._stderr, sys.stderr.fileno())
return False