CodeSampleX

Пример

github.com/envoyproxy/protoc-gen-validate v1.0.4: validate.E_Rules

Проверенный пример — golang github.com/envoyproxy/protoc-gen-validate v1.0.4: validate.E_Rules. Контракт выполнен на go 1.26 · linux debian/x64 · docker и…

sha256:f2106b504a0b752e1352fd2977cf445d5ac692be61b93f8b4b5ec129864e7917

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. 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-10-12

Кейс

HOW
Цель
verify github.com/envoyproxy/protoc-gen-validate/validate.E_Rules in pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4
Пакеты
Символы
  • github.com/envoyproxy/protoc-gen-validate/validate.E_Rules
Создан
2026-10-12T08:06:47Z

Контракт

  1. validate.E_Rules extension descriptor identifies field number 1071 extending google.protobuf.FieldOptions with message type validate.FieldRules
  2. proto.SetExtension associates validate.FieldRules with descriptorpb.FieldOptions and proto.HasExtension reports presence
  3. proto.GetExtension retrieves the configured validate.FieldRules preserving constraint values
  4. proto.ClearExtension removes validate.E_Rules from descriptorpb.FieldOptions returning presence to false
  5. proto.Marshal and proto.Unmarshal round-trip descriptorpb.FieldOptions preserving validate.E_Rules extension data

Файлы

  • 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/envoyproxy/protoc-gen-validate/validate.E_Rules in pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4
Demonstrate these symbols/APIs:
  - github.com/envoyproxy/protoc-gen-validate/validate.E_Rules

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:3b74e298f26840bc543473600e7cfacc424adbd3a3fe34a6ec91e9798226acd0","contract":["validate.E_Rules extension descriptor identifies field number 1071 extending google.protobuf.FieldOptions with message type validate.FieldRules","proto.SetExtension associates validate.FieldRules with descriptorpb.FieldOptions and proto.HasExtension reports presence","proto.GetExtension retrieves the configured validate.FieldRules preserving constraint values","proto.ClearExtension removes validate.E_Rules from descriptorpb.FieldOptions returning presence to false","proto.Marshal and proto.Unmarshal round-trip descriptorpb.FieldOptions preserving validate.E_Rules extension data"],"goal":"verify github.com/envoyproxy/protoc-gen-validate/validate.E_Rules in pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4","kind":"HOW","packages":["pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4"],"schemaVersion":1,"symbols":["github.com/envoyproxy/protoc-gen-validate/validate.E_Rules"]},"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/envoyproxy/protoc-gen-validate@v1.0.4"],"schemaVersion":1,"subject":"pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4","symbols":["github.com/envoyproxy/protoc-gen-validate/validate.E_Rules"],"verifierAdapter":"golang@1"}
go.mod
module example.com/validate_rules

go 1.26.6

require (
	github.com/envoyproxy/protoc-gen-validate v1.0.4
	google.golang.org/protobuf v1.32.0
)

require golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
go.sum
github.com/envoyproxy/protoc-gen-validate v1.0.4 h1:gVPz/FMfvh57HdSJQyvBtF00j8JU4zdyUgIUNhlgg0A=
github.com/envoyproxy/protoc-gen-validate v1.0.4/go.mod h1:qys6tmnRsYrQqIhm2bvKZH4Blx/1gTIZ2UKVY1M+Yew=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
main.go
package main

import (
	"fmt"

	"github.com/envoyproxy/protoc-gen-validate/validate"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/descriptorpb"
)

func main() {
	opts := &descriptorpb.FieldOptions{}

	rules := &validate.FieldRules{
		Type: &validate.FieldRules_String_{
			String_: &validate.StringRules{
				MinLen: proto.Uint64(1),
				MaxLen: proto.Uint64(64),
			},
		},
	}

	proto.SetExtension(opts, validate.E_Rules, rules)

	hasRules := proto.HasExtension(opts, validate.E_Rules)
	retrieved := proto.GetExtension(opts, validate.E_Rules).(*validate.FieldRules)

	fmt.Printf("Has validation rules: %v\n", hasRules)
	fmt.Printf("String rule min length: %d\n", retrieved.GetString_().GetMinLen())
	fmt.Printf("String rule max length: %d\n", retrieved.GetString_().GetMaxLen())
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify github.com/envoyproxy/protoc-gen-validate/validate.E_Rules in pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/envoyproxy/protoc-gen-validate@v1.0.4"
  ],
  "symbols": [
    "github.com/envoyproxy/protoc-gen-validate/validate.E_Rules"
  ]
}
test/contract.go
package main

