CodeSampleX

示例

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

已验证示例 — golang go.yaml.in/yaml/v2 v2.4.4: Marshal. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: yaml.Marshal serializes primitive types, structs…

sha256:e060b232d5c642a6ff7c49e93028c235f1ec0f5adeeb667d3d78b7c350689091

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

执行证据

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

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

验证运行环境

环境 契约 阶段 运行日期
go 1.26 · linux debian/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26@sha256:e30143be198a…
2026-09-06

案例

HOW
目标
verify go.yaml.in/yaml/v2.Marshal in pkg:golang/go.yaml.in/yaml/v2@v2.4.4
包
符号
  • go.yaml.in/yaml/v2.Marshal
创建时间
2026-09-06T13:02:29Z

契约

  1. yaml.Marshal serializes primitive types, structs, slices, and maps into standard YAML
  2. yaml.Marshal respects struct field tags for custom key names, omitempty, and ignored fields
  3. yaml.Marshal supports inlining embedded structs using the inline tag
  4. yaml.Marshal applies flow style to collections when flow tag is present
  5. yaml.Marshal invokes MarshalYAML on types implementing the Marshaler interface
  6. yaml.Marshal propagates errors returned by types implementing the 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 go.yaml.in/yaml/v2.Marshal in 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:
  - go.yaml.in/yaml/v2.Marshal

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:ca4122add92a100006b1ba89a9dfdf0b3cb55a2a70bab285ddcbf7026b42a2f2","contract":["yaml.Marshal serializes primitive types, structs, slices, and maps into standard YAML","yaml.Marshal respects struct field tags for custom key names, omitempty, and ignored fields","yaml.Marshal supports inlining embedded structs using the inline tag","yaml.Marshal applies flow style to collections when flow tag is present","yaml.Marshal invokes MarshalYAML on types implementing the Marshaler interface","yaml.Marshal propagates errors returned by types implementing the Marshaler interface"],"goal":"verify go.yaml.in/yaml/v2.Marshal in 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":["go.yaml.in/yaml/v2.Marshal"]},"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":["go.yaml.in/yaml/v2.Marshal"],"verifierAdapter":"golang@1"}
go.mod
module example.com/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 go.yaml.in/yaml/v2.Marshal in pkg:golang/go.yaml.in/yaml/v2@v2.4.4",
  "kind": "HOW",
  "packages": [
    "pkg:golang/go.yaml.in/yaml/v2@v2.4.4"
  ],
  "symbols": [
    "go.yaml.in/yaml/v2.Marshal"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"
	"strings"

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

// 1. Types for testing basic serialization and struct tags
type ServerConfig struct {
	Host       string            `yaml:"host"`
	Port       int               `yaml:"port"`
	Active     bool              `yaml:"active"`
	Labels     []string          `yaml:"labels,omitempty"`
	Settings   map[string]string `yaml:"settings,omitempty"`
	SecretKey  string            `yaml:"-"`
	CustomName string            `yaml:"service_name"`
}

// 2. Types for inline tag testing
type BaseMetadata struct {
	Version string `yaml:"version"`
}

type ServiceDefinition struct {
	Name         string `yaml:"name"`
	BaseMetadata `yaml:",inline"`
}

// 3. Types for flow style testing
type FlowConfig struct {
	Endpoints []string `yaml:"endpoints,flow"`
}

// 4. Types for custom Marshaler interface testing
type StatusValue struct {
	code int
}

func (s StatusValue) MarshalYAML() (interface{}, error) {
	switch s.code {
	case 200:
		return "OK", nil
	case 404:
		return "NOT_FOUND", nil
	default:
		return nil, fmt.Errorf("invalid status code: %d", s.code)
	}
}

type StatusReport struct {
	Status StatusValue `yaml:"status"`
}

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

func runContractTests() error {
	// 1. yaml.Marshal serializes primitive types, structs, slices, and maps into standard YAML
	cfg := ServerConfig{
		Host:       "127.0.0.1",
		Port:       8080,
		Active:     true,
		Labels:     []string{"web", "prod"},
		Settings:   map[string]string{"timeout": "30s", "mode": "fast"},
		SecretKey:  "supersecret",
		CustomName: "api-service",
	}

	out, err := yaml.Marshal(&cfg)
	if err != nil {
		return fmt.Errorf("yaml.Marshal basic failed: %w", err)
	}

	yamlStr := string(out)
	if !strings.Contains(yamlStr, "host: 127.0.0.1") ||
		!strings.Contains(yamlStr, "port: 8080") ||
		!strings.Contains(yamlStr, "active: true") {
		return fmt.Errorf("yaml.Marshal output missing scalar fields: %s", yamlStr)
	}

	// 2. yaml.Marshal respects struct field tags for custom key names, omitempty, and ignored fields
	if !strings.Contains(yamlStr, "service_name: api-service") {
		return fmt.Errorf("custom key tag failed: %s", yamlStr)
	}
	if strings.Contains(yamlStr, "supersecret") || strings.Contains(yamlStr, "SecretKey") {
		return fmt.Errorf("ignored field '-' was included: %s", yamlStr)
	}

	// Verify omitempty
	emptyCfg := ServerConfig{
		Host:       "localhost",
		Port:       9000,
		Active:     false,
		CustomName: "test-service",
	}
	emptyOut, err := yaml.Marshal(&emptyCfg)
	if err != nil {
		return fmt.Errorf("yaml.Marshal empty failed: %w", err)
	}
	emptyStr := string(emptyOut)
	if strings.Contains(emptyStr, "labels:") || strings.Contains(emptyStr, "settings:") {
		return fmt.Errorf("omitempty failed, empty fields present: %s", emptyStr)
	}

	// 3. yaml.Marshal supports inlining embedded structs using the inline tag
	svc := ServiceDefinition{
		Name: "auth",
		BaseMetadata: BaseMetadata{
			Version: "v1.2.3",
		},
	}
	inlineOut, err := yaml.Marshal(&svc)
	if err != nil {
		return fmt.Errorf("yaml.Marshal inline failed: %w", err)
	}
	inlineStr := string(inlineOut)
	if !strings.Contains(inlineStr, "name: auth") || !strings.Contains(inlineStr, "version: v1.2.3") {
		return fmt.Errorf("inline tag failed: %s", inlineStr)
	}
	if strings.Contains(inlineStr, "basemetadata:") {
		return fmt.Errorf("inline field was nested: %s", inlineStr)
	}

	// 4. yaml.Marshal applies flow style to collections when flow tag is present
	flowCfg := FlowConfig{
		Endpoints: []string{"api1", "api2"},
	}
	flowOut, err := yaml.Marshal(&flowCfg)
	if err != nil {
		return fmt.Errorf("yaml.Marshal flow failed: %w", err)
	}
	flowStr := string(flowOut)
	if !strings.Contains(flowStr, "endpoints: [api1, api2]") {
		return fmt.Errorf("flow tag failed: %s", flowStr)
	}

	// 5. yaml.Marshal invokes MarshalYAML on types implementing the Marshaler interface
	rep := StatusReport{
		Status: StatusValue{code: 200},
	}
	repOut, err := yaml.Marshal(&rep)
	if err != nil {
		return fmt.Errorf("yaml.Marshal custom Marshaler failed: %w", err)
	}
	if !strings.Contains(string(repOut), "status: OK") {
		return fmt.Errorf("custom Marshaler failed: %s", string(repOut))
	}

	// 6. yaml.Marshal propagates errors returned by types implementing the Marshaler interface
	repErr := StatusReport{
		Status: StatusValue{code: 500},
	}
	if _, err := yaml.Marshal(&repErr); err == nil {
		return fmt.Errorf("expected error from custom Marshaler, got nil")
	}

	// Verify roundtrip fidelity with a map to ensure valid YAML produced
	var parsed map[string]interface{}
	if err := yaml.Unmarshal(out, &parsed); err != nil {
		return fmt.Errorf("unmarshaling generated YAML failed: %w", err)
	}
	if parsed["service_name"] != "api-service" {
		return fmt.Errorf("roundtrip key check failed: %v", parsed)
	}

	return nil
}

原始种子者

匿名