CodeSampleX

示例

ruff 0.16.1

已验证示例 — pypi ruff 0.16.1. contract 在 python 3.12 · linux alpine/x64 · docker 上运行并通过: assert ruff.find_ruff_bin returns the path to an existing executable…

sha256:b9bf3ed364cbd2130b9c1c53d2ca6d9afaeba851721c11583364a055d10a0a22

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

执行证据

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

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 python 3.12 linux 24 · ubuntu · glibc 2.39 x64 python 3.12 python pip

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-27

案例

HOW
目标
verify pkg:pypi/ruff@0.16.1
包
环境
python 3.12
创建时间
2026-08-27T18:04:54Z

契约

  1. assert ruff.find_ruff_bin returns the path to an existing executable ruff binary
  2. assert ruff binary lints python code and detects unused imports via json output
  3. assert ruff binary fixes autofixable violations via standard input
  4. assert ruff binary inspects rule metadata via rule command

文件

  • PROMPT.md
  • csx.json
  • pyproject.toml
  • requirements.txt
  • sample.py
  • spec.json
  • test/contract.py

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

源代码

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify pkg:pypi/ruff@0.16.1
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/ruff@0.16.1
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:d2894125a3679b32b3b56d9c8b315dd8a4cf7975b23de5ce2e6de7a548969f12","contract":["assert ruff.find_ruff_bin returns the path to an existing executable ruff binary","assert ruff binary lints python code and detects unused imports via json output","assert ruff binary fixes autofixable violations via standard input","assert ruff binary inspects rule metadata via rule command"],"goal":"verify pkg:pypi/ruff@0.16.1","kind":"HOW","packages":["pkg:pypi/ruff@0.16.1"],"schemaVersion":1},"contractCommand":["python3","test/contract.py"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"pypi","executionContext":"python","language":"python","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/ruff@0.16.1"],"schemaVersion":1,"subject":"pkg:pypi/ruff@0.16.1","verifierAdapter":"python@1"}
pyproject.toml
[project]
name = "verify-ruff"
version = "0.1.0"
dependencies = [
    "ruff==0.16.1",
]
requirements.txt
ruff==0.16.1
sample.py
"""Sample demonstrating linting, autofixing, and rule inspection with ruff."""

import json
import os
import subprocess
from typing import Any, Dict, List
import ruff


def get_ruff_binary_path() -> str:
    """Return path to executable ruff binary."""
    bin_path = ruff.find_ruff_bin()
    if not os.path.exists(bin_path):
        raise FileNotFoundError(f"ruff binary not found at {bin_path}")
    return bin_path


def lint_code_json(source: str) -> List[Dict[str, Any]]:
    """Run ruff linter check on Python code via stdin and return diagnostic objects."""
    bin_path = get_ruff_binary_path()
    result = subprocess.run(
        [bin_path, "check", "--output-format=json", "--stdin-filename", "example.py", "-"],
        input=source,
        capture_output=True,
        text=True,
    )
    return json.loads(result.stdout) if result.stdout.strip() else []


def fix_code_stdin(source: str, select_rule: str = "F401") -> str:
    """Run ruff fix on Python source code via stdin for specified rules."""
    bin_path = get_ruff_binary_path()
    result = subprocess.run(
        [bin_path, "check", f"--select={select_rule}", "--fix", "--stdin-filename", "example.py", "-"],
        input=source,
        capture_output=True,
        text=True,
        check=True,
    )
    return result.stdout


def inspect_rule(rule_code: str) -> Dict[str, Any]:
    """Retrieve rule documentation metadata using ruff rule command."""
    bin_path = get_ruff_binary_path()
    result = subprocess.run(
        [bin_path, "rule", rule_code, "--output-format=json"],
        capture_output=True,
        text=True,
        check=True,
    )
    return json.loads(result.stdout)


def main() -> None:
    bin_path = get_ruff_binary_path()
    print(f"Ruff binary: {bin_path}")

    unclean_code = "import os\nimport sys\n\nx = 1\n"
    diagnostics = lint_code_json(unclean_code)
    print(f"Detected {len(diagnostics)} diagnostics:")
    for d in diagnostics:
        print(f"  - [{d.get('code')}] {d.get('message')}")

    fixed = fix_code_stdin(unclean_code, select_rule="F401")
    print("Fixed code:")
    print(fixed)

    rule_info = inspect_rule("F401")
    print(f"Rule F401 name: {rule_info.get('name')}")


if __name__ == "__main__":
    main()
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:pypi/ruff@0.16.1",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/ruff@0.16.1"
  ],
  "constraints": {
    "executionContext": "python"
  },
  "runtimeConditions": {
    "ecosystem": "pypi",
    "language": "python",
    "runtime": "python@3.12"
  }
}
test/contract.py
"""Contract verification test for pkg:pypi/ruff@0.16.1."""

import json
import os
import subprocess
import sys

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

import ruff
from sample import fix_code_stdin, get_ruff_binary_path, inspect_rule, lint_code_json


def test_find_ruff_bin() -> None:
    # Assertion 1: assert ruff.find_ruff_bin returns the path to an existing executable ruff binary
    bin_path = ruff.find_ruff_bin()
    assert isinstance(bin_path, str), f"Expected str, got {type(bin_path)}"
    assert os.path.isfile(bin_path), f"ruff binary does not exist at {bin_path}"
    assert os.access(bin_path, os.X_OK), f"ruff binary is not executable at {bin_path}"

    helper_path = get_ruff_binary_path()
    assert helper_path == bin_path


def test_lint_code_json() -> None:
    # Assertion 2: assert ruff binary lints python code and detects unused imports via json output
    source_with_issues = "import os\nimport sys\n\nx = 1\n"
    diagnostics = lint_code_json(source_with_issues)
    assert len(diagnostics) == 2, f"Expected 2 diagnostics, got {len(diagnostics)}"
    codes = [d["code"] for d in diagnostics]
    assert "F401" in codes, f"Expected F401 in diagnostics: {codes}"


def test_fix_code_stdin() -> None:
    # Assertion 3: assert ruff binary fixes autofixable violations via standard input
    source_with_unused = "import os\nimport sys\n\nx = 1\n"
    fixed = fix_code_stdin(source_with_unused, select_rule="F401")
    assert "x = 1" in fixed, f"Expected 'x = 1' in fixed code: {fixed!r}"
    assert "import os" not in fixed, f"'import os' was not removed: {fixed!r}"
    assert "import sys" not in fixed, f"'import sys' was not removed: {fixed!r}"


def test_inspect_rule() -> None:
    # Assertion 4: assert ruff binary inspects rule metadata via rule command
    rule_data = inspect_rule("F401")
    assert rule_data.get("code") == "F401", f"Expected code F401, got {rule_data.get('code')}"
    assert rule_data.get("name") == "unused-import", f"Expected name unused-import, got {rule_data.get('name')}"


def main() -> int:
    test_find_ruff_bin()
    test_lint_code_json()
    test_fix_code_stdin()
    test_inspect_rule()
    print("All ruff contract assertions passed successfully.")
    return 0


if __name__ == "__main__":
    sys.exit(main())

原始种子者

匿名