CodeSampleX

Exemplo

google.golang.org/protobuf v1.36.11: prototext.Unmarshal

Amostra verificada para golang google.golang.org/protobuf v1.36.11: prototext.Unmarshal. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou…

sha256:b0260f6a2ceda20e0639956fb3a3371bf7ab72cd3dd489bdc09082884c98a1df

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
1
Chaves de assinatura que o compilaram
1
Ambiente declarado go linux 24 · ubuntu · glibc 2.39 x64 go go go

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
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-02

Caso

HOW
Objetivo
verify prototext.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11
Pacotes
Símbolos
  • prototext.Unmarshal
Ambiente
go
Criado
2026-09-02T08:51:27Z

Contrato

  1. prototext.Unmarshal parses scalar fields, enums, repeated elements, and nested submessages using either brace or angle-bracket syntax.
  2. prototext.Unmarshal supports comments and list notation for repeated fields in text format representations.
  3. prototext.UnmarshalOptions.DiscardUnknown ignores unrecognized fields when true and returns an error by default when false.
  4. prototext.Unmarshal parses map entries and Google well-known types such as Timestamp and Duration.
  5. prototext.Unmarshal returns an error when encountering syntax errors or type mismatches.

Arquivos

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • prototext_unmarshal_test.go
  • spec.json

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

NOTES.md
# Protocol Buffers Text Format Deserialization with prototext.Unmarshal

This sample demonstrates and verifies text format unmarshaling semantics in `google.golang.org/protobuf/encoding/prototext` pinned to version `v1.36.11`.

## Verified Behaviors

1. **Basic Field Deserialization and Comments**:
   - `prototext.Unmarshal` parses standard scalar fields (int64, string, bool, double).
   - Text format supports comments starting with `#`.

2. **Enums and Nested Submessages**:
   - Enum fields can be populated using their symbolic identifier names (e.g. `STATUS_ACTIVE`).
   - Nested submessages can be parsed using either curly braces `{ ... }` or angle brackets `< ... >`.

3. **Repeated Fields**:
   - Repeated fields are parsed from multiple consecutive field declarations or from list brackets `[...]`.

4. **Map Entries**:
   - Protocol buffer maps are parsed from sequence entries with `key` and `value` fields.

5. **UnmarshalOptions.DiscardUnknown**:
   - By default, unmarshaling returns an error when encountering unknown/unrecognized fields.
   - Setting `prototext.UnmarshalOptions{DiscardUnknown: true}` ignores unknown fields and populates known fields.

