CodeSampleX

示例

github.com/google/go-cmp v0.5.7: cmp.Ignore

已验证示例 — golang github.com/google/go-cmp v0.5.7: cmp.Ignore. contract 在 go 1.26 · linux debian/x64 · docker 上运行并通过: cmp.Ignore is an Option that causes all…

sha256:fef000cb342fbacd74f18f946e4d3ce6312a75ec51bb6e4cd049843854d628d5

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

执行证据

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

证据依据
签名契约通过
验证回执
1
构建过它的签名密钥
1
声明的环境 linux 24 · ubuntu · glibc 2.39 x64 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-11-07

案例

HOW
目标
verify github.com/google/go-cmp/cmp.Ignore in pkg:golang/github.com/google/go-cmp@v0.5.7
包
符号
  • github.com/google/go-cmp/cmp.Ignore
创建时间
2026-11-07T09:00:32Z

契约

  1. cmp.Ignore is an Option that causes all comparisons matching a filter to be ignored
  2. Passing an unfiltered cmp.Ignore directly to cmp.Equal panics with cannot use an unfiltered option: Ignore()
  3. cmp.FilterPath with cmp.Ignore ignores struct fields by name leaving non-ignored fields evaluated
  4. cmp.FilterPath with cmp.Ignore bypasses reflection panics on unexported struct fields without AllowUnexported
  5. cmp.FilterPath with cmp.Ignore ignores any node in the comparison path matching a specified reflect.Type
  6. cmp.FilterValues with cmp.Ignore conditionally ignores comparisons when a symmetric value predicate returns true
  7. cmp.FilterPath with cmp.Ignore ignores specific map keys or slice indices during container comparison

文件

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • ignore.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/google/go-cmp/cmp.Ignore in pkg:golang/github.com/google/go-cmp@v0.5.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/google/go-cmp@v0.5.7
Demonstrate these symbols/APIs:
  - github.com/google/go-cmp/cmp.Ignore

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:79d0f4417b9e412471e2e6c7d85a328149ffe3282f59a99e6939ddd4275d64a8","contract":["cmp.Ignore is an Option that causes all comparisons matching a filter to be ignored","Passing an unfiltered cmp.Ignore directly to cmp.Equal panics with cannot use an unfiltered option: Ignore()","cmp.FilterPath with cmp.Ignore ignores struct fields by name leaving non-ignored fields evaluated","cmp.FilterPath with cmp.Ignore bypasses reflection panics on unexported struct fields without AllowUnexported","cmp.FilterPath with cmp.Ignore ignores any node in the comparison path matching a specified reflect.Type","cmp.FilterValues with cmp.Ignore conditionally ignores comparisons when a symmetric value predicate returns true","cmp.FilterPath with cmp.Ignore ignores specific map keys or slice indices during container comparison"],"goal":"verify github.com/google/go-cmp/cmp.Ignore in pkg:golang/github.com/google/go-cmp@v0.5.7","kind":"HOW","packages":["pkg:golang/github.com/google/go-cmp@v0.5.7"],"schemaVersion":1,"symbols":["github.com/google/go-cmp/cmp.Ignore"]},"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/google/go-cmp@v0.5.7"],"schemaVersion":1,"subject":"pkg:golang/github.com/google/go-cmp@v0.5.7","symbols":["github.com/google/go-cmp/cmp.Ignore"],"verifierAdapter":"golang@1"}
go.mod
module example.com/ignorecmp

go 1.24

require github.com/google/go-cmp v0.5.7
go.sum
github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
ignore.go
package ignorecmp

import (
	"reflect"
	"unicode"

	"github.com/google/go-cmp/cmp"
)

// IgnoreFieldByName returns an Option that ignores struct fields matching the specified field name.
func IgnoreFieldByName(name string) cmp.Option {
	return cmp.FilterPath(func(p cmp.Path) bool {
		sf, ok := p.Last().(cmp.StructField)
		return ok && sf.Name() == name
	}, cmp.Ignore())
}

// IgnoreUnexportedFields returns an Option that ignores all unexported struct fields,
// preventing reflection panics when comparing structs that contain private fields.
func IgnoreUnexportedFields() cmp.Option {
	return cmp.FilterPath(func(p cmp.Path) bool {
		sf, ok := p.Last().(cmp.StructField)
		if !ok {
			return false
		}
		name := sf.Name()
		return len(name) > 0 && !unicode.IsUpper(rune(name[0]))
	}, cmp.Ignore())
}

