From a7ba3a27e368718960c9107b6cbe7e4b565ca4fc Mon Sep 17 00:00:00 2001 From: hugosmoreira Date: Sun, 25 Oct 2026 22:05:42 -0700 Subject: [PATCH] Fix middle truncation width boundaries --- fire/formatting.py | 5 +++-- fire/formatting_test.py | 24 ++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/fire/formatting.py b/fire/formatting.py index 68484c279..77665b2e4 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 e0f6699d2..7d3af6f20 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()