6. **Syntax Errors and Well-Known Types**:
   - Malformed text input (e.g. unclosed braces or invalid scalar types) produces an error.
   - Google well-known types (`timestamppb.Timestamp`, `durationpb.Duration`) are deserialized properly.
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 prototext.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/google.golang.org/protobuf@v1.36.11
Demonstrate these symbols/APIs:
  - prototext.Unmarshal

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:ad9c8d1bae3fde3a0e3ab7b0838a91759efb6861e3f11425c4048f96ad11f6e6","contract":["prototext.Unmarshal parses scalar fields, enums, repeated elements, and nested submessages using either brace or angle-bracket syntax.","prototext.Unmarshal supports comments and list notation for repeated fields in text format representations.","prototext.UnmarshalOptions.DiscardUnknown ignores unrecognized fields when true and returns an error by default when false.","prototext.Unmarshal parses map entries and Google well-known types such as Timestamp and Duration.","prototext.Unmarshal returns an error when encountering syntax errors or type mismatches."],"goal":"verify prototext.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11","kind":"HOW","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"symbols":["prototext.Unmarshal"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","language":"go","libc":"glibc","libcVersion":"2.39","os":"linux","osVersionBucket":"24","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/google.golang.org/protobuf@v1.36.11"],"schemaVersion":1,"subject":"pkg:golang/google.golang.org/protobuf@v1.36.11","symbols":["prototext.Unmarshal"],"verifierAdapter":"golang@1"}
go.mod
module example.com/prototextunmarshal

go 1.23

require google.golang.org/protobuf v1.36.11
go.sum
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
prototext_unmarshal_test.go
package main

import (
	"testing"
	"time"

	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protodesc"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/descriptorpb"
	"google.golang.org/protobuf/types/dynamicpb"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)

func buildDescriptors(t *testing.T) (protoreflect.MessageDescriptor, protoreflect.MessageDescriptor, protoreflect.EnumDescriptor) {
	t.Helper()
	fd := &descriptorpb.FileDescriptorProto{
		Name:    proto.String("sample.proto"),
		Syntax:  proto.String("proto3"),
		Package: proto.String("sample"),
		EnumType: []*descriptorpb.EnumDescriptorProto{
			{
				Name: proto.String("Status"),
				Value: []*descriptorpb.EnumValueDescriptorProto{
					{Name: proto.String("STATUS_UNSPECIFIED"), Number: proto.Int32(0)},
					{Name: proto.String("STATUS_ACTIVE"), Number: proto.Int32(1)},
					{Name: proto.String("STATUS_SUSPENDED"), Number: proto.Int32(2)},
				},
			},
		},
		MessageType: []*descriptorpb.DescriptorProto{
			{
				Name: proto.String("Profile"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:   proto.String("bio"),
						Number: proto.Int32(1),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
					},
					{
						Name:   proto.String("avatar_url"),
						Number: proto.Int32(2),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
					},
				},
			},
			{
				Name: proto.String("User"),
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:   proto.String("user_id"),
						Number: proto.Int32(1),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_INT64.Enum(),
					},
					{
						Name:   proto.String("username"),
						Number: proto.Int32(2),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
					},
					{
						Name:   proto.String("is_active"),
						Number: proto.Int32(3),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_BOOL.Enum(),
					},
					{
						Name:   proto.String("score"),
						Number: proto.Int32(4),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_DOUBLE.Enum(),
					},
					{
						Name:     proto.String("status"),
						Number:   proto.Int32(5),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_ENUM.Enum(),
						TypeName: proto.String(".sample.Status"),
					},
					{
						Name:     proto.String("profile"),
						Number:   proto.Int32(6),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
						TypeName: proto.String(".sample.Profile"),
					},
					{
						Name:   proto.String("tags"),
						Number: proto.Int32(7),
						Label:  descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						Type:   descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
					},
				},
			},
			{
				Name: proto.String("ConfigMap"),
				NestedType: []*descriptorpb.DescriptorProto{
					{
						Name: proto.String("AttributesEntry"),
						Field: []*descriptorpb.FieldDescriptorProto{
							{
								Name:   proto.String("key"),
								Number: proto.Int32(1),
								Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
								Type:   descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
							},
							{
								Name:   proto.String("value"),
								Number: proto.Int32(2),
								Label:  descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
								Type:   descriptorpb.FieldDescriptorProto_TYPE_STRING.Enum(),
							},
						},
						Options: &descriptorpb.MessageOptions{
							MapEntry: proto.Bool(true),
						},
					},
				},
				Field: []*descriptorpb.FieldDescriptorProto{
					{
						Name:     proto.String("attributes"),
						Number:   proto.Int32(1),
						Label:    descriptorpb.FieldDescriptorProto_LABEL_REPEATED.Enum(),
						Type:     descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum(),
						TypeName: proto.String(".sample.ConfigMap.AttributesEntry"),
					},
				},
			},
		},
	}

	file, err := protodesc.NewFile(fd, nil)
	if err != nil {
		t.Fatalf("protodesc.NewFile failed: %v", err)
	}

	userMsg := file.Messages().ByName("User")
	configMapMsg := file.Messages().ByName("ConfigMap")
	statusEnum := file.Enums().ByName("Status")
	return userMsg, configMapMsg, statusEnum
}

func TestPrototextUnmarshalBasicFieldsAndComments(t *testing.T) {
	userMsg, _, _ := buildDescriptors(t)

	inputText := `
		# User account configuration
		user_id: 1001
		username: "alice"
		is_active: true
		score: 98.5
	`

	msg := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(inputText), msg); err != nil {
		t.Fatalf("prototext.Unmarshal failed: %v", err)
	}

	if msg.Get(userMsg.Fields().ByName("user_id")).Int() != 1001 {
		t.Fatalf("expected user_id 1001, got %v", msg.Get(userMsg.Fields().ByName("user_id")).Int())
	}
	if msg.Get(userMsg.Fields().ByName("username")).String() != "alice" {
		t.Fatalf("expected username 'alice', got %v", msg.Get(userMsg.Fields().ByName("username")).String())
	}
	if !msg.Get(userMsg.Fields().ByName("is_active")).Bool() {
		t.Fatalf("expected is_active true, got false")
	}
	if msg.Get(userMsg.Fields().ByName("score")).Float() != 98.5 {
		t.Fatalf("expected score 98.5, got %v", msg.Get(userMsg.Fields().ByName("score")).Float())
	}
}

