CodeSampleX

Пример

golang.org/x/tools v0.31.0: txtar.File

Проверенный пример — golang golang.org/x/tools v0.31.0: txtar.File. Контракт выполнен на go 1.26 · linux alpine/x64 · docker и пройден.

sha256:756da2a45ea749a4597c331f50432164ce629543187c01f6b36f6e047391036f

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux 24 · ubuntu · glibc 2.39 x64 go go

Среды запусков проверки

Окружение Контракт Этапы Запуск
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

Кейс

HOW
Цель
verify golang.org/x/tools/txtar.File in pkg:golang/golang.org/x/tools@v0.31.0
Пакеты
Символы
  • golang.org/x/tools/txtar.File
Создан
2026-08-27T14:51:21Z

Контракт

  1. txtar.File encapsulates file name and file data content within a txtar.Archive
  2. txtar.Parse parses archive text into individual txtar.File elements preserving names and contents
  3. txtar.Format serializes Archive containing txtar.File elements into canonical txtar format
  4. txtar.File supports empty file content, multiline content, and binary-safe byte slices
  5. txtar.Parse correctly extracts multiple txtar.File entries and separates them from archive comments
  6. txtar.Format and txtar.Parse roundtrip txtar.File data with full fidelity

Файлы

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/contract.go

Скачать артефакт с исходным кодом (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 golang.org/x/tools/txtar.File in pkg:golang/golang.org/x/tools@v0.31.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/golang.org/x/tools@v0.31.0
Demonstrate these symbols/APIs:
  - golang.org/x/tools/txtar.File

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:1db004365979a8f3e35707cf30290762708547d8f162da06030f56859bbc7f90","contract":["txtar.File encapsulates file name and file data content within a txtar.Archive","txtar.Parse parses archive text into individual txtar.File elements preserving names and contents","txtar.Format serializes Archive containing txtar.File elements into canonical txtar format","txtar.File supports empty file content, multiline content, and binary-safe byte slices","txtar.Parse correctly extracts multiple txtar.File entries and separates them from archive comments","txtar.Format and txtar.Parse roundtrip txtar.File data with full fidelity"],"goal":"verify golang.org/x/tools/txtar.File in pkg:golang/golang.org/x/tools@v0.31.0","kind":"HOW","packages":["pkg:golang/golang.org/x/tools@v0.31.0"],"schemaVersion":1,"symbols":["golang.org/x/tools/txtar.File"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/golang.org/x/tools@v0.31.0"],"schemaVersion":1,"subject":"pkg:golang/golang.org/x/tools@v0.31.0","symbols":["golang.org/x/tools/txtar.File"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.24.0

require golang.org/x/tools v0.31.0
go.sum
golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify golang.org/x/tools/txtar.File in pkg:golang/golang.org/x/tools@v0.31.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/golang.org/x/tools@v0.31.0"
  ],
  "symbols": [
    "golang.org/x/tools/txtar.File"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"

	"golang.org/x/tools/txtar"
)

func main() {
	if err := runTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All contract tests passed successfully.")
}

