CodeSampleX

Exemple

github.com/google/go-cmp v0.6.0: cmp.Transformer

Échantillon vérifié pour golang github.com/google/go-cmp v0.6.0: cmp.Transformer. Le contrat s'est exécuté sur go 1.26 · linux debian/x64 · docker et a…

sha256:3e57308f36c1729b8b42b6d3537f4e9836af99da89eca0cb4726432f4facdb13

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-15

Cas

HOW
Objectif
verify github.com/google/go-cmp/cmp.Transformer in pkg:golang/github.com/google/go-cmp@v0.6.0
Paquets
Symboles
  • github.com/google/go-cmp/cmp.Transformer
Créé
2026-09-15T10:45:27Z

Contrat

  1. cmp.Transformer converts unexported struct types into exported primitive values to avoid reflection panics during comparison
  2. cmp.Transformer enables case-insensitive and trimmed string comparisons by applying normalization functions
  3. cmp.Transformer allows normalizing complex types like time.Time to integer Unix seconds to ignore timezone and subsecond differences
  4. cmp.Transformer applies recursively across nested struct fields and slice elements
  5. cmp.Transformer rejects functions with invalid signatures such as zero inputs or multiple outputs with runtime panics
  6. cmp.Diff includes the transformer name in the diff path output when transformed values differ

Fichiers

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

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

Code source

NOTES.md
# google/go-cmp: Custom Value Transformation and Normalization with cmp.Transformer

## Known Solutions Search
A search for `github.com/google/go-cmp/cmp.Transformer` in `pkg:golang/github.com/google/go-cmp@v0.6.0` returned `REFERENCE_ONLY` (adapted from v0.7.0).

This sample investigates and verifies the contract of `cmp.Transformer` for `pkg:golang/github.com/google/go-cmp@v0.6.0`, demonstrating:
1. Transforming unexported struct types to comparable primitive values, preventing reflection panics on unexported fields.
2. Value normalization (e.g., case-insensitivity with `strings.ToLower`, whitespace trimming with `strings.TrimSpace`).
3. Normalizing complex types such as `time.Time` to integer Unix timestamps to ignore timezone and subsecond differences.
4. Recursive application of transformers across nested structs and slice elements.
5. Strict runtime signature validation when constructing transformers (requiring `func(T) R` with exactly 1 parameter and 1 return value).
6. Inclusion of transformer names in diff paths when comparisons fail.

## Pinned Release
`github.com/google/go-cmp v0.6.0` declared in `go.mod` and verified in `go.sum`.

## Failure Modes
1. Direct comparison of types with unexported fields triggers runtime panics: `cannot handle unexported field`.
2. Direct comparison of strings with varying cases or timestamps with differing subseconds/timezones evaluates as unequal without explicit transformation options.
3. Passing non-functions, zero-argument functions, or multi-return functions to `cmp.Transformer` panics at runtime.

## Observed Behaviour
1. `cmp.Transformer(name, f)` wraps a conversion function `func(T) R` to convert values before comparison.
2. Transformers automatically apply recursively to any field or slice element matching type `T`.
3. Diff output includes the transformer's name for clear diagnostics.
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.Transformer in pkg:golang/github.com/google/go-cmp@v0.6.0
Kind: HOW

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

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:0968eddc538657444c4f331e38d199392ad0ee0cb402d261b62fef8c9ee421a6","contract":["cmp.Transformer converts unexported struct types into exported primitive values to avoid reflection panics during comparison","cmp.Transformer enables case-insensitive and trimmed string comparisons by applying normalization functions","cmp.Transformer allows normalizing complex types like time.Time to integer Unix seconds to ignore timezone and subsecond differences","cmp.Transformer applies recursively across nested struct fields and slice elements","cmp.Transformer rejects functions with invalid signatures such as zero inputs or multiple outputs with runtime panics","cmp.Diff includes the transformer name in the diff path output when transformed values differ"],"goal":"verify github.com/google/go-cmp/cmp.Transformer in pkg:golang/github.com/google/go-cmp@v0.6.0","kind":"HOW","packages":["pkg:golang/github.com/google/go-cmp@v0.6.0"],"schemaVersion":1,"symbols":["github.com/google/go-cmp/cmp.Transformer"]},"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.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/google/go-cmp@v0.6.0","symbols":["github.com/google/go-cmp/cmp.Transformer"],"verifierAdapter":"golang@1"}
go.mod
module example.com/transformercmp

go 1.22

require github.com/google/go-cmp v0.6.0
go.sum
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/google/go-cmp/cmp.Transformer in pkg:golang/github.com/google/go-cmp@v0.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/google/go-cmp@v0.6.0"
  ],
  "symbols": [
    "github.com/google/go-cmp/cmp.Transformer"
  ]
}
test/contract.go
package main

