CodeSampleX

示例

rich 15.0.0: Preserve trailing newlines in Text.from_ansi and respect end delimiter in empty Console.print without silent character truncation or extra newline emission

已验证示例 — pypi rich 15.0.0: Preserve trailing newlines in Text.from_ansi and respect end delimiter in empty Console.print without silent character truncation…

sha256:00d8a99b69f897ed7eef81f1df0723a0b33201915b031f892bad809451296ba5

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
2
声明的环境 python linux x64 python python pip

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-16
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

案例

HOW
目标
Preserve trailing newlines in Text.from_ansi and respect end delimiter in empty Console.print without silent character truncation or extra newline emission
包
符号
  • rich.text.Text.from_ansi
  • rich.console.Console.print
环境
python
创建时间
2026-08-16T06:22:24Z

契约

  1. assert Text.from_ansi('hello\n').plain == 'hello\n' preserving trailing newlines
  2. assert Text.from_ansi('\n').plain == '\n' without stripping bare newline
  3. assert Text.from_ansi('\x1b[32mSUCCESS\x1b[0m\n').plain == 'SUCCESS\n' with styled span
  4. assert Console.print(end='') with empty objects outputs '' instead of hardcoded '\n'
  5. assert Console.print(end='\r') outputs '\r'
  6. assert empty NO_COLOR='' env var does not disable console colors

文件

  • NOTES.md
  • csx.json
  • requirements.txt
  • src/__init__.py
  • src/ansi_formatter.py
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Rich Version Boundary Silent Behavioral Changes

## CSX Search Result
`search_known_solution` answered `NO_SAFE_MATCH` for Rich version boundary traps (returning unrelated results for `packaging.specifiers.SpecifierSet` sample `sha256:2158f71f8f0182e574ebf8c6a651b8c00cc0e084fe82523db391f8d026016a3c` and Dart shelf sample `sha256:2651162215727e626baac2f69d7b7e043707968fea0f9218aa9dda0648549e95`).

## What a Model Would Have Written Instead
A model assumes `Text.from_ansi(payload).plain` retains all trailing newline delimiters identically to the original payload string, and that calling `console.print(end="")` without positional arguments emits zero bytes to the stream just like Python's standard `print(end="")`.

