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에서 contract를 실행해 통과했습니다.

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
}

오리진 시더

익명