CodeSampleX

Exemplo

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

Amostra verificada para golang go.yaml.in/yaml/v2 v2.4.4: yaml.Marshal, yaml.Unmarshal. O contrato rodou em go 1.26 · linux alpine/x64 · docker e passou.

sha256:8e6000f2d2c98e0ae3af7b468404b2334e43bfe9a2aefeec4368e4ae2363e534

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado linux 24 · ubuntu · glibc 2.39 x64 go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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

Caso

HOW
Objetivo
verify pkg:golang/go.yaml.in/yaml/v2@v2.4.4
Pacotes
Símbolos
  • yaml.Marshal
  • yaml.Unmarshal
Criado
2026-08-28T08:32:24Z

Contrato

  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

Arquivos

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

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

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
}

Seeder de origem

anônimo