// IgnoreType returns an Option that ignores any node in the comparison path matching targetType.
func IgnoreType(targetType reflect.Type) cmp.Option {
	return cmp.FilterPath(func(p cmp.Path) bool {
		return p.Last().Type() == targetType
	}, cmp.Ignore())
}

// IgnoreMapKey returns an Option that ignores map entries with the specified key value.
func IgnoreMapKey[K comparable](ignoredKey K) cmp.Option {
	return cmp.FilterPath(func(p cmp.Path) bool {
		mi, ok := p.Last().(cmp.MapIndex)
		if !ok {
			return false
		}
		keyVal := mi.Key()
		if !keyVal.IsValid() || !keyVal.CanInterface() {
			return false
		}
		if k, ok := keyVal.Interface().(K); ok {
			return k == ignoredKey
		}
		return false
	}, cmp.Ignore())
}

// IgnoreSliceIndex returns an Option that ignores slice elements at the specified zero-based index.
func IgnoreSliceIndex(ignoredIndex int) cmp.Option {
	return cmp.FilterPath(func(p cmp.Path) bool {
		si, ok := p.Last().(cmp.SliceIndex)
		return ok && (si.Key() == ignoredIndex)
	}, cmp.Ignore())
}

// IgnoreMatchingValues returns an Option using FilterValues that ignores comparison
// when the symmetric predicate func(T, T) bool returns true.
func IgnoreMatchingValues[T any](predicate func(x, y T) bool) cmp.Option {
	return cmp.FilterValues(predicate, cmp.Ignore())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/google/go-cmp/cmp.Ignore in pkg:golang/github.com/google/go-cmp@v0.5.7",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/google/go-cmp@v0.5.7"
  ],
  "symbols": [
    "github.com/google/go-cmp/cmp.Ignore"
  ]
}
test/contract.go
package main

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

	"example.com/ignorecmp"
	"github.com/google/go-cmp/cmp"
)

type Account struct {
	ID        int
	Username  string
	UpdatedAt time.Time
}

type TokenSession struct {
	SessionID string
	token     string
}

type MultiSecretSession struct {
	SessionID string
	token     string
	secretKey []byte
}

func assert(cond bool, msg string) {
	if !cond {
		fmt.Fprintln(os.Stderr, "assertion failed:", msg)
		os.Exit(1)
	}
}

