[BUG] `Text.right_crop(0)` empties the text and an amount larger than the text makes `len()` raise

Aperta Adatta ai principianti
#4,265 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
76/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Inizia trovando Text.right_crop() nel codice sorgente di Rich e leggendo i suoi aggiornamenti degli span e della lunghezza memorizzata nella cache insieme agli esempi dell’issue. Verifica se esistono già test per quantità pari a zero, negative, esattamente pari alla lunghezza e superiori alla lunghezza; poi aggiungi o aggiorna i casi per il comportamento atteso indicato. Il lavoro è completato quando le quantità non positive lasciano il testo invariato e quelle superiori alla lunghezza producono un testo vuoto con len(text) == 0.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Rich main (3a109cc), Python 3.13.

Text.right_crop() is documented as "Remove a number of characters from the end of the text", but amounts outside 1..len(text) leave the Text object inconsistent:

from rich.text import Text

def probe(amount):
    text = Text("abc")
    try:
        text.right_crop(amount)
        return repr(text.plain), len(text)
    except Exception as error:
        return type(error).__name__ + ": " + str(error)

for amount in (1, 0, -1, 3, 10):
    print(amount, probe(amount))
1  ('ab', 2)
0  ('', 3)
-1 ('a', 4)
3  ('', 0)
10 ValueError: __len__() should return >= 0

Two separate problems:

  1. amount == 0 wipes the text. max_offset = len(self.plain) - 0 keeps every span, but self._text = [self.plain[:-amount]] is self.plain[:0] == "", so the text becomes empty while _length stays at 3 and the spans still cover 0..3. Any code that crops by a computed amount can therefore lose the line instead of leaving it alone.
  2. amount > len(text) makes _length negative (3 - 10), so the next len(text) raises ValueError: __len__() should return >= 0.

(The negative-amount case, where right_crop(-1) leaves len(text) == 4, is #4256; the same clamp covers it.)

Expected: a non-positive amount is a no-op, and an amount larger than the text removes the whole text (plain == "", len(text) == 0), so the cached length and spans stay consistent.

Pull requests to this repository are restricted to collaborators, so I can't send the change directly. The fix is small:

def right_crop(self, amount: int = 1) -> None:
    """Remove a number of characters from the end of the text."""
    if amount <= 0:
        return
    amount = min(amount, len(self.plain))
    max_offset = len(self.plain) - amount
    ...

With that, the table above becomes 1 ('ab', 2), 0 ('abc', 3), -1 ('abc', 3), 3 ('', 0), 10 ('', 0).

Lingua principale
Python
Stelle
57.8k
Fork
2.6k
Merge medio
20m
PR unite (30g)
3

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di Textualize/rich

Tutte le issue di Textualize/rich

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.