CodeSampleX

Ejemplo

github.com/mitchellh/copystructure v1.0.0: CopierFunc

Muestra verificada para golang github.com/mitchellh/copystructure v1.0.0: CopierFunc. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y pasó.

sha256:1bb2f6b9dff9e6316dea2d9438c87ce61b648943ccba3f3c719bbe79d5f291c8

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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-10-12

Caso

HOW
Objetivo
verify github.com/mitchellh/copystructure.CopierFunc in pkg:golang/github.com/mitchellh/copystructure@v1.0.0
Paquetes
Símbolos
  • github.com/mitchellh/copystructure.CopierFunc
Creado
2026-10-12T09:03:35Z

Contrato

  1. copystructure.CopierFunc registered on Copiers executes custom deep copy logic for a specified type
  2. copystructure.CopierFunc is recursively invoked when the registered type is nested within structs, slices, and maps
  3. copystructure.CopierFunc returning an error halts Copy and propagates that exact error back to the caller
  4. Deep copying via copystructure.CopierFunc ensures mutations on the copied value do not affect the original source value

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 github.com/mitchellh/copystructure.CopierFunc in pkg:golang/github.com/mitchellh/copystructure@v1.0.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/mitchellh/copystructure@v1.0.0
Demonstrate these symbols/APIs:
  - github.com/mitchellh/copystructure.CopierFunc

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:bf8c3fcaf3445c3df99d737a7455e6caed6cff449bf55fca28f124f29328a238","contract":["copystructure.CopierFunc registered on Copiers executes custom deep copy logic for a specified type","copystructure.CopierFunc is recursively invoked when the registered type is nested within structs, slices, and maps","copystructure.CopierFunc returning an error halts Copy and propagates that exact error back to the caller","Deep copying via copystructure.CopierFunc ensures mutations on the copied value do not affect the original source value"],"goal":"verify github.com/mitchellh/copystructure.CopierFunc in pkg:golang/github.com/mitchellh/copystructure@v1.0.0","kind":"HOW","packages":["pkg:golang/github.com/mitchellh/copystructure@v1.0.0"],"schemaVersion":1,"symbols":["github.com/mitchellh/copystructure.CopierFunc"]},"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/github.com/mitchellh/copystructure@v1.0.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/mitchellh/copystructure@v1.0.0","symbols":["github.com/mitchellh/copystructure.CopierFunc"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/mitchellh/copystructure v1.0.0

require github.com/mitchellh/reflectwalk v1.0.2 // indirect
go.sum
github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ=
github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw=
github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=
github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=
main.go
package main

import (
	"fmt"
	"reflect"
	"time"

	"github.com/mitchellh/copystructure"
)

// Timestamp wraps time.Time to demonstrate custom CopierFunc behavior.
type Timestamp struct {
	Value time.Time
}

// UserProfile represents a struct containing a custom copied type.
type UserProfile struct {
	Username  string
	CreatedAt Timestamp
	Tags      []string
}

func main() {
	copystructure.Copiers[reflect.TypeOf(Timestamp{})] = copystructure.CopierFunc(func(v interface{}) (interface{}, error) {
		ts, ok := v.(Timestamp)
		if !ok {
			return nil, fmt.Errorf("expected Timestamp, got %T", v)
		}
		return Timestamp{Value: ts.Value}, nil
	})

	profile := UserProfile{
		Username:  "example-user",
		CreatedAt: Timestamp{Value: time.Now()},
		Tags:      []string{"golang", "developer"},
	}

	copied, err := copystructure.Copy(profile)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Original: %+v\n", profile)
	fmt.Printf("Copied:   %+v\n", copied)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/mitchellh/copystructure.CopierFunc in pkg:golang/github.com/mitchellh/copystructure@v1.0.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/mitchellh/copystructure@v1.0.0"
  ],
  "symbols": [
    "github.com/mitchellh/copystructure.CopierFunc"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"
	"reflect"
	"time"

	"github.com/mitchellh/copystructure"
)

// CustomBuffer demonstrates custom cloning logic for reference types.
type CustomBuffer struct {
	Data []byte
}

// CustomTimestamp demonstrates custom type transformation during deep copy.
type CustomTimestamp struct {
	Time time.Time
}

// NestedRecord demonstrates nested structures with custom CopierFunc types.
type NestedRecord struct {
	ID         string
	Timestamp  CustomTimestamp
	History    []CustomTimestamp
	Attributes map[string]CustomTimestamp
	Buffer     *CustomBuffer
}