## How the Wrong Version Fails
In Rich < 15.0.0 (e.g. 14.3.4), `Text.from_ansi("output\n").plain` silently drops trailing newlines (evaluating to `"output"` or `""` for `"\n"`), and `console.print(end="")` silently writes a hardcoded `\n` to the stream; in Rich < 14.0.0, setting `NO_COLOR=""` silently strips all terminal color formatting.
csx.json
{"case":{"caseId":"case:sha256:a86e99264baee4e0c137112f39f17fd696387ad058d80a10bcafd4f0339c5273","contract":["assert Text.from_ansi('hello\\n').plain == 'hello\\n' preserving trailing newlines","assert Text.from_ansi('\\n').plain == '\\n' without stripping bare newline","assert Text.from_ansi('\\x1b[32mSUCCESS\\x1b[0m\\n').plain == 'SUCCESS\\n' with styled span","assert Console.print(end='') with empty objects outputs '' instead of hardcoded '\\n'","assert Console.print(end='\\r') outputs '\\r'","assert empty NO_COLOR='' env var does not disable console colors"],"goal":"Preserve trailing newlines in Text.from_ansi and respect end delimiter in empty Console.print without silent character truncation or extra newline emission","kind":"HOW","packages":["pkg:pypi/rich@15.0.0"],"schemaVersion":1,"symbols":["rich.text.Text.from_ansi","rich.console.Console.print"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/rich@15.0.0"],"schemaVersion":1,"symbols":["rich.text.Text.from_ansi","rich.console.Console.print"],"verifierAdapter":"python@1"}
requirements.txt
rich==15.0.0
src/__init__.py
"""Rich ANSI and console formatting module."""
src/ansi_formatter.py
"""Helper routines illustrating Rich ANSI parsing and console stream output."""

from io import StringIO
from typing import Tuple
from rich.console import Console
from rich.text import Text


def parse_ansi_payload(payload: str) -> Tuple[str, int]:
    """Parse ANSI formatted text into plain string and span count.

    Preserves exact trailing and internal newlines in Rich >= 15.0.0.
    """
    text = Text.from_ansi(payload)
    return text.plain, len(text.spans)


def emit_empty_separator(buffer: StringIO, end: str = "") -> str:
    """Emit an empty print call with custom end delimiter to a string buffer.

    Respects the end parameter without emitting hardcoded newlines in Rich >= 15.0.0.
    """
    console = Console(file=buffer, force_terminal=False, color_system=None)
    console.print(end=end)
    return buffer.getvalue()
test/contract.py
import io
import os
import sys

# Ensure project root is in sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from rich.console import Console
from rich.text import Text
from src.ansi_formatter import emit_empty_separator, parse_ansi_payload

# -----------------------------------------------------------------------------
# 1. Text.from_ansi Trailing Newline Preservation Trap (Rich 15.0.0+)
# Naive model expectation: Text.from_ansi converts ANSI escape codes to styled
# spans and leaves plain text verbatim (including single and multiple newlines).
# Prior versions reality (Rich < 15.0.0): Text.from_ansi silently stripped trailing
# newlines (e.g., 'hello\n' -> 'hello', '\n' -> '').
# -----------------------------------------------------------------------------
plain, span_count = parse_ansi_payload("hello\n")
assert plain == "hello\n", f"Expected 'hello\\n', got {plain!r}"

plain_single_nl, _ = parse_ansi_payload("\n")
assert plain_single_nl == "\n", f"Expected '\\n', got {plain_single_nl!r}"

plain_multi_nl, _ = parse_ansi_payload("line1\nline2\n\n")
assert plain_multi_nl == "line1\nline2\n\n", f"Expected 'line1\\nline2\\n\\n', got {plain_multi_nl!r}"

plain_styled, styled_spans = parse_ansi_payload("\x1b[32mSUCCESS\x1b[0m\n")
assert plain_styled == "SUCCESS\n", f"Expected 'SUCCESS\\n', got {plain_styled!r}"
assert styled_spans == 1

# -----------------------------------------------------------------------------
# 2. Console.print Empty Object with Custom 'end' Delimiter Trap (Rich 15.0.0+)
# Naive model expectation: console.print(end="") with no positional arguments
# behaves identically to built-in Python print(end=""), emitting zero characters.
# Prior versions reality (Rich < 15.0.0): console.print(end="") completely ignored
# the 'end' parameter when positional objects were empty and hardcoded a '\n' write.
# -----------------------------------------------------------------------------
buf = io.StringIO()
result = emit_empty_separator(buf, end="")
assert result == "", f"Expected empty output from console.print(end=''), got {result!r}"

buf_cr = io.StringIO()
result_cr = emit_empty_separator(buf_cr, end="\r")
assert result_cr == "\r", f"Expected '\\r' from console.print(end='\\r'), got {result_cr!r}"

# -----------------------------------------------------------------------------
# 3. Environment Variable NO_COLOR='' & FORCE_COLOR='' Empty String Semantics
# Naive model expectation: NO_COLOR="" (empty string) means NO_COLOR is not set
# or disabled, per the no-color.org specification.
# Prior versions reality (Rich < 14.0.0): Rich checked `"NO_COLOR" in os.environ`,
# treating an empty string as active, silently disabling all terminal color output.
# -----------------------------------------------------------------------------
os.environ["NO_COLOR"] = ""
con_no_col = Console(force_terminal=True)
assert con_no_col.no_color is False, "Empty NO_COLOR should not disable color in Rich >= 14"

os.environ["FORCE_COLOR"] = ""
if "NO_COLOR" in os.environ:
    del os.environ["NO_COLOR"]
con_force_col = Console(force_terminal=False)
assert con_force_col.color_system is None, "Empty FORCE_COLOR should not force color system"

print("CONTRACT PASS: rich 15.0.0 newline preservation, empty print end delimiter, and NO_COLOR semantics verified")

原始种子者

csx-seed