File size: 2,298 Bytes
61bb557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
"""Extracted verbatim from python-slugify (github.com/un33k/python-slugify).



This is the `_modern_truncate` helper from slugify/slugify.py, isolated so the

trailing-delimiter bug can be reproduced without the full package. The function

body is copied exactly from the named commit; only the module docstring and the

DEFAULT_SEPARATOR constant were added for standalone use.

"""
DEFAULT_SEPARATOR = '-'


# Provenance: commit 8f9a550 (the fix)
def truncate(text: str, max_length: int, word_boundary: bool, separator: str, save_order: bool) -> str:
    """Budget internal dash-separated tokens before mapping output delimiters.



    Output delimiters may also occur in words; never strip or split emitted text.

    Post replacements retain the historical global dash-to-separator mapping.

    """
    if max_length <= 0:
        return text.replace(DEFAULT_SEPARATOR, separator)
    output_length = len(text) + text.count(DEFAULT_SEPARATOR) * (len(separator) - 1)
    if output_length <= max_length:
        return text.replace(DEFAULT_SEPARATOR, separator)
    tokens = text.split(DEFAULT_SEPARATOR)
    if word_boundary:
        words: list[str] = []
        length = 0
        for word in tokens:
            if not word:
                continue
            next_length = length + len(word) + (len(separator) if words else 0)
            if next_length <= max_length:
                words.append(word)
                length = next_length
            elif save_order:
                break
        if words:
            return separator.join(words)
    # 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):
        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)