Skip to content

Commit

Permalink
Made len_color() safer and added testing
Browse files Browse the repository at this point in the history
  • Loading branch information
wolph committed Jul 13, 2019
1 parent 4b60e82 commit 34aff68
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions progressbar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,25 @@


def len_color(value):
'''Return the length of `value` without ANSI escape codes'''
if isinstance(value, str):
value = re.sub(u'\u001b\\[.*?[@-~]', '', value)
'''
Return the length of `value` without ANSI escape codes
>>> len_color(u'\u001b[1234]abc')
3
>>> len_color(b'\u001b[1234]abc')
3
>>> len_color('\u001b[1234]abc')
3
'''
pattern = u'\u001b\\[.*?[@-~]'
if isinstance(value, bytes):
pattern = pattern.encode()
replace = b''
assert isinstance(pattern, bytes)
else:
replace = ''

value = re.sub(pattern, replace, value)
return len(value)


Expand Down

0 comments on commit 34aff68

Please sign in to comment.