[dts] [PATCH for-next v3 1/7] framework/texttable: Update to latest upstream version
Patrick MacArthur
pmacarth at iol.unh.edu
Thu Mar 29 21:15:59 CEST 2018
Both DTS and the T-Rex Python API use the Python texttable module. The
texttable module that is currently bundled with DTS is old and does not
support methods required by t-rex. Fix this by replacing it with an
updated version of the module [1]. Both the old and new version of this
module are made available by the author under the LGPL-2.1+ license.
[1]: https://github.com/foutaise/texttable/blob/master/texttable.py
Tested-by: Ali Alnubani <alialnu at mellanox.com>
Signed-off-by: Patrick MacArthur <pmacarth at iol.unh.edu>
---
framework/texttable.py | 145 ++++++++++++++++++++++++++++++++-----------------
1 file changed, 96 insertions(+), 49 deletions(-)
diff --git a/framework/texttable.py b/framework/texttable.py
index 2f37a0c7ba58..9f049035cf3e 100644
--- a/framework/texttable.py
+++ b/framework/texttable.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
#
# texttable - module for creating simple ASCII tables
-# Copyright (C) 2003-2011 Gerome Fournier <jef(at)foutaise.org>
+# Copyright (C) 2003-2015 Gerome Fournier <jef(at)foutaise.org>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
@@ -15,7 +15,7 @@
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
"""module for creating simple ASCII tables
@@ -25,9 +25,9 @@ Example:
table = Texttable()
table.set_cols_align(["l", "r", "c"])
table.set_cols_valign(["t", "m", "b"])
- table.add_rows([ ["Name", "Age", "Nickname"],
- ["Mr\\nXavier\\nHuon", 32, "Xav'"],
- ["Mr\\nBaptiste\\nClement", 1, "Baby"] ])
+ table.add_rows([["Name", "Age", "Nickname"],
+ ["Mr\\nXavier\\nHuon", 32, "Xav'"],
+ ["Mr\\nBaptiste\\nClement", 1, "Baby"]])
print table.draw() + "\\n"
table = Texttable()
@@ -70,8 +70,8 @@ Result:
__all__ = ["Texttable", "ArraySizeError"]
__author__ = 'Gerome Fournier <jef(at)foutaise.org>'
-__license__ = 'GPL'
-__version__ = '0.8.1'
+__license__ = 'LGPL'
+__version__ = '0.8.4'
__credits__ = """\
Jeff Kowalczyk:
- textwrap improved import
@@ -88,11 +88,17 @@ Roger Lew:
Brian Peterson:
- better handling of unicode errors
+
+Frank Sachsenheim:
+ - add Python 2/3-compatibility
+
+Maximilian Hils:
+ - fix minor bug for Python 3 compatibility
"""
import sys
import string
-from functools import reduce
+import re
try:
if sys.version >= '2.3':
@@ -105,11 +111,8 @@ except ImportError:
sys.stderr.write("Can't import textwrap module!\n")
raise
-try:
- True, False
-except NameError:
- (True, False) = (1, 0)
-
+if sys.version >= '2.7':
+ from functools import reduce
def len(iterable):
"""Redefining len here so it will be able to work with non-ASCII characters
@@ -118,13 +121,45 @@ def len(iterable):
return iterable.__len__()
try:
- return len(unicode(iterable, 'utf'))
+ if sys.version >= '3.0':
+ return len(str)
+ else:
+ return len(unicode(iterable, 'utf'))
except:
return iterable.__len__()
-class ArraySizeError(Exception):
+TEXT_CODES = {'bold': {'start': '\x1b[1m',
+ 'end': '\x1b[22m'},
+ 'cyan': {'start': '\x1b[36m',
+ 'end': '\x1b[39m'},
+ 'blue': {'start': '\x1b[34m',
+ 'end': '\x1b[39m'},
+ 'red': {'start': '\x1b[31m',
+ 'end': '\x1b[39m'},
+ 'magenta': {'start': '\x1b[35m',
+ 'end': '\x1b[39m'},
+ 'green': {'start': '\x1b[32m',
+ 'end': '\x1b[39m'},
+ 'yellow': {'start': '\x1b[33m',
+ 'end': '\x1b[39m'},
+ 'underline': {'start': '\x1b[4m',
+ 'end': '\x1b[24m'}}
+
+class TextCodesStripper:
+ keys = [re.escape(v['start']) for k,v in TEXT_CODES.items()]
+ keys += [re.escape(v['end']) for k,v in TEXT_CODES.items()]
+ pattern = re.compile("|".join(keys))
+
+ @staticmethod
+ def strip (s):
+ return re.sub(TextCodesStripper.pattern, '', s)
+
+def ansi_len (iterable):
+ return len(TextCodesStripper.strip(iterable))
+
+class ArraySizeError(Exception):
"""Exception raised when specified rows don't fit the required size
"""
@@ -185,7 +220,7 @@ class Texttable:
if len(array) != 4:
raise ArraySizeError("array should contain 4 characters")
- array = [x[:1] for x in [str(s) for s in array]]
+ array = [ x[:1] for x in [ str(s) for s in array ] ]
(self._char_horiz, self._char_vert,
self._char_corner, self._char_header) = array
@@ -262,7 +297,7 @@ class Texttable:
self._check_row_size(array)
try:
- array = map(int, array)
+ array = list(map(int, array))
if reduce(min, array) <= 0:
raise ValueError
except ValueError:
@@ -278,7 +313,7 @@ class Texttable:
- default value is set to 3
"""
- if not isinstance(width, int) or width < 0:
+ if not type(width) is int or width < 0:
raise ValueError('width must be an integer greater then 0')
self._precision = width
@@ -287,7 +322,7 @@ class Texttable:
"""
self._check_row_size(array)
- self._header = map(str, array)
+ self._header = list(map(str, array))
def add_row(self, array):
"""Add a row in the rows stack
@@ -361,7 +396,11 @@ class Texttable:
try:
f = float(x)
except:
- return str(x)
+ try:
+ return str(x)
+ except:
+ return x.encode('utf-8')
+
n = self._precision
dtype = self._dtype[i]
@@ -393,8 +432,8 @@ class Texttable:
if not self._row_size:
self._row_size = len(array)
elif self._row_size != len(array):
- raise ArraySizeError("array should contain %d elements"
- % self._row_size)
+ raise ArraySizeError("array should contain %d elements" \
+ % self._row_size)
def _has_vlines(self):
"""Return a boolean, if vlines are required or not
@@ -443,13 +482,13 @@ class Texttable:
horiz = self._char_header
# compute cell separator
s = "%s%s%s" % (horiz, [horiz, self._char_corner][self._has_vlines()],
- horiz)
+ horiz)
# build the line
- l = string.join([horiz * n for n in self._width], s)
+ l = s.join([horiz * n for n in self._width])
# add border if needed
if self._has_border():
l = "%s%s%s%s%s\n" % (self._char_corner, horiz, l, horiz,
- self._char_corner)
+ self._char_corner)
else:
l += "\n"
return l
@@ -466,10 +505,10 @@ class Texttable:
for line in cell_lines:
length = 0
parts = line.split('\t')
- for part, i in zip(parts, range(1, len(parts) + 1)):
+ for part, i in zip(parts, list(range(1, len(parts) + 1))):
length = length + len(part)
if i < len(parts):
- length = (length / 8 + 1) * 8
+ length = (length//8 + 1) * 8
maxi = max(maxi, length)
return maxi
@@ -485,17 +524,17 @@ class Texttable:
return
maxi = []
if self._header:
- maxi = [self._len_cell(x) for x in self._header]
+ maxi = [ self._len_cell(x) for x in self._header ]
for row in self._rows:
- for cell, i in zip(row, range(len(row))):
+ for cell,i in zip(row, list(range(len(row)))):
try:
maxi[i] = max(maxi[i], self._len_cell(cell))
except (TypeError, IndexError):
maxi.append(self._len_cell(cell))
items = len(maxi)
- length = reduce(lambda x, y: x + y, maxi)
+ length = reduce(lambda x, y: x+y, maxi)
if self._max_width and length + items * 3 + 1 > self._max_width:
- maxi = [(self._max_width - items * 3 - 1) / items
+ maxi = [(self._max_width - items * 3 -1) // items \
for n in range(items)]
self._width = maxi
@@ -524,14 +563,14 @@ class Texttable:
for cell, width, align in zip(line, self._width, self._align):
length += 1
cell_line = cell[i]
- fill = width - len(cell_line)
+ fill = width - ansi_len(cell_line)
if isheader:
- align = "l"
+ align = "c"
if align == "r":
out += "%s " % (fill * space + cell_line)
elif align == "c":
- out += "%s " % (fill / 2 * space + cell_line
- + (fill / 2 + fill % 2) * space)
+ out += "%s " % (int(fill/2) * space + cell_line \
+ + int(fill/2 + fill%2) * space)
else:
out += "%s " % (cell_line + fill * space)
if length < len(line):
@@ -551,26 +590,34 @@ class Texttable:
array = []
for c in cell.split('\n'):
try:
- c = unicode(c, 'utf')
+ c = str(c)
except UnicodeDecodeError as strerror:
sys.stderr.write("UnicodeDecodeError exception for string '%s': %s\n" % (c, strerror))
- c = unicode(c, 'utf', 'replace')
- array.extend(textwrap.wrap(c, width))
+ if sys.version >= '3.0':
+ c = str(c, 'utf', 'replace')
+ else:
+ c = unicode(c, 'utf', 'replace')
+
+ # imarom - no wrap for now
+ #array.extend(textwrap.wrap(c, width))
+ array.extend([c])
+
line_wrapped.append(array)
- max_cell_lines = reduce(max, map(len, line_wrapped))
+ max_cell_lines = reduce(max, list(map(len, line_wrapped)))
for cell, valign in zip(line_wrapped, self._valign):
if isheader:
valign = "t"
if valign == "m":
missing = max_cell_lines - len(cell)
- cell[:0] = [""] * (missing / 2)
- cell.extend([""] * (missing / 2 + missing % 2))
+ cell[:0] = [""] * int(missing / 2)
+ cell.extend([""] * int(missing / 2 + missing % 2))
elif valign == "b":
cell[:0] = [""] * (max_cell_lines - len(cell))
else:
cell.extend([""] * (max_cell_lines - len(cell)))
return line_wrapped
+
if __name__ == '__main__':
table = Texttable()
table.set_cols_align(["l", "r", "c"])
@@ -578,7 +625,7 @@ if __name__ == '__main__':
table.add_rows([["Name", "Age", "Nickname"],
["Mr\nXavier\nHuon", 32, "Xav'"],
["Mr\nBaptiste\nClement", 1, "Baby"]])
- print table.draw() + "\n"
+ print(table.draw() + "\n")
table = Texttable()
table.set_deco(Texttable.HEADER)
@@ -586,11 +633,11 @@ if __name__ == '__main__':
'f', # float (decimal)
'e', # float (exponent)
'i', # integer
- 'a']) # automatic
+ 'a']) # automatic
table.set_cols_align(["l", "r", "r", "r", "l"])
- table.add_rows([["text", "float", "exp", "int", "auto"],
- ["abcd", "67", 654, 89, 128.001],
- ["efghijk", 67.5434, .654, 89.6, 12800000000000000000000.00023],
- ["lmn", 5e-78, 5e-78, 89.4, .000000000000128],
- ["opqrstu", .023, 5e+78, 92., 12800000000000000000000]])
- print table.draw()
+ table.add_rows([["text", "float", "exp", "int", "auto"],
+ ["abcd", "67", 654, 89, 128.001],
+ ["efghijk", 67.5434, .654, 89.6, 12800000000000000000000.00023],
+ ["lmn", 5e-78, 5e-78, 89.4, .000000000000128],
+ ["opqrstu", .023, 5e+78, 92., 12800000000000000000000]])
+ print(table.draw())
--
2.14.1
More information about the dts
mailing list