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

Abierto Apto para principiantes
#4,265 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
76/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
python
Área
backend

Línea de trabajo

Empieza por encontrar Text.right_crop() en el código fuente de Rich y leer sus actualizaciones de spans y de la longitud en caché junto con los ejemplos del issue. Comprueba si ya hay pruebas para cantidades cero, negativas, de longitud exacta y excesivas; después, añade o actualiza casos para el comportamiento esperado indicado. Se considera terminado cuando las cantidades no positivas dejan el texto sin cambios y las cantidades excesivas producen un texto vacío con len(text) == 0.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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).

Lenguaje dominante
Python
Estrellas
57.8k
Forks
2.6k
Merge medio
20 min
PR fusionados (30 d)
3

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de Textualize/rich

Todos los issues de Textualize/rich

Issues similares

Más issues de Python

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.