CodeSampleX

Exemple

gopkg.in/yaml.v2 v2.3.0: yaml.Marshal, yaml.Unmarshal

Échantillon vérifié pour golang gopkg.in/yaml.v2 v2.3.0: yaml.Marshal, yaml.Unmarshal. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a…

sha256:259b877416b5d598b0afa479b64472726810a6a340f073703ef01dbfccff456d

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux 24 · ubuntu · glibc 2.39 x64 go

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-04

Cas

HOW
Objectif
verify pkg:golang/gopkg.in/yaml.v2@v2.3.0
Paquets
Symboles
  • yaml.Marshal
  • yaml.Unmarshal
Créé
2026-09-04T19:15:52Z

Contrat

  1. yaml.Unmarshal unmarshals valid YAML bytes into a struct with yaml struct tags
  2. yaml.Marshal serializes a Go struct into valid YAML bytes
  3. yaml.Unmarshal unmarshals nested maps and slices into typed struct fields
  4. yaml.Unmarshal returns an error when parsing malformed YAML syntax
  5. yaml.Marshal respects omitempty tag by omitting zero-value fields

Fichiers

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

Télécharger l’artefact source (tar.gz)

Code source

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/gopkg.in/yaml.v2@v2.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/gopkg.in/yaml.v2@v2.3.0

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:ff3fab15bf28fbcaea4b745b561eada3a9b34bf18cae910d3101565b96a92a6a","contract":["yaml.Unmarshal unmarshals valid YAML bytes into a struct with yaml struct tags","yaml.Marshal serializes a Go struct into valid YAML bytes","yaml.Unmarshal unmarshals nested maps and slices into typed struct fields","yaml.Unmarshal returns an error when parsing malformed YAML syntax","yaml.Marshal respects omitempty tag by omitting zero-value fields"],"goal":"verify pkg:golang/gopkg.in/yaml.v2@v2.3.0","kind":"HOW","packages":["pkg:golang/gopkg.in/yaml.v2@v2.3.0"],"schemaVersion":1,"symbols":["yaml.Marshal","yaml.Unmarshal"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/gopkg.in/yaml.v2@v2.3.0"],"schemaVersion":1,"subject":"pkg:golang/gopkg.in/yaml.v2@v2.3.0","symbols":["yaml.Marshal","yaml.Unmarshal"],"verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22.0

require gopkg.in/yaml.v2 v2.3.0
go.sum
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
main.go
package main

import (
	"fmt"
	"os"

	"gopkg.in/yaml.v2"
)

// Config represents a sample application configuration.
type Config struct {
	Name    string            `yaml:"name"`
	Port    int               `yaml:"port"`
	Debug   bool              `yaml:"debug,omitempty"`
	Tags    []string          `yaml:"tags,omitempty"`
	Options map[string]string `yaml:"options,omitempty"`
}

// ParseConfig unmarshals YAML data into a Config struct.
func ParseConfig(data []byte) (*Config, error) {
	var cfg Config
	if err := yaml.Unmarshal(data, &cfg); err != nil {
		return nil, fmt.Errorf("failed to unmarshal yaml: %w", err)
	}
	return &cfg, nil
}

// SerializeConfig marshals a Config struct into YAML bytes.
func SerializeConfig(cfg *Config) ([]byte, error) {
	data, err := yaml.Marshal(cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal yaml: %w", err)
	}
	return data, nil
}

func main() {
	sampleYAML := `
name: sample-app
port: 8080
debug: true
tags:
  - web
  - api
options:
  env: production
`
	cfg, err := ParseConfig([]byte(sampleYAML))
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("Loaded config: name=%s, port=%d, debug=%t\n", cfg.Name, cfg.Port, cfg.Debug)

	out, err := SerializeConfig(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("Marshaled YAML:")
	fmt.Println(string(out))
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/gopkg.in/yaml.v2@v2.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/gopkg.in/yaml.v2@v2.3.0"
  ],
  "symbols": [
    "yaml.Marshal",
    "yaml.Unmarshal"
  ]
}
test/contract.go
package main

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

	"gopkg.in/yaml.v2"
)