import (
	"errors"
	"fmt"
	"os"
	"strings"
	"time"

	sample "example.com/transformercmp"
	"github.com/google/go-cmp/cmp"
)

func main() {
	// Assertion 1: cmp.Transformer converts unexported struct types into exported primitive values to avoid reflection panics during comparison
	tokA := sample.NewSecretToken("auth_sec_987")
	tokB := sample.NewSecretToken("auth_sec_987")

	_, panicMsg := sample.CompareRawSecretTokens(tokA, tokB)
	if panicMsg == "" {
		fmt.Fprintf(os.Stderr, "FAIL: expected raw comparison of struct with unexported field to panic\n")
		os.Exit(1)
	}
	if !strings.Contains(panicMsg, "cannot handle unexported field") {
		fmt.Fprintf(os.Stderr, "FAIL: expected unexported field panic, got: %s\n", panicMsg)
		os.Exit(1)
	}

	if !sample.CompareSecretTokens(tokA, tokB) {
		fmt.Fprintf(os.Stderr, "FAIL: expected matching SecretToken values to evaluate as equal with SecretTokenTransformer\n")
		os.Exit(1)
	}
	if diff := sample.DiffSecretTokens(tokA, tokB); diff != "" {
		fmt.Fprintf(os.Stderr, "FAIL: expected empty diff for equal SecretToken values, got: %s\n", diff)
		os.Exit(1)
	}

	// Assertion 2: cmp.Transformer enables case-insensitive and trimmed string comparisons by applying normalization functions
	strA := "HelloWorld"
	strB := "helloworld"
	if cmp.Equal(strA, strB) {
		fmt.Fprintf(os.Stderr, "FAIL: expected raw string comparison to fail for different cases\n")
		os.Exit(1)
	}
	if !cmp.Equal(strA, strB, sample.CaseInsensitiveTransformer) {
		fmt.Fprintf(os.Stderr, "FAIL: expected CaseInsensitiveTransformer to equate different cased strings\n")
		os.Exit(1)
	}

	padA := "  data payload \t\n"
	padB := "data payload"
	if cmp.Equal(padA, padB) {
		fmt.Fprintf(os.Stderr, "FAIL: expected raw string comparison to fail for padded strings\n")
		os.Exit(1)
	}
	if !cmp.Equal(padA, padB, sample.TrimSpaceTransformer) {
		fmt.Fprintf(os.Stderr, "FAIL: expected TrimSpaceTransformer to equate strings differing only in whitespace\n")
		os.Exit(1)
	}

	// Assertion 3: cmp.Transformer allows normalizing complex types like time.Time to integer Unix seconds to ignore timezone and subsecond differences
	locTokyo := time.FixedZone("JST", 9*3600)
	t1 := time.Date(2026, 8, 28, 12, 0, 0, 100000, time.UTC)
	t2 := time.Date(2026, 8, 28, 21, 0, 0, 900000, locTokyo)
	if cmp.Equal(t1, t2) {
		fmt.Fprintf(os.Stderr, "FAIL: expected raw time.Time comparison to fail due to timezone and subsecond differences\n")
		os.Exit(1)
	}
	if !cmp.Equal(t1, t2, sample.UnixSecondTransformer) {
		fmt.Fprintf(os.Stderr, "FAIL: expected UnixSecondTransformer to equate timestamps with same Unix second\n")
		os.Exit(1)
	}

	// Assertion 4: cmp.Transformer applies recursively across nested struct fields and slice elements
	userA := sample.UserProfile{
		Username: "ADMIN_USER",
		Token:    sample.NewSecretToken("sec_prod_99"),
		Created:  time.Date(2026, 1, 1, 0, 0, 0, 100, time.UTC),
		Tags:     []string{"ALPHA", "BETA"},
	}
	userB := sample.UserProfile{
		Username: "admin_user",
		Token:    sample.NewSecretToken("sec_prod_99"),
		Created:  time.Date(2026, 1, 1, 9, 0, 0, 999, locTokyo),
		Tags:     []string{"alpha", "beta"},
	}
	if !sample.EqualUserProfiles(userA, userB) {
		fmt.Fprintf(os.Stderr, "FAIL: expected UserProfiles to match under composed transformers\n")
		os.Exit(1)
	}
	userB.Tags[1] = "gamma"
	if sample.EqualUserProfiles(userA, userB) {
		fmt.Fprintf(os.Stderr, "FAIL: expected UserProfiles with differing tags to evaluate as not equal\n")
		os.Exit(1)
	}

	// Assertion 5: cmp.Transformer rejects functions with invalid signatures such as zero inputs or multiple outputs with runtime panics
	assertPanics := func(name string, f func()) {
		defer func() {
			if r := recover(); r == nil {
				fmt.Fprintf(os.Stderr, "FAIL: expected panic for %s but did not panic\n", name)
				os.Exit(1)
			}
		}()
		f()
	}
	assertPanics("non-function", func() {
		_ = cmp.Transformer("invalid", "not_a_function")
	})
	assertPanics("zero-inputs", func() {
		_ = cmp.Transformer("invalid", func() string { return "" })
	})
	assertPanics("multiple-outputs", func() {
		_ = cmp.Transformer("invalid", func(s string) (string, error) { return s, nil })
	})

	// Assertion 6: cmp.Diff includes the transformer name in the diff path output when transformed values differ
	diffTokA := sample.NewSecretToken("auth_sec_aaa")
	diffTokB := sample.NewSecretToken("auth_sec_bbb")
	diff := sample.DiffSecretTokens(diffTokA, diffTokB)
	if !strings.Contains(diff, "SecretToken") {
		fmt.Fprintf(os.Stderr, "FAIL: expected diff to include transformer name 'SecretToken', got: %s\n", diff)
		os.Exit(1)
	}

	// Additional check: ErrorStringTransformer
	errA := errors.New("record not found in storage")
	errB := fmt.Errorf("record not found in storage")
	if !cmp.Equal(errA, errB, sample.ErrorStringTransformer) {
		fmt.Fprintf(os.Stderr, "FAIL: expected ErrorStringTransformer to equate distinct error types with same message\n")
		os.Exit(1)
	}

	fmt.Println("PASS: all cmp.Transformer contract assertions verified")
}
transformer.go
package transformercmp

