diff --git a/fire/formatting.py b/fire/formatting.py index 68484c27..77665b2e 100644 --- a/fire/formatting.py +++ b/fire/formatting.py @@ -81,12 +81,13 @@ def EllipsisMiddleTruncate(text, available_space, line_length): """Truncates text from the middle with ellipsis.""" if available_space < len(ELLIPSIS): available_space = line_length - if len(text) < available_space: + if len(text) <= available_space: return text available_string_len = available_space - len(ELLIPSIS) first_half_len = int(available_string_len / 2) # start from middle second_half_len = available_string_len - first_half_len - return text[:first_half_len] + ELLIPSIS + text[-second_half_len:] + suffix = text[-second_half_len:] if second_half_len else '' + return text[:first_half_len] + ELLIPSIS + suffix def DoubleQuote(text): diff --git a/fire/formatting_test.py b/fire/formatting_test.py index e0f6699d..7d3af6f2 100644 --- a/fire/formatting_test.py +++ b/fire/formatting_test.py @@ -73,6 +73,30 @@ def test_ellipsis_middle_truncate_not_enough_space(self): text=text, available_space=2, line_length=LINE_LENGTH) self.assertEqual('1000000000L', truncated_text) + def test_ellipsis_middle_truncate_only_ellipsis_fits(self): + self.assertEqual('...', formatting.EllipsisMiddleTruncate( + 'abcdefghij', 3, LINE_LENGTH)) + + def test_ellipsis_middle_truncate_text_fits(self): + for text, width in [('', 3), ('ab', 3), ('abc', 3), ('abcd', 4)]: + with self.subTest(text=text, width=width): + self.assertEqual(text, formatting.EllipsisMiddleTruncate( + text, width, LINE_LENGTH)) + + def test_ellipsis_middle_truncate_retains_ends(self): + for width, expected in [(4, '...j'), (5, 'a...j'), + (6, 'a...ij'), (7, 'ab...ij')]: + with self.subTest(width=width): + self.assertEqual(expected, formatting.EllipsisMiddleTruncate( + 'abcdefghij', width, LINE_LENGTH)) + + def test_ellipsis_middle_truncate_fallback_boundaries(self): + for text, line_length, expected in [('abcdefghij', 3, '...'), + ('abcd', 4, 'abcd')]: + with self.subTest(text=text, line_length=line_length): + self.assertEqual(expected, formatting.EllipsisMiddleTruncate( + text, 2, line_length)) + if __name__ == '__main__': testutils.main()