Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion slugify/slugify.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,18 @@ def _modern_truncate(text: str, max_length: int, word_boundary: bool, separator:
# A hard cut may shorten a word but must not emit a partial/trailing delimiter.
parts: list[str] = []
length = 0
previous_index = 0
for index, word in enumerate(tokens):
delimiter = separator if index else ''
if not word:
continue
# Keep repeated delimiters with the next nonempty word until it fits.
delimiter = separator * (index - previous_index)
remaining = max_length - length - len(delimiter)
if remaining <= 0:
break
parts.append(delimiter + word[:remaining])
length += len(delimiter) + min(len(word), remaining)
previous_index = index
if len(word) > remaining:
break
return ''.join(parts)
Expand Down
26 changes: 26 additions & 0 deletions tests/test_release.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,32 @@ def test_modern_fitting_post_replacements_preserve_delimiters(self):
separator=separator, max_length=limit,
word_boundary=boundary, save_order=order), expected)

def test_modern_hard_cut_does_not_end_in_post_replacement_delimiters(self):
cases = (
('one--two', '-', 4, 'one'),
('one--two', '-', 5, 'one'),
('one--two', '-', 6, 'one--t'),
('one--two', '::', 6, 'one'),
('one--two', '::', 7, 'one'),
('one--two', '::', 8, 'one::::t'),
('--one', '-', 2, ''),
('--one', '-', 3, '--o'),
('---', '-', 2, ''),
('x--two', 'x', 3, 'x'),
('one--two', '', 4, 'onet'),
)
for replacement, separator, limit, expected in cases:
with self.subTest(replacement=replacement, separator=separator, limit=limit):
self.assertEqual(slugify('value', replacements=[('value', replacement)],
replacement_stage='post', allow_unicode=True,
separator=separator, max_length=limit), expected)

def test_modern_word_boundary_hard_cut_keeps_delimiters_with_the_next_word(self):
for order in (False, True):
self.assertEqual(slugify('value', replacements=[('value', '--longword')],
replacement_stage='post', allow_unicode=True,
max_length=2, word_boundary=True, save_order=order), '')

def test_cli_preserves_legacy_default_shape(self):
expected = dict(text='', entities=True, decimal=True, hexadecimal=True,
max_length=0, word_boundary=False, save_order=False, separator='-',
Expand Down