func main() {
	// 1. Unfiltered cmp.Ignore() panics with "cannot use an unfiltered option: Ignore()"
	func() {
		defer func() {
			r := recover()
			assert(r != nil, "expected unfiltered cmp.Ignore() to panic")
			assert(strings.Contains(fmt.Sprint(r), "cannot use an unfiltered option: Ignore()"), "unexpected panic message for unfiltered Ignore()")
		}()
		_ = cmp.Equal(10, 20, cmp.Ignore())
	}()

	// 2. Ignore struct field by name via cmp.FilterPath + cmp.Ignore()
	acc1 := Account{
		ID:        1001,
		Username:  "user-alpha",
		UpdatedAt: time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC),
	}
	acc2 := Account{
		ID:        1001,
		Username:  "user-alpha",
		UpdatedAt: time.Date(2026, 9, 15, 12, 0, 0, 0, time.UTC),
	}
	optIgnoreTimestamp := ignorecmp.IgnoreFieldByName("UpdatedAt")
	assert(cmp.Equal(acc1, acc2, optIgnoreTimestamp), "expected accounts to be equal when UpdatedAt is ignored")
	assert(cmp.Diff(acc1, acc2, optIgnoreTimestamp) == "", "expected empty diff when UpdatedAt is ignored")

	acc2.Username = "user-beta"
	assert(!cmp.Equal(acc1, acc2, optIgnoreTimestamp), "expected accounts to differ when Username differs")
	diffWithBeta := cmp.Diff(acc1, acc2, optIgnoreTimestamp)
	assert(strings.Contains(diffWithBeta, "Username"), "expected diff to report Username mismatch")
	assert(!strings.Contains(diffWithBeta, "UpdatedAt"), "expected diff not to report UpdatedAt difference")

	// 3. Unexported struct fields: direct comparison panics, FilterPath + cmp.Ignore() bypasses reflection panic
	func() {
		a := MultiSecretSession{SessionID: "sess-1", token: "tok-aaa", secretKey: []byte{1, 2}}
		b := MultiSecretSession{SessionID: "sess-1", token: "tok-bbb", secretKey: []byte{3, 4}}
		defer func() {
			r := recover()
			assert(r != nil, "expected unexported field comparison to panic without options")
			assert(strings.Contains(fmt.Sprint(r), "cannot handle unexported field"), "unexpected panic message for unexported field")
		}()
		_ = cmp.Equal(a, b)
	}()

	aSess := MultiSecretSession{SessionID: "sess-1", token: "tok-aaa", secretKey: []byte{1, 2}}
	bSess := MultiSecretSession{SessionID: "sess-1", token: "tok-bbb", secretKey: []byte{3, 4}}
	optUnexported := ignorecmp.IgnoreUnexportedFields()
	assert(cmp.Equal(aSess, bSess, optUnexported), "expected equality when unexported fields are ignored")
	assert(cmp.Diff(aSess, bSess, optUnexported) == "", "expected empty diff when unexported fields are ignored")

	bSess.SessionID = "sess-2"
	assert(!cmp.Equal(aSess, bSess, optUnexported), "expected inequality when exported SessionID differs")

	tokA := TokenSession{SessionID: "sess-1", token: "tok-aaa"}
	tokB := TokenSession{SessionID: "sess-1", token: "tok-bbb"}
	assert(cmp.Equal(tokA, tokB, ignorecmp.IgnoreFieldByName("token")), "expected equality when unexported token field is ignored by name")

	// 4. Ignore by reflect.Type via cmp.FilterPath + cmp.Ignore()
	t1 := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
	t2 := time.Date(2026, 12, 31, 23, 59, 59, 0, time.UTC)
	optIgnoreTime := ignorecmp.IgnoreType(reflect.TypeOf(time.Time{}))
	assert(cmp.Equal(t1, t2, optIgnoreTime), "expected time.Time values to be ignored")
	assert(cmp.Equal(
		Account{ID: 5, Username: "user5", UpdatedAt: t1},
		Account{ID: 5, Username: "user5", UpdatedAt: t2},
		optIgnoreTime,
	), "expected struct with differing time.Time field to match when time.Time type is ignored")

	// 5. Conditional ignore via cmp.FilterValues + cmp.Ignore()
	ignoreWildcard := ignorecmp.IgnoreMatchingValues(func(x, y string) bool {
		return x == "*" || y == "*"
	})
	type Config struct {
		Host string
		Port string
	}
	assert(cmp.Equal(Config{Host: "localhost", Port: "8080"}, Config{Host: "*", Port: "8080"}, ignoreWildcard), "expected wildcard host to match")
	assert(!cmp.Equal(Config{Host: "localhost", Port: "8080"}, Config{Host: "*", Port: "9090"}, ignoreWildcard), "expected port mismatch to fail")

	// 6. Ignore specific map keys and slice indices via cmp.FilterPath + cmp.Ignore()
	m1 := map[string]int{"status": 200, "cache_ttl": 60, "cluster": 1}
	m2 := map[string]int{"status": 200, "cache_ttl": 9999, "cluster": 1}
	optMapKey := ignorecmp.IgnoreMapKey("cache_ttl")
	assert(cmp.Equal(m1, m2, optMapKey), "expected maps to match when cache_ttl key is ignored")
	m3 := map[string]int{"status": 500, "cache_ttl": 9999, "cluster": 1}
	assert(!cmp.Equal(m1, m3, optMapKey), "expected non-ignored map key mismatch to be detected")

	s1 := []string{"rev-abc", "active", "zone-1"}
	s2 := []string{"rev-xyz", "active", "zone-1"}
	optSliceIdx := ignorecmp.IgnoreSliceIndex(0)
	assert(cmp.Equal(s1, s2, optSliceIdx), "expected slices to match when index 0 is ignored")
	s3 := []string{"rev-xyz", "inactive", "zone-1"}
	assert(!cmp.Equal(s1, s3, optSliceIdx), "expected non-ignored slice index mismatch to be detected")
}

原始种子者

匿名