import (
	"fmt"
	"os"

	"github.com/envoyproxy/protoc-gen-validate/validate"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/descriptorpb"
)

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

func runTests() error {
	// 1. validate.E_Rules extension descriptor identifies field number 1071 extending google.protobuf.FieldOptions with message type validate.FieldRules
	typeDesc := validate.E_Rules.TypeDescriptor()
	if typeDesc.Number() != 1071 {
		return fmt.Errorf("expected field number 1071, got %d", typeDesc.Number())
	}
	if string(typeDesc.ContainingMessage().FullName()) != "google.protobuf.FieldOptions" {
		return fmt.Errorf("expected extended message google.protobuf.FieldOptions, got %s", typeDesc.ContainingMessage().FullName())
	}
	if typeDesc.Message() == nil || string(typeDesc.Message().FullName()) != "validate.FieldRules" {
		return fmt.Errorf("expected message type validate.FieldRules, got %v", typeDesc.Message())
	}

	// 2. proto.SetExtension associates validate.FieldRules with descriptorpb.FieldOptions and proto.HasExtension reports presence
	opts := &descriptorpb.FieldOptions{}
	if proto.HasExtension(opts, validate.E_Rules) {
		return fmt.Errorf("expected empty FieldOptions to not have validate.E_Rules")
	}

	rules := &validate.FieldRules{
		Type: &validate.FieldRules_String_{
			String_: &validate.StringRules{
				MinLen:  proto.Uint64(3),
				MaxLen:  proto.Uint64(20),
				Pattern: proto.String("^[a-z0-9_-]+$"),
			},
		},
	}
	proto.SetExtension(opts, validate.E_Rules, rules)
	if !proto.HasExtension(opts, validate.E_Rules) {
		return fmt.Errorf("expected FieldOptions to have validate.E_Rules after proto.SetExtension")
	}

	// 3. proto.GetExtension retrieves the configured validate.FieldRules preserving constraint values
	rawExt := proto.GetExtension(opts, validate.E_Rules)
	gotRules, ok := rawExt.(*validate.FieldRules)
	if !ok {
		return fmt.Errorf("expected *validate.FieldRules from GetExtension, got %T", rawExt)
	}
	strRules := gotRules.GetString_()
	if strRules == nil {
		return fmt.Errorf("expected non-nil StringRules in retrieved FieldRules")
	}
	if strRules.GetMinLen() != 3 {
		return fmt.Errorf("expected min length 3, got %d", strRules.GetMinLen())
	}
	if strRules.GetMaxLen() != 20 {
		return fmt.Errorf("expected max length 20, got %d", strRules.GetMaxLen())
	}
	if strRules.GetPattern() != "^[a-z0-9_-]+$" {
		return fmt.Errorf("expected pattern ^[a-z0-9_-]+$, got %s", strRules.GetPattern())
	}

	// 4. proto.ClearExtension removes validate.E_Rules from descriptorpb.FieldOptions returning presence to false
	proto.ClearExtension(opts, validate.E_Rules)
	if proto.HasExtension(opts, validate.E_Rules) {
		return fmt.Errorf("expected validate.E_Rules to be removed after proto.ClearExtension")
	}

	// 5. proto.Marshal and proto.Unmarshal round-trip descriptorpb.FieldOptions preserving validate.E_Rules extension data
	optsToMarshal := &descriptorpb.FieldOptions{}
	proto.SetExtension(optsToMarshal, validate.E_Rules, rules)

	marshaled, err := proto.Marshal(optsToMarshal)
	if err != nil {
		return fmt.Errorf("proto.Marshal failed: %w", err)
	}

	unmarshaledOpts := &descriptorpb.FieldOptions{}
	if err := proto.Unmarshal(marshaled, unmarshaledOpts); err != nil {
		return fmt.Errorf("proto.Unmarshal failed: %w", err)
	}
	if !proto.HasExtension(unmarshaledOpts, validate.E_Rules) {
		return fmt.Errorf("expected unmarshaled FieldOptions to retain validate.E_Rules extension")
	}
	roundTripExt := proto.GetExtension(unmarshaledOpts, validate.E_Rules).(*validate.FieldRules)
	if roundTripExt.GetString_().GetMinLen() != 3 || roundTripExt.GetString_().GetMaxLen() != 20 {
		return fmt.Errorf("unmarshaled rules constraints do not match original: %+v", roundTripExt.GetString_())
	}

	return nil
}

Исходный сидер

аноним