type ServerConfig struct {
	Host    string            `yaml:"host"`
	Port    int               `yaml:"port"`
	Enabled bool              `yaml:"enabled"`
	Secret  string            `yaml:"secret,omitempty"`
	Routes  []string          `yaml:"routes,omitempty"`
	Meta    map[string]string `yaml:"meta,omitempty"`
}

func main() {
	// Assertion 1: yaml.Unmarshal unmarshals valid YAML bytes into a struct with yaml struct tags
	yamlInput := []byte("host: localhost\nport: 9000\nenabled: true\n")
	var srv ServerConfig
	if err := yaml.Unmarshal(yamlInput, &srv); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Unmarshal failed: %v\n", err)
		os.Exit(1)
	}
	if srv.Host != "localhost" || srv.Port != 9000 || !srv.Enabled {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Unmarshal struct fields mismatch: %+v\n", srv)
		os.Exit(1)
	}

	// Assertion 2: yaml.Marshal serializes a Go struct into valid YAML bytes
	srvToMarshal := ServerConfig{
		Host:    "example.com",
		Port:    8080,
		Enabled: true,
	}
	marshaledBytes, err := yaml.Marshal(&srvToMarshal)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Marshal failed: %v\n", err)
		os.Exit(1)
	}
	if !strings.Contains(string(marshaledBytes), "host: example.com") || !strings.Contains(string(marshaledBytes), "port: 8080") {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Marshal output missing expected content:\n%s\n", string(marshaledBytes))
		os.Exit(1)
	}

	// Assertion 3: yaml.Unmarshal unmarshals nested maps and slices into typed struct fields
	nestedYAML := []byte("host: 127.0.0.1\nport: 3000\nenabled: false\nroutes:\n  - /api/v1\n  - /health\nmeta:\n  tier: backend\n  region: us-east\n")
	var nestedSrv ServerConfig
	if err := yaml.Unmarshal(nestedYAML, &nestedSrv); err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Unmarshal nested YAML failed: %v\n", err)
		os.Exit(1)
	}
	expectedRoutes := []string{"/api/v1", "/health"}
	if !reflect.DeepEqual(nestedSrv.Routes, expectedRoutes) {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Unmarshal routes mismatch: got %v, want %v\n", nestedSrv.Routes, expectedRoutes)
		os.Exit(1)
	}
	if nestedSrv.Meta["tier"] != "backend" || nestedSrv.Meta["region"] != "us-east" {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Unmarshal meta mismatch: got %v\n", nestedSrv.Meta)
		os.Exit(1)
	}

	// Assertion 4: yaml.Unmarshal returns an error when parsing malformed YAML syntax
	malformedYAML := []byte("host: [unclosed list\n  port: 8080\n")
	var malformedSrv ServerConfig
	if err := yaml.Unmarshal(malformedYAML, &malformedSrv); err == nil {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Unmarshal expected error for malformed YAML, got nil\n")
		os.Exit(1)
	}

	// Assertion 5: yaml.Marshal respects omitempty tag by omitting zero-value fields
	emptySecretSrv := ServerConfig{
		Host:    "app.local",
		Port:    443,
		Enabled: true,
		Secret:  "",
	}
	outWithOmit, err := yaml.Marshal(&emptySecretSrv)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Marshal with omitempty failed: %v\n", err)
		os.Exit(1)
	}
	if strings.Contains(string(outWithOmit), "secret:") {
		fmt.Fprintf(os.Stderr, "FAIL: yaml.Marshal did not omit empty field secret:\n%s\n", string(outWithOmit))
		os.Exit(1)
	}

	fmt.Println("PASS: pkg:golang/gopkg.in/yaml.v2@v2.3.0 contract passed")
}

Seeder d'origine

anonyme