func TestPrototextUnmarshalEnumsAndSubmessages(t *testing.T) {
	userMsg, _, statusEnum := buildDescriptors(t)

	// Test nested submessage with curly braces and enum identifier
	inputTextBraces := `
		user_id: 2002
		status: STATUS_ACTIVE
		profile: {
			bio: "Engineer and builder"
			avatar_url: "https://example.com/avatar.png"
		}
	`

	msg1 := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(inputTextBraces), msg1); err != nil {
		t.Fatalf("prototext.Unmarshal with braces failed: %v", err)
	}

	activeVal := statusEnum.Values().ByName("STATUS_ACTIVE").Number()
	if msg1.Get(userMsg.Fields().ByName("status")).Enum() != activeVal {
		t.Fatalf("expected status STATUS_ACTIVE (%d), got %v", activeVal, msg1.Get(userMsg.Fields().ByName("status")).Enum())
	}

	profileMsg1 := msg1.Get(userMsg.Fields().ByName("profile")).Message()
	bioField := userMsg.Fields().ByName("profile").Message().Fields().ByName("bio")
	if profileMsg1.Get(bioField).String() != "Engineer and builder" {
		t.Fatalf("expected bio 'Engineer and builder', got %s", profileMsg1.Get(bioField).String())
	}

	// Test nested submessage with angle brackets (<>) syntax
	inputTextAngleBrackets := `
		user_id: 3003
		status: STATUS_SUSPENDED
		profile: <
			bio: "Temporary account"
			avatar_url: "https://example.com/suspended.png"
		>
	`

	msg2 := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(inputTextAngleBrackets), msg2); err != nil {
		t.Fatalf("prototext.Unmarshal with angle brackets failed: %v", err)
	}

	suspendedVal := statusEnum.Values().ByName("STATUS_SUSPENDED").Number()
	if msg2.Get(userMsg.Fields().ByName("status")).Enum() != suspendedVal {
		t.Fatalf("expected status STATUS_SUSPENDED (%d), got %v", suspendedVal, msg2.Get(userMsg.Fields().ByName("status")).Enum())
	}

	profileMsg2 := msg2.Get(userMsg.Fields().ByName("profile")).Message()
	if profileMsg2.Get(bioField).String() != "Temporary account" {
		t.Fatalf("expected bio 'Temporary account', got %s", profileMsg2.Get(bioField).String())
	}
}

func TestPrototextUnmarshalRepeatedFieldsAndListNotation(t *testing.T) {
	userMsg, _, _ := buildDescriptors(t)

	// Repeated fields specified as consecutive entries
	inputConsecutive := `
		tags: "golang"
		tags: "protobuf"
		tags: "grpc"
	`

	msg1 := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(inputConsecutive), msg1); err != nil {
		t.Fatalf("prototext.Unmarshal consecutive repeated failed: %v", err)
	}

	tagsList1 := msg1.Get(userMsg.Fields().ByName("tags")).List()
	if tagsList1.Len() != 3 {
		t.Fatalf("expected 3 tags, got %d", tagsList1.Len())
	}
	if tagsList1.Get(0).String() != "golang" || tagsList1.Get(1).String() != "protobuf" || tagsList1.Get(2).String() != "grpc" {
		t.Fatalf("unexpected tags: %v", tagsList1)
	}

	// Repeated fields specified with list bracket notation [...]
	inputListBracket := `
		tags: ["backend", "distributed", "networking"]
	`

	msg2 := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(inputListBracket), msg2); err != nil {
		t.Fatalf("prototext.Unmarshal bracket list notation failed: %v", err)
	}

	tagsList2 := msg2.Get(userMsg.Fields().ByName("tags")).List()
	if tagsList2.Len() != 3 {
		t.Fatalf("expected 3 tags, got %d", tagsList2.Len())
	}
	if tagsList2.Get(0).String() != "backend" || tagsList2.Get(1).String() != "distributed" || tagsList2.Get(2).String() != "networking" {
		t.Fatalf("unexpected tags: %v", tagsList2)
	}
}

