CodeSampleX

サンプル

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

検証済みサンプル — golang github.com/mitchellh/copystructure v1.2.0: CopierFunc. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:a0c32604d0a9576604ee9356be07fdeb34d8477bc2df7185007df9e3555ff493

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-21

ケース

HOW
ゴール
verify github.com/mitchellh/copystructure.CopierFunc in pkg:golang/github.com/mitchellh/copystructure@v1.2.0
パッケージ
シンボル
  • github.com/mitchellh/copystructure.CopierFunc
作成日
2026-08-21T00:30:30Z

コントラクト

  1. copystructure.CopierFunc registered on Config.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 Config.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

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • 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 github.com/mitchellh/copystructure.CopierFunc in pkg:golang/github.com/mitchellh/copystructure@v1.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/mitchellh/copystructure@v1.2.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:b0be43803c52d2c63ca5ee172c431f6dd1c42a5a4cd5d50390597ea3a4a1675f","contract":["copystructure.CopierFunc registered on Config.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 Config.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.2.0","kind":"HOW","packages":["pkg:golang/github.com/mitchellh/copystructure@v1.2.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.2.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/mitchellh/copystructure@v1.2.0","symbols":["github.com/mitchellh/copystructure.CopierFunc"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/mitchellh/copystructure v1.2.0

require github.com/mitchellh/reflectwalk v1.0.2 // indirect
go.sum
github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=
github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=
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"
)

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

// UserRecord represents a data structure containing custom types.
type UserRecord struct {
	ID        string
	CreatedAt TimestampWrapper
	Tags      []string
}

func main() {
	// Define a CopierFunc that clones TimestampWrapper
	customCopier := copystructure.CopierFunc(func(v interface{}) (interface{}, error) {
		ts, ok := v.(TimestampWrapper)
		if !ok {
			return nil, fmt.Errorf("unexpected type: %T", v)
		}
		// Return a copy with preserved timestamp
		return TimestampWrapper{Value: ts.Value}, nil
	})

	config := copystructure.Config{
		Copiers: map[reflect.Type]copystructure.CopierFunc{
			reflect.TypeOf(TimestampWrapper{}): customCopier,
		},
	}

	record := UserRecord{
		ID:        "user-100",
		CreatedAt: TimestampWrapper{Value: time.Now()},
		Tags:      []string{"admin", "active"},
	}

	copied, err := config.Copy(record)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Original: %+v\n", record)
	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.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/mitchellh/copystructure@v1.2.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 Config.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")
		}
		// Make a distinct deep copy of underlying slice
		newSlice := make([]byte, len(buf.Data))
		copy(newSlice, buf.Data)
		return CustomBuffer{Data: newSlice}, nil
	})

	cfg1 := copystructure.Config{
		Copiers: map[reflect.Type]copystructure.CopierFunc{
			reflect.TypeOf(CustomBuffer{}): bufferCopier,
		},
	}

	origBuf := CustomBuffer{Data: []byte("initial-payload")}
	copiedBufAny, err := cfg1.Copy(origBuf)
	if err != nil {
		return fmt.Errorf("Assertion 1 failed: cfg1.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
	})

	cfg2 := copystructure.Config{
		Copiers: map[reflect.Type]copystructure.CopierFunc{
			reflect.TypeOf(CustomTimestamp{}): timestampCopier,
			reflect.TypeOf(CustomBuffer{}):    bufferCopier,
		},
	}

	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 := cfg2.Copy(nested)
	if err != nil {
		return fmt.Errorf("Assertion 2 failed: cfg2.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 Config.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
	})

	cfg3 := copystructure.Config{
		Copiers: map[reflect.Type]copystructure.CopierFunc{
			reflect.TypeOf(CustomTimestamp{}): errCopier,
		},
	}

	_, err = cfg3.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
}

オリジンシーダー

匿名