]>
Commit | Line | Data |
---|---|---|
11fdf7f2 TL |
1 | |
2 | ( | |
3 | BLACK, | |
4 | RED, | |
5 | GREEN, | |
6 | YELLOW, | |
7 | BLUE, | |
8 | MAGENTA, | |
9 | CYAN, | |
10 | GRAY | |
11 | ) = range(8) | |
12 | ||
13 | RESET_SEQ = "\033[0m" | |
14 | COLOR_SEQ = "\033[1;%dm" | |
15 | COLOR_DARK_SEQ = "\033[0;%dm" | |
16 | BOLD_SEQ = "\033[1m" | |
17 | UNDERLINE_SEQ = "\033[4m" | |
18 | ||
19 | ||
20 | def colorize(msg, color, dark=False): | |
21 | """ | |
22 | Decorate `msg` with escape sequences to give the requested color | |
23 | """ | |
24 | return (COLOR_DARK_SEQ if dark else COLOR_SEQ) % (30 + color) \ | |
25 | + msg + RESET_SEQ | |
26 | ||
27 | ||
28 | def bold(msg): | |
29 | """ | |
30 | Decorate `msg` with escape sequences to make it appear bold | |
31 | """ | |
32 | return BOLD_SEQ + msg + RESET_SEQ | |
33 | ||
34 | ||
35 | def format_units(n, width, colored, decimal): | |
36 | """ | |
37 | Format a number without units, so as to fit into `width` characters, substituting | |
38 | an appropriate unit suffix. | |
39 | ||
40 | Use decimal for dimensionless things, use base 2 (decimal=False) for byte sizes/rates. | |
41 | """ | |
42 | ||
43 | factor = 1000 if decimal else 1024 | |
44 | units = [' ', 'k', 'M', 'G', 'T', 'P', 'E'] | |
45 | unit = 0 | |
46 | while len("%s" % (int(n) // (factor**unit))) > width - 1: | |
47 | unit += 1 | |
48 | ||
49 | if unit > 0: | |
50 | truncated_float = ("%f" % (n / (float(factor) ** unit)))[0:width - 1] | |
51 | if truncated_float[-1] == '.': | |
52 | truncated_float = " " + truncated_float[0:-1] | |
53 | else: | |
54 | truncated_float = "%{wid}d".format(wid=width - 1) % n | |
55 | formatted = "%s%s" % (truncated_float, units[unit]) | |
56 | ||
57 | if colored: | |
58 | if n == 0: | |
59 | color = BLACK, False | |
60 | else: | |
61 | color = YELLOW, False | |
62 | return bold(colorize(formatted[0:-1], color[0], color[1])) \ | |
63 | + bold(colorize(formatted[-1], BLACK, False)) | |
64 | else: | |
65 | return formatted | |
66 | ||
67 | ||
68 | def format_dimless(n, width, colored=True): | |
69 | return format_units(n, width, colored, decimal=True) | |
70 | ||
71 | ||
72 | def format_bytes(n, width, colored=True): | |
73 | return format_units(n, width, colored, decimal=False) | |
81eedcae TL |
74 | |
75 | ||
76 | def merge_dicts(*args): | |
77 | # type: (dict) -> dict | |
78 | """ | |
79 | >>> assert merge_dicts({1:2}, {3:4}) == {1:2, 3:4} | |
80 | You can also overwrite keys: | |
81 | >>> assert merge_dicts({1:2}, {1:4}) == {1:4} | |
82 | :rtype: dict[str, Any] | |
83 | """ | |
84 | ret = {} | |
85 | for arg in args: | |
86 | ret.update(arg) | |
87 | return ret |