func TestPrototextUnmarshalMaps(t *testing.T) {
	_, configMapMsg, _ := buildDescriptors(t)

	inputMapText := `
		attributes: { key: "environment" value: "production" }
		attributes: { key: "cluster" value: "us-central1" }
	`

	msg := dynamicpb.NewMessage(configMapMsg)
	if err := prototext.Unmarshal([]byte(inputMapText), msg); err != nil {
		t.Fatalf("prototext.Unmarshal map entries failed: %v", err)
	}

	attrsMap := msg.Get(configMapMsg.Fields().ByName("attributes")).Map()
	if attrsMap.Len() != 2 {
		t.Fatalf("expected map length 2, got %d", attrsMap.Len())
	}

	envVal := attrsMap.Get(protoreflect.ValueOfString("environment").MapKey())
	if envVal.String() != "production" {
		t.Fatalf("expected environment 'production', got %s", envVal.String())
	}

	clusterVal := attrsMap.Get(protoreflect.ValueOfString("cluster").MapKey())
	if clusterVal.String() != "us-central1" {
		t.Fatalf("expected cluster 'us-central1', got %s", clusterVal.String())
	}
}

func TestPrototextUnmarshalOptionsDiscardUnknown(t *testing.T) {
	userMsg, _, _ := buildDescriptors(t)

	inputWithUnknown := `
		user_id: 5050
		username: "charlie"
		unknown_legacy_field: "should_fail_unless_discarded"
	`

	// Default unmarshal returns error when encountering unknown field
	msgDefault := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(inputWithUnknown), msgDefault); err == nil {
		t.Fatalf("expected prototext.Unmarshal to fail on unknown field by default")
	}

	// UnmarshalOptions with DiscardUnknown: true succeeds
	opts := prototext.UnmarshalOptions{
		DiscardUnknown: true,
	}

	msgDiscard := dynamicpb.NewMessage(userMsg)
	if err := opts.Unmarshal([]byte(inputWithUnknown), msgDiscard); err != nil {
		t.Fatalf("opts.Unmarshal with DiscardUnknown=true failed: %v", err)
	}

	if msgDiscard.Get(userMsg.Fields().ByName("user_id")).Int() != 5050 {
		t.Fatalf("expected user_id 5050, got %v", msgDiscard.Get(userMsg.Fields().ByName("user_id")).Int())
	}
	if msgDiscard.Get(userMsg.Fields().ByName("username")).String() != "charlie" {
		t.Fatalf("expected username 'charlie', got %v", msgDiscard.Get(userMsg.Fields().ByName("username")).String())
	}
}

func TestPrototextUnmarshalSyntaxErrors(t *testing.T) {
	userMsg, _, _ := buildDescriptors(t)

	// Unclosed braces syntax error
	invalidBraceInput := `
		user_id: 100
		profile: {
			bio: "missing closing brace"
	`
	msg := dynamicpb.NewMessage(userMsg)
	if err := prototext.Unmarshal([]byte(invalidBraceInput), msg); err == nil {
		t.Fatalf("expected unclosed brace input to produce syntax error")
	}

	// Invalid scalar type (string provided for integer field)
	invalidTypeInput := `
		user_id: "not_a_valid_number"
	`
	if err := prototext.Unmarshal([]byte(invalidTypeInput), msg); err == nil {
		t.Fatalf("expected type mismatch input to produce error")
	}
}

func TestPrototextUnmarshalWellKnownTypes(t *testing.T) {
	// Timestamp text representation
	tsText := `seconds: 1725264000 nanos: 500000`
	ts := &timestamppb.Timestamp{}
	if err := prototext.Unmarshal([]byte(tsText), ts); err != nil {
		t.Fatalf("prototext.Unmarshal Timestamp failed: %v", err)
	}
	if ts.Seconds != 1725264000 || ts.Nanos != 500000 {
		t.Fatalf("expected seconds=1725264000, nanos=500000, got seconds=%d, nanos=%d", ts.Seconds, ts.Nanos)
	}

	// Duration text representation
	durText := `seconds: 120 nanos: 0`
	dur := &durationpb.Duration{}
	if err := prototext.Unmarshal([]byte(durText), dur); err != nil {
		t.Fatalf("prototext.Unmarshal Duration failed: %v", err)
	}
	if dur.AsDuration() != 2*time.Minute {
		t.Fatalf("expected duration 2m, got %v", dur.AsDuration())
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify prototext.Unmarshal in pkg:golang/google.golang.org/protobuf@v1.36.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.11"
  ],
  "symbols": [
    "prototext.Unmarshal"
  ]
}

Seeder de origem

anônimo