Added --we. Ignore AlreadyAsleepOrAwake error (-o).
[cnetworkmanager.git] / networkmanager / util.py
blob83595e0e73377d2df106ee691749ac2b966f6f7e
1 class NamedNumbers(object):
2 """Base for Enum and Flags."""
4 def __init__(self, value):
5 self.value = value
6 def __int__(self):
7 """
8 >>> n = NamedNumbers(42)
10 >>> int(n)
12 """
13 return self.value
15 class Enum(NamedNumbers):
16 """Enumeration."""
18 def __str__(self):
19 """
20 >>> class Foo(Enum):
21 ... ONE = 1
22 ... TWO = 2
24 >>> Foo.ONE
27 >>> str(Foo(Foo.TWO))
28 'TWO'
30 >>> str(Foo(3))
31 '3'
32 """
34 for n, v in self.__class__.__dict__.iteritems():
35 if v == self.value:
36 return n
37 return str(self.value)
38 # TODO __repr__
40 class Flags(NamedNumbers):
41 """Bit flags."""
43 def __str__(self):
44 """
45 >>> class MyFlags(Flags):
46 ... NONE = 0x0
47 ... EXECUTE = 0x1
48 ... WRITE = 0x2
49 ... READ = 0x4
51 >>> str(MyFlags(5))
52 'EXECUTE,READ'
54 >>> str(MyFlags(0))
55 'NONE'
57 >>> str(MyFlags(9)) # doctest: +SKIP
58 'EXECUTE,0x8'
59 """
61 has = {}
62 for n, v in self.__class__.__dict__.iteritems():
63 if isinstance(v, int): # FIXME long
64 if self.value & v or (self.value == 0 and v == 0):
65 has[v] = n
67 names = [has[v] for v in sorted(has.keys())]
68 # TODO unknown values?
69 return ",".join(names)
71 class Table(object):
72 """Formats a table
74 >>> t = Table("A", "Bee", "C")
76 >>> t.row("ay", "B", "sea")
78 >>> t.row("", "b", "c")
80 >>> print t
81 A | Bee | C
82 ---+-----+----
83 ay | B | sea
84 | b | c
86 >>> Table.terse = True
88 >>> print t
89 ay|B|sea
90 |b|c
91 """
92 # there are trailing spaces in the above non-terse printout
94 terse = False
95 "No headings and no padding, suitable for parsing."
97 def __init__(self, *args):
98 "The arguments are column headings."
100 self.headings = args
101 self.rows = []
103 @staticmethod
104 def from_items(obj, *items):
105 t = Table("Property", "Value")
106 for i in items:
107 t.row(i, obj[i])
108 return t
110 @staticmethod
111 def from_nested_dict(dd):
112 t = Table("Section", "Property", "Value")
113 for s, d in dd.iteritems():
114 t.row(s, "", "")
115 for k, v in d.iteritems():
116 if isinstance(v, list):
117 v = ", ".join(v)
118 t.row("", k, v)
119 return t
121 def row(self, *args):
122 """The arguments are row items.
124 str is applied to them"""
125 self.rows.append(map(str,args))
127 @staticmethod
128 def pad_row(row, col_sizes):
129 return map(str.ljust, row, col_sizes)
131 def col_widths(self):
132 "Returns a list of the column widths."
134 # the table of lengths of original items
135 lengths = map(lambda cells: map(len, cells), self.rows + [self.headings])
136 return reduce(lambda cells1, cells2: map(max, cells1, cells2), lengths)
138 def terse_str(self):
139 "Formats the table, tersely."
141 rs = map("|".join, self.rows)
142 return "\n".join(rs)
144 def __str__(self):
145 "Formats the table."
147 if self.terse:
148 return self.terse_str()
150 cw = self.col_widths()
151 def fmt_row(items):
152 return " | ".join(self.pad_row(items, cw))
153 h = fmt_row(self.headings)
154 s = "-+-".join(map(lambda w: "-" * w, cw))
155 rs = map(fmt_row, self.rows)
156 rs.insert(0, s)
157 rs.insert(0, h)
158 return "\n".join(rs)
161 if __name__ == "__main__":
162 import doctest
163 doctest.testmod()