import (
	"fmt"
	"strings"
	"time"

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

// SecretToken wraps a sensitive string in an unexported field.
// Direct comparison with cmp.Diff triggers a panic due to unexported fields.
type SecretToken struct {
	value string
}

// NewSecretToken constructs a SecretToken.
func NewSecretToken(v string) SecretToken {
	return SecretToken{value: v}
}

// UserProfile represents a user entity with custom and nested fields.
type UserProfile struct {
	Username string
	Token    SecretToken
	Created  time.Time
	Tags     []string
}

// CaseInsensitiveTransformer normalizes strings to lowercase for case-insensitive comparison.
var CaseInsensitiveTransformer = cmp.Transformer("CaseInsensitive", strings.ToLower)

// TrimSpaceTransformer strips leading and trailing whitespace from strings.
var TrimSpaceTransformer = cmp.Transformer("TrimSpace", strings.TrimSpace)

// SecretTokenTransformer converts SecretToken to its underlying string value,
// bypassing unexported field reflection restrictions.
var SecretTokenTransformer = cmp.Transformer("SecretToken", func(t SecretToken) string {
	return t.value
})

// UnixSecondTransformer transforms time.Time into integer Unix seconds,
// ignoring monotonic clock readings, nanosecond precision, and timezone differences.
var UnixSecondTransformer = cmp.Transformer("UnixSeconds", func(t time.Time) int64 {
	return t.Unix()
})

// ErrorStringTransformer transforms an error into its string representation,
// safely handling nil error values.
var ErrorStringTransformer = cmp.Transformer("ErrorString", func(err error) string {
	if err == nil {
		return ""
	}
	return err.Error()
})

// CompareRawSecretTokens attempts direct comparison of SecretToken values without options.
// Traversal of the unexported field 'value' panics at runtime.
func CompareRawSecretTokens(a, b SecretToken) (diff string, panicMsg string) {
	defer func() {
		if r := recover(); r != nil {
			panicMsg = fmt.Sprint(r)
		}
	}()
	diff = cmp.Diff(a, b)
	return diff, panicMsg
}

// CompareSecretTokens evaluates equality of SecretToken using SecretTokenTransformer.
func CompareSecretTokens(a, b SecretToken) bool {
	return cmp.Equal(a, b, SecretTokenTransformer)
}

// DiffSecretTokens produces the diff of SecretToken using SecretTokenTransformer.
func DiffSecretTokens(a, b SecretToken) string {
	return cmp.Diff(a, b, SecretTokenTransformer)
}

// EqualUserProfiles evaluates equality of UserProfile using composed transformers.
func EqualUserProfiles(a, b UserProfile) bool {
	return cmp.Equal(a, b,
		CaseInsensitiveTransformer,
		SecretTokenTransformer,
		UnixSecondTransformer,
	)
}

// DiffUserProfiles computes the diff between UserProfiles using composed transformers.
func DiffUserProfiles(a, b UserProfile) string {
	return cmp.Diff(a, b,
		CaseInsensitiveTransformer,
		SecretTokenTransformer,
		UnixSecondTransformer,
	)
}

Seeder d'origine

anonyme