Skip to content

Commit 34aff68

Browse files
committed
Made len_color() safer and added testing
1 parent 4b60e82 commit 34aff68

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

progressbar/utils.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,25 @@
1919

2020

2121
def len_color(value):
22-
'''Return the length of `value` without ANSI escape codes'''
23-
if isinstance(value, str):
24-
value = re.sub(u'\u001b\\[.*?[@-~]', '', value)
22+
'''
23+
Return the length of `value` without ANSI escape codes
24+
25+
>>> len_color(u'\u001b[1234]abc')
26+
3
27+
>>> len_color(b'\u001b[1234]abc')
28+
3
29+
>>> len_color('\u001b[1234]abc')
30+
3
31+
'''
32+
pattern = u'\u001b\\[.*?[@-~]'
33+
if isinstance(value, bytes):
34+
pattern = pattern.encode()
35+
replace = b''
36+
assert isinstance(pattern, bytes)
37+
else:
38+
replace = ''
39+
40+
value = re.sub(pattern, replace, value)
2541
return len(value)
2642

2743

0 commit comments

Comments
 (0)