CodeSampleX

Пример

go.yaml.in/yaml/v2 v2.4.4: yaml.Marshal, yaml.Unmarshal

Проверенный пример — golang go.yaml.in/yaml/v2 v2.4.4: yaml.Marshal, yaml.Unmarshal. Контракт выполнен на go 1.26 · linux alpine/x64 · docker и пройден.

sha256:8e6000f2d2c98e0ae3af7b468404b2334e43bfe9a2aefeec4368e4ae2363e534

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

Кейс

HOW
Цель
verify pkg:golang/go.yaml.in/yaml/v2@v2.4.4
Пакеты
Символы
  • yaml.Marshal
  • yaml.Unmarshal
Создан
2026-08-28T08:32:24Z

Контракт

  1. yaml.Unmarshal decodes valid YAML scalar, list, and map structures into matching Go struct fields
  2. yaml.Marshal serializes Go structs into valid YAML with correct field names, types, and struct tags
  3. yaml.Unmarshal handles omitempty struct tags by excluding empty slices and maps during Marshal
  4. yaml.UnmarshalStrict returns a TypeError when encountering unknown fields or duplicate keys
  5. yaml.Unmarshal correctly decodes into custom Unmarshaler implementations
  6. yaml.Marshal correctly encodes types implementing the custom Marshaler interface

Файлы

  • 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 pkg:golang/go.yaml.in/yaml/v2@v2.4.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/go.yaml.in/yaml/v2@v2.4.4
Demonstrate these symbols/APIs:
  - yaml.Marshal
  - yaml.Unmarshal

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:686678dc1dd1a28cecab2eb08d4a2dc76fc71ce565f14aecaef3a4c42c9432fd","contract":["yaml.Unmarshal decodes valid YAML scalar, list, and map structures into matching Go struct fields","yaml.Marshal serializes Go structs into valid YAML with correct field names, types, and struct tags","yaml.Unmarshal handles omitempty struct tags by excluding empty slices and maps during Marshal","yaml.UnmarshalStrict returns a TypeError when encountering unknown fields or duplicate keys","yaml.Unmarshal correctly decodes into custom Unmarshaler implementations","yaml.Marshal correctly encodes types implementing the custom Marshaler interface"],"goal":"verify pkg:golang/go.yaml.in/yaml/v2@v2.4.4","kind":"HOW","packages":["pkg:golang/go.yaml.in/yaml/v2@v2.4.4"],"schemaVersion":1,"symbols":["yaml.Marshal","yaml.Unmarshal"]},"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/go.yaml.in/yaml/v2@v2.4.4"],"schemaVersion":1,"subject":"pkg:golang/go.yaml.in/yaml/v2@v2.4.4","symbols":["yaml.Marshal","yaml.Unmarshal"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require go.yaml.in/yaml/v2 v2.4.4
go.sum
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/go.yaml.in/yaml/v2@v2.4.4",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.yaml.in/yaml/v2@v2.4.4"
  ],
  "symbols": [
    "yaml.Marshal",
    "yaml.Unmarshal"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"reflect"
	"strings"

	"go.yaml.in/yaml/v2"
)

type Config struct {
	Name    string            `yaml:"name"`
	Port    int               `yaml:"port"`
	Enabled bool              `yaml:"enabled"`
	Tags    []string          `yaml:"tags,omitempty"`
	Meta    map[string]string `yaml:"meta,omitempty"`
}

type CustomTime struct {
	Value string
}

func (c *CustomTime) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var s string
	if err := unmarshal(&s); err != nil {
		return err
	}
	c.Value = strings.ToUpper(s)
	return nil
}

func (c CustomTime) MarshalYAML() (interface{}, error) {
	return strings.ToLower(c.Value), nil
}

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. yaml.Unmarshal decodes valid YAML scalar, list, and map structures into matching Go struct fields
	yamlData := []byte(`
name: sample-app
port: 8080
enabled: true
tags:
  - web
  - production
meta:
  env: test
  region: us-east-1
`)
	var cfg Config
	if err := yaml.Unmarshal(yamlData, &cfg); err != nil {
		return fmt.Errorf("Unmarshal failed: %w", err)
	}
	if cfg.Name != "sample-app" || cfg.Port != 8080 || !cfg.Enabled {
		return fmt.Errorf("unexpected unmarshaled scalar values: %+v", cfg)
	}
	if !reflect.DeepEqual(cfg.Tags, []string{"web", "production"}) {
		return fmt.Errorf("unexpected tags: %+v", cfg.Tags)
	}
	if cfg.Meta["env"] != "test" || cfg.Meta["region"] != "us-east-1" {
		return fmt.Errorf("unexpected meta map: %+v", cfg.Meta)
	}

	// 2. yaml.Marshal serializes Go structs into valid YAML with correct field names, types, and struct tags
	out, err := yaml.Marshal(&cfg)
	if err != nil {
		return fmt.Errorf("Marshal failed: %w", err)
	}
	var roundtrip Config
	if err := yaml.Unmarshal(out, &roundtrip); err != nil {
		return fmt.Errorf("roundtrip unmarshal failed: %w", err)
	}
	if !reflect.DeepEqual(cfg, roundtrip) {
		return fmt.Errorf("roundtrip mismatch: original %+v != roundtrip %+v", cfg, roundtrip)
	}

	// 3. yaml.Unmarshal handles omitempty struct tags by excluding empty slices and maps during Marshal
	emptyCfg := Config{Name: "minimal", Port: 9000, Enabled: false}
	emptyOut, err := yaml.Marshal(&emptyCfg)
	if err != nil {
		return fmt.Errorf("Marshal emptyCfg failed: %w", err)
	}
	yamlStr := string(emptyOut)
	if strings.Contains(yamlStr, "tags:") || strings.Contains(yamlStr, "meta:") {
		return fmt.Errorf("omitempty fields were not omitted: %s", yamlStr)
	}

	// 4. yaml.UnmarshalStrict returns a TypeError when encountering unknown fields or duplicate keys
	strictData := []byte(`
name: strict-test
port: 3000
unknown_field: true
`)
	var strictCfg Config
	errStrict := yaml.UnmarshalStrict(strictData, &strictCfg)
	if errStrict == nil {
		return fmt.Errorf("expected TypeError on unknown field in UnmarshalStrict, got nil")
	}
	if _, ok := errStrict.(*yaml.TypeError); !ok {
		return fmt.Errorf("expected *yaml.TypeError, got %T: %v", errStrict, errStrict)
	}

	// 5. yaml.Unmarshal correctly decodes into custom Unmarshaler implementations
	type Wrapper struct {
		Timestamp CustomTime `yaml:"timestamp"`
	}
	var w Wrapper
	if err := yaml.Unmarshal([]byte("timestamp: custom-time-value"), &w); err != nil {
		return fmt.Errorf("Unmarshal custom Unmarshaler failed: %w", err)
	}
	if w.Timestamp.Value != "CUSTOM-TIME-VALUE" {
		return fmt.Errorf("custom Unmarshaler did not transform value, got: %q", w.Timestamp.Value)
	}

	// 6. yaml.Marshal correctly encodes types implementing the custom Marshaler interface
	customOut, err := yaml.Marshal(&w)
	if err != nil {
		return fmt.Errorf("Marshal custom Marshaler failed: %w", err)
	}
	if !strings.Contains(string(customOut), "timestamp: custom-time-value") {
		return fmt.Errorf("custom Marshaler output mismatch: %s", string(customOut))
	}

	return nil
}

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

аноним