lsst.pex.config  16.0-5-gd0f1235+5
history.py
Go to the documentation of this file.
1 #
2 # LSST Data Management System
3 # Copyright 2008, 2009, 2010 LSST Corporation.
4 #
5 # This product includes software developed by the
6 # LSST Project (http://www.lsst.org/).
7 #
8 # This program is free software: you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation, either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the LSST License Statement and
19 # the GNU General Public License along with this program. If not,
20 # see <http://www.lsstcorp.org/LegalNotices/>.
21 #
22 
23 import os
24 import re
25 import sys
26 
27 
28 class Color:
29  """Control whether strings should be coloured
30 
31  The usual usage is `Color(string, category)` which returns a string that
32  may be printed; categories are given by the keys of Color.categories
33 
34  Color.colorize() may be used to set or retrieve whether the user wants
35  colour; it always returns False when sys.stdout is not attached to a
36  terminal.
37  """
38 
39  categories = dict(
40  NAME="blue",
41  VALUE="yellow",
42  FILE="green",
43  TEXT="red",
44  FUNCTION_NAME="blue",
45  )
46 
47  colors = {
48  "black": 0,
49  "red": 1,
50  "green": 2,
51  "yellow": 3,
52  "blue": 4,
53  "magenta": 5,
54  "cyan": 6,
55  "white": 7,
56  }
57 
58  _colorize = True
59 
60  def __init__(self, text, category):
61  """Return a string that should display as coloured on a conformant terminal"""
62  try:
63  color = Color.categories[category]
64  except KeyError:
65  raise RuntimeError("Unknown category: %s" % category)
66 
67  self.rawText = str(text)
68  x = color.lower().split(";")
69  self.color, bold = x.pop(0), False
70  if x:
71  props = x.pop(0)
72  if props in ("bold",):
73  bold = True
74 
75  try:
76  self._code = "%s" % (30 + Color.colors[self.color])
77  except KeyError:
78  raise RuntimeError("Unknown colour: %s" % self.color)
79 
80  if bold:
81  self._code += ";1"
82 
83  @staticmethod
84  def colorize(val=None):
85  """Should I colour strings? With an argument, set the value
86 
87  The value is usually a bool, but it may be a dict which is used
88  to modify Color.categories
89 
90  N.b. only strings written to a terminal are colourized
91  """
92 
93  if val is not None:
94  Color._colorize = val
95 
96  if isinstance(val, dict):
97  unknown = []
98  for k in val:
99  if k in Color.categories:
100  if val[k] in Color.colors:
101  Color.categories[k] = val[k]
102  else:
103  print("Unknown colour %s for category %s" % (val[k], k), file=sys.stderr)
104  else:
105  unknown.append(k)
106 
107  if unknown:
108  print("Unknown colourizing category: %s" % " ".join(unknown), file=sys.stderr)
109 
110  return Color._colorize if sys.stdout.isatty() else False
111 
112  def __str__(self):
113  if not self.colorize():
114  return self.rawText
115 
116  base = "\033["
117 
118  prefix = base + self._code + "m"
119  suffix = base + "m"
120 
121  return prefix + self.rawText + suffix
122 
123 
124 def _colorize(text, category):
125  text = Color(text, category)
126  return str(text)
127 
128 
129 def format(config, name=None, writeSourceLine=True, prefix="", verbose=False):
130  """Format the history record for config.name"""
131 
132  if name is None:
133  for i, name in enumerate(config.history.keys()):
134  if i > 0:
135  print()
136  print(format(config, name))
137 
138  outputs = []
139  for value, stack, label in config.history[name]:
140  output = []
141  for frame in stack:
142  if frame.function in ("__new__", "__set__", "__setattr__", "execfile", "wrapper") or \
143  os.path.split(frame.filename)[1] in ("argparse.py", "argumentParser.py"):
144  if not verbose:
145  continue
146 
147  line = []
148  if writeSourceLine:
149  line.append(["%s" % ("%s:%d" % (frame.filename, frame.lineno)), "FILE", ])
150 
151  line.append([frame.content, "TEXT", ])
152  if False:
153  line.append([frame.function, "FUNCTION_NAME", ])
154 
155  output.append(line)
156 
157  outputs.append([value, output])
158  #
159  # Find the maximum widths of the value and file:lineNo fields
160  #
161  if writeSourceLine:
162  sourceLengths = []
163  for value, output in outputs:
164  sourceLengths.append(max([len(x[0][0]) for x in output]))
165  sourceLength = max(sourceLengths)
166 
167  valueLength = len(prefix) + max([len(str(value)) for value, output in outputs])
168  #
169  # actually generate the config history
170  #
171  msg = []
172  fullname = "%s.%s" % (config._name, name) if config._name is not None else name
173  msg.append(_colorize(re.sub(r"^root\.", "", fullname), "NAME"))
174  for value, output in outputs:
175  line = prefix + _colorize("%-*s" % (valueLength, value), "VALUE") + " "
176  for i, vt in enumerate(output):
177  if writeSourceLine:
178  vt[0][0] = "%-*s" % (sourceLength, vt[0][0])
179 
180  output[i] = " ".join([_colorize(v, t) for v, t in vt])
181 
182  line += ("\n%*s" % (valueLength + 1, "")).join(output)
183  msg.append(line)
184 
185  return "\n".join(msg)
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:129
def colorize(val=None)
Definition: history.py:84
def __init__(self, text, category)
Definition: history.py:60