CodeSampleX

示例

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

已验证示例 — golang github.com/mitchellh/copystructure v1.2.0: CopierFunc. contract 在 go 1.26 · linux alpine/x64 · docker 上运行并通过: copystructure.CopierFunc…

sha256:a0c32604d0a9576604ee9356be07fdeb34d8477bc2df7185007df9e3555ff493

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

原始种子者

匿名