func main() {
	if err := runContract(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract verification failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All copystructure.CopierFunc contract assertions passed successfully.")
}

func runContract() error {
	// Assertion 1: copystructure.CopierFunc registered on Copiers executes custom deep copy logic for a specified type
	var copier1Calls int
	bufferCopier := copystructure.CopierFunc(func(v interface{}) (interface{}, error) {
		copier1Calls++
		buf, ok := v.(CustomBuffer)
		if !ok {
			return nil, errors.New("expected CustomBuffer")
		}
		newSlice := make([]byte, len(buf.Data))
		copy(newSlice, buf.Data)
		return CustomBuffer{Data: newSlice}, nil
	})

	copystructure.Copiers[reflect.TypeOf(CustomBuffer{})] = bufferCopier

	origBuf := CustomBuffer{Data: []byte("initial-payload")}
	copiedBufAny, err := copystructure.Copy(origBuf)
	if err != nil {
		return fmt.Errorf("Assertion 1 failed: copystructure.Copy returned error: %w", err)
	}
	copiedBuf, ok := copiedBufAny.(CustomBuffer)
	if !ok {
		return fmt.Errorf("Assertion 1 failed: expected CustomBuffer, got %T", copiedBufAny)
	}
	if copier1Calls != 1 {
		return fmt.Errorf("Assertion 1 failed: expected 1 CopierFunc call, got %d", copier1Calls)
	}
	if string(copiedBuf.Data) != "initial-payload" {
		return fmt.Errorf("Assertion 1 failed: expected payload %q, got %q", "initial-payload", string(copiedBuf.Data))
	}

	// Assertion 2: copystructure.CopierFunc is recursively invoked when the registered type is nested within structs, slices, and maps
	var timestampCopierCalls int
	timestampCopier := copystructure.CopierFunc(func(v interface{}) (interface{}, error) {
		timestampCopierCalls++
		ts, ok := v.(CustomTimestamp)
		if !ok {
			return nil, errors.New("expected CustomTimestamp")
		}
		return CustomTimestamp{Time: ts.Time.Add(time.Second)}, nil
	})

	copystructure.Copiers[reflect.TypeOf(CustomTimestamp{})] = timestampCopier

	baseTime := time.Date(2026, 8, 21, 10, 0, 0, 0, time.UTC)
	nested := NestedRecord{
		ID:        "rec-42",
		Timestamp: CustomTimestamp{Time: baseTime},
		History: []CustomTimestamp{
			{Time: baseTime.Add(1 * time.Minute)},
			{Time: baseTime.Add(2 * time.Minute)},
		},
		Attributes: map[string]CustomTimestamp{
			"published": {Time: baseTime.Add(3 * time.Minute)},
		},
		Buffer: &CustomBuffer{Data: []byte("nested-buffer")},
	}

	copiedNestedAny, err := copystructure.Copy(nested)
	if err != nil {
		return fmt.Errorf("Assertion 2 failed: copystructure.Copy returned error: %w", err)
	}
	copiedNested, ok := copiedNestedAny.(NestedRecord)
	if !ok {
		return fmt.Errorf("Assertion 2 failed: expected NestedRecord, got %T", copiedNestedAny)
	}
	// Total CustomTimestamp instances: 1 (field) + 2 (slice) + 1 (map) = 4
	if timestampCopierCalls != 4 {
		return fmt.Errorf("Assertion 2 failed: expected 4 CustomTimestamp copier calls, got %d", timestampCopierCalls)
	}
	if !copiedNested.Timestamp.Time.Equal(baseTime.Add(time.Second)) {
		return fmt.Errorf("Assertion 2 failed: expected nested timestamp %v, got %v", baseTime.Add(time.Second), copiedNested.Timestamp.Time)
	}
	if len(copiedNested.History) != 2 || !copiedNested.History[0].Time.Equal(baseTime.Add(1*time.Minute+time.Second)) {
		return fmt.Errorf("Assertion 2 failed: history slice elements not copied properly")
	}
	if !copiedNested.Attributes["published"].Time.Equal(baseTime.Add(3*time.Minute+time.Second)) {
		return fmt.Errorf("Assertion 2 failed: map attributes not copied properly")
	}

	// Assertion 3: copystructure.CopierFunc returning an error halts Copy and propagates that exact error back to the caller
	targetErr := errors.New("custom copy failed intentionally")
	errCopier := copystructure.CopierFunc(func(v interface{}) (interface{}, error) {
		return nil, targetErr
	})

	copystructure.Copiers[reflect.TypeOf(CustomTimestamp{})] = errCopier

	_, err = copystructure.Copy(nested)
	if err == nil {
		return fmt.Errorf("Assertion 3 failed: expected copy error, got nil")
	}
	if !errors.Is(err, targetErr) {
		return fmt.Errorf("Assertion 3 failed: expected error %v, got %v", targetErr, err)
	}

	// Assertion 4: Deep copying via copystructure.CopierFunc ensures mutations on the copied value do not affect the original source value
	copiedBuf.Data[0] = 'X'
	if origBuf.Data[0] == 'X' {
		return fmt.Errorf("Assertion 4 failed: mutating copied buffer modified original buffer")
	}

	return nil
}

Seeder de origen

anónimo