func runTests() error {
	// 1. txtar.File encapsulates file name and file data content within a txtar.Archive
	f1 := txtar.File{
		Name: "greeting.txt",
		Data: []byte("Hello, CodeSampleX!\n"),
	}
	if f1.Name != "greeting.txt" {
		return fmt.Errorf("expected Name 'greeting.txt', got %q", f1.Name)
	}
	if !bytes.Equal(f1.Data, []byte("Hello, CodeSampleX!\n")) {
		return fmt.Errorf("unexpected Data: %q", string(f1.Data))
	}

	// 2. txtar.Parse parses archive text into individual txtar.File elements preserving names and contents
	rawArchive := []byte("Archive comment header\n-- alpha.txt --\nAlpha content\n-- beta/nested.txt --\nLine 1\nLine 2\n")
	parsed := txtar.Parse(rawArchive)
	if string(parsed.Comment) != "Archive comment header\n" {
		return fmt.Errorf("unexpected parsed comment: %q", string(parsed.Comment))
	}
	if len(parsed.Files) != 2 {
		return fmt.Errorf("expected 2 parsed files, got %d", len(parsed.Files))
	}
	if parsed.Files[0].Name != "alpha.txt" || string(parsed.Files[0].Data) != "Alpha content\n" {
		return fmt.Errorf("unexpected file 0: %+v", parsed.Files[0])
	}
	if parsed.Files[1].Name != "beta/nested.txt" || string(parsed.Files[1].Data) != "Line 1\nLine 2\n" {
		return fmt.Errorf("unexpected file 1: %+v", parsed.Files[1])
	}

	// 3. txtar.Format serializes Archive containing txtar.File elements into canonical txtar format
	archToFormat := &txtar.Archive{
		Comment: []byte("Generated archive\n"),
		Files: []txtar.File{
			{Name: "config.json", Data: []byte("{\"enabled\": true}\n")},
			{Name: "empty.txt", Data: []byte{}},
		},
	}
	formatted := txtar.Format(archToFormat)
	expectedFormat := "Generated archive\n-- config.json --\n{\"enabled\": true}\n-- empty.txt --\n"
	if string(formatted) != expectedFormat {
		return fmt.Errorf("unexpected formatted output:\nGot:\n%s\nExpected:\n%s", string(formatted), expectedFormat)
	}

	// 4. txtar.File supports empty file content, multiline content, and binary-safe byte slices
	binFile := txtar.File{
		Name: "binary.dat",
		Data: []byte{0x00, 0x01, 0x02, 0xFF, 0x0A},
	}
	archBin := &txtar.Archive{
		Files: []txtar.File{binFile},
	}
	formattedBin := txtar.Format(archBin)
	parsedBin := txtar.Parse(formattedBin)
	if len(parsedBin.Files) != 1 {
		return fmt.Errorf("expected 1 file in binary roundtrip, got %d", len(parsedBin.Files))
	}
	if parsedBin.Files[0].Name != "binary.dat" {
		return fmt.Errorf("expected binary.dat, got %q", parsedBin.Files[0].Name)
	}
	if !bytes.Equal(parsedBin.Files[0].Data, binFile.Data) {
		return fmt.Errorf("binary data mismatch: got %v, expected %v", parsedBin.Files[0].Data, binFile.Data)
	}

	// 5. txtar.Parse correctly extracts multiple txtar.File entries and separates them from archive comments
	multiRaw := []byte("Multi-file test\n-- f1 --\n1\n-- f2 --\n2\n-- f3 --\n3\n")
	parsedMulti := txtar.Parse(multiRaw)
	if len(parsedMulti.Files) != 3 {
		return fmt.Errorf("expected 3 files, got %d", len(parsedMulti.Files))
	}
	for i, expectedName := range []string{"f1", "f2", "f3"} {
		if parsedMulti.Files[i].Name != expectedName {
			return fmt.Errorf("file %d name mismatch: %q != %q", i, parsedMulti.Files[i].Name, expectedName)
		}
	}

	// 6. txtar.Format and txtar.Parse roundtrip txtar.File data with full fidelity
	origFiles := []txtar.File{
		{Name: "docs/readme.md", Data: []byte("# Title\n\nSome body\n")},
		{Name: "src/main.go", Data: []byte("package main\n\nfunc main() {}\n")},
	}
	origArchive := &txtar.Archive{
		Comment: []byte("Roundtrip verification\n"),
		Files:   origFiles,
	}
	rtData := txtar.Format(origArchive)
	rtParsed := txtar.Parse(rtData)
	if len(rtParsed.Files) != len(origFiles) {
		return fmt.Errorf("roundtrip file count mismatch: %d != %d", len(rtParsed.Files), len(origFiles))
	}
	for i := range origFiles {
		if rtParsed.Files[i].Name != origFiles[i].Name {
			return fmt.Errorf("roundtrip file %d name mismatch: %q != %q", i, rtParsed.Files[i].Name, origFiles[i].Name)
		}
		if !bytes.Equal(rtParsed.Files[i].Data, origFiles[i].Data) {
			return fmt.Errorf("roundtrip file %d data mismatch: got %q, expected %q", i, string(rtParsed.Files[i].Data), string(origFiles[i].Data))
		}
	}

	return nil
}

Исходный сидер

аноним