CodeSampleX

Пример

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

Проверенный пример — golang google.golang.org/protobuf v1.36.11: prototext.Marshal. Контракт выполнен на go 1.26 · linux debian/x64 · docker и пройден…

sha256:da0c8ee03de8c9201d6815851c5177129945cc111bad70b3052da06deeb69874

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда go linux 24 · ubuntu · glibc 2.39 x64 go go 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-09-02

Кейс

HOW
Цель
verify prototext.Marshal in pkg:golang/google.golang.org/protobuf@v1.36.11
Пакеты
Символы
  • prototext.Marshal
Окружение
go
Создан
2026-09-02T08:54:04Z

Контракт

  1. prototext.Marshal formats a proto.Message into compact single-line text format without extra whitespace after colons, and prototext.Format produces multiline text format.
  2. prototext.MarshalOptions with Multiline and Indent formats text with newlines, colon spacing, and custom indentation.
  3. prototext.MarshalOptions.MarshalAppend appends serialized protobuf text to an existing byte slice without mutating prefix data.
  4. prototext.MarshalOptions with EmitASCII controls whether non-ASCII UTF-8 characters are escaped with octal/hex sequences or preserved as UTF-8.
  5. prototext.MarshalOptions with Resolver expands anypb.Any messages into type-bracketed text syntax [type_url] { ... }.
  6. prototext.MarshalOptions serializes dynamic messages including structpb.Struct and timestamppb.Timestamp.

Файлы

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

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

NOTES.md
# Protocol Buffers prototext.Marshal Serialization Semantics

A search for `prototext.Marshal` in `pkg:golang/google.golang.org/protobuf@v1.36.11` returned `NO_SAFE_MATCH`.

This sample verifies the serialization options and behavior provided by `prototext.Marshal` and `prototext.MarshalOptions`.

## Observed Behavior

1. **Default Compact Formatting (`prototext.Marshal` vs `prototext.Format`)**:
   - `prototext.Marshal(m)` produces compact single-line text output with no space after colons (e.g. `file_name:"service/schema.proto"`).
   - `prototext.Format(m)` formats messages with multiline human-readable text by default (e.g. `file_name:  "service/schema.proto"\n`).

2. **Multiline and Indentation (`Multiline`, `Indent`, `Format`)**:
   - Setting `Multiline: false` produces compact single-line text output with 2-space separator between top-level fields.
   - Setting `Multiline: true` formats text with newlines and 2 spaces after field colons.
   - Setting `Indent: "  "` sets 2-space indentation per nesting level.
   - `MarshalOptions.Format(m)` returns string representation identical to `Marshal(m)` under configured options.

3. **Appending to Buffer (`MarshalAppend`)**:
   - `MarshalOptions.MarshalAppend(dst, m)` appends the serialized protobuf text payload directly to `dst` without mutating prefix data.

4. **Non-ASCII Escaping (`EmitASCII`)**:
   - When `EmitASCII: false` (default), valid UTF-8 characters are preserved directly in output.
   - When `EmitASCII: true`, non-ASCII Unicode characters are escaped with octal/hex sequences while preserving ASCII substrings.

5. **Any Message Resolution (`Resolver`)**:
   - Setting `Resolver: protoregistry.GlobalTypes` expands `anypb.Any` messages into bracketed type URL syntax `[type.googleapis.com/...] { ... }` with inner fields serialized.

6. **Dynamic Message Serialization**:
   - Serializes dynamic well-known types including `structpb.Struct` (`fields: { ... }`) and `timestamppb.Timestamp` (`seconds: ...`).
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.Marshal 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.Marshal
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:c636f602f3bb7d00bf156dec7821d597f68b985fa5f98630fb87af244b18ae1c","contract":["prototext.Marshal formats a proto.Message into compact single-line text format without extra whitespace after colons, and prototext.Format produces multiline text format.","prototext.MarshalOptions with Multiline and Indent formats text with newlines, colon spacing, and custom indentation.","prototext.MarshalOptions.MarshalAppend appends serialized protobuf text to an existing byte slice without mutating prefix data.","prototext.MarshalOptions with EmitASCII controls whether non-ASCII UTF-8 characters are escaped with octal/hex sequences or preserved as UTF-8.","prototext.MarshalOptions with Resolver expands anypb.Any messages into type-bracketed text syntax [type_url] { ... }.","prototext.MarshalOptions serializes dynamic messages including structpb.Struct and timestamppb.Timestamp."],"goal":"verify prototext.Marshal 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.Marshal"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","distro":"ubuntu","ecosystem":"golang","executionContext":"go","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.Marshal"],"verifierAdapter":"golang@1"}
go.mod
module example.com/prototextdemo

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=
google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
prototext_marshal_test.go
package prototextdemo_test

import (
	"bytes"
	"strings"
	"testing"

	"google.golang.org/protobuf/encoding/prototext"
	"google.golang.org/protobuf/reflect/protoregistry"
	"google.golang.org/protobuf/types/known/anypb"
	"google.golang.org/protobuf/types/known/apipb"
	"google.golang.org/protobuf/types/known/sourcecontextpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)

// TestMarshalDefault verifies prototext.Marshal default compact single-line output
// and prototext.Format multiline text formatting.
func TestMarshalDefault(t *testing.T) {
	msg := &sourcecontextpb.SourceContext{
		FileName: "service/schema.proto",
	}

	out, err := prototext.Marshal(msg)
	if err != nil {
		t.Fatalf("prototext.Marshal failed: %v", err)
	}

	expectedCompact := `file_name:"service/schema.proto"`
	if string(out) != expectedCompact {
		t.Fatalf("unexpected marshal output: want %q, got %q", expectedCompact, string(out))
	}

	// prototext.Format formats as multiline text
	formatted := prototext.Format(msg)
	if !strings.Contains(formatted, "file_name:") || !strings.Contains(formatted, `"service/schema.proto"`) {
		t.Fatalf("prototext.Format unexpected output: %s", formatted)
	}
}

// TestMarshalOptionsMultilineAndIndent verifies Multiline and Indent formatting.
func TestMarshalOptionsMultilineAndIndent(t *testing.T) {
	msg := &apipb.Api{
		Name:    "v1.ComputeService",
		Version: "v1.0",
		SourceContext: &sourcecontextpb.SourceContext{
			FileName: "compute.proto",
		},
	}

	// 1. Single-line default (Multiline: false)
	optsSingle := prototext.MarshalOptions{
		Multiline: false,
	}
	outSingle, err := optsSingle.Marshal(msg)
	if err != nil {
		t.Fatalf("Marshal with Multiline: false failed: %v", err)
	}
	if strings.Contains(string(outSingle), "\n") {
		t.Fatalf("expected single line output, got newline: %s", string(outSingle))
	}
	outSingleStr := string(outSingle)
	if !strings.Contains(outSingleStr, `name:"v1.ComputeService"`) ||
		!strings.Contains(outSingleStr, `version:"v1.0"`) ||
		!strings.Contains(outSingleStr, `source_context:{file_name:"compute.proto"}`) {
		t.Fatalf("unexpected single-line output: %s", outSingleStr)
	}

	// 2. Multiline with 2-space indent
	optsMulti := prototext.MarshalOptions{
		Multiline: true,
		Indent:    "  ",
	}
	outMulti, err := optsMulti.Marshal(msg)
	if err != nil {
		t.Fatalf("Marshal with Multiline: true failed: %v", err)
	}
	if !strings.Contains(string(outMulti), "\n") {
		t.Fatalf("expected multiline output with newlines: %s", string(outMulti))
	}
	outMultiStr := string(outMulti)
	if !strings.Contains(outMultiStr, "source_context:") ||
		!strings.Contains(outMultiStr, "  file_name:") ||
		!strings.Contains(outMultiStr, `"compute.proto"`) {
		t.Fatalf("unexpected indentation structure in:\n%s", outMultiStr)
	}

	// 3. Format parity with Multiline options
	formatted := optsMulti.Format(msg)
	if formatted != string(outMulti) {
		t.Fatalf("Format() mismatch: want %q, got %q", string(outMulti), formatted)
	}
}

// TestMarshalOptionsMarshalAppend verifies appending marshaled text to an existing buffer.
func TestMarshalOptionsMarshalAppend(t *testing.T) {
	msg := &sourcecontextpb.SourceContext{
		FileName: "config.proto",
	}

	opts := prototext.MarshalOptions{}
	prefix := []byte("# Header comment\n")
	result, err := opts.MarshalAppend(prefix, msg)
	if err != nil {
		t.Fatalf("MarshalAppend failed: %v", err)
	}

	if !bytes.HasPrefix(result, prefix) {
		t.Fatalf("expected prefix preserved, got: %s", string(result))
	}

	payload := string(result[len(prefix):])
	if payload != `file_name:"config.proto"` {
		t.Fatalf("unexpected appended payload: %s", payload)
	}
}

// TestMarshalOptionsEmitASCII verifies escaping non-ASCII characters vs preserving UTF-8.
func TestMarshalOptionsEmitASCII(t *testing.T) {
	msg := &wrapperspb.StringValue{
		Value: "안녕 World \u00e9",
	}

	// Default (EmitASCII: false): preserves UTF-8
	optsUTF8 := prototext.MarshalOptions{
		EmitASCII: false,
	}
	outUTF8, err := optsUTF8.Marshal(msg)
	if err != nil {
		t.Fatalf("Marshal UTF-8 failed: %v", err)
	}
	if !strings.Contains(string(outUTF8), "안녕 World \u00e9") {
		t.Fatalf("expected UTF-8 text preserved, got: %s", string(outUTF8))
	}

	// EmitASCII: true: escapes non-ASCII characters
	optsASCII := prototext.MarshalOptions{
		EmitASCII: true,
	}
	outASCII, err := optsASCII.Marshal(msg)
	if err != nil {
		t.Fatalf("Marshal ASCII failed: %v", err)
	}
	if strings.Contains(string(outASCII), "안녕") {
		t.Fatalf("expected non-ASCII to be escaped, got: %s", string(outASCII))
	}
	if !strings.Contains(string(outASCII), "World") {
		t.Fatalf("expected ASCII part 'World' to remain readable, got: %s", string(outASCII))
	}
}

// TestMarshalOptionsResolverWithAny verifies marshaling anypb.Any messages.
func TestMarshalOptionsResolverWithAny(t *testing.T) {
	inner := &sourcecontextpb.SourceContext{
		FileName: "nested/spec.proto",
	}
	anyMsg, err := anypb.New(inner)
	if err != nil {
		t.Fatalf("anypb.New failed: %v", err)
	}

	opts := prototext.MarshalOptions{
		Multiline: true,
		Indent:    "  ",
		Resolver:  protoregistry.GlobalTypes,
	}
	out, err := opts.Marshal(anyMsg)
	if err != nil {
		t.Fatalf("Marshal with Resolver failed: %v", err)
	}

	outStr := string(out)
	if !strings.Contains(outStr, "[type.googleapis.com/google.protobuf.SourceContext]:") {
		t.Fatalf("expected type URL expanded in Any text output, got:\n%s", outStr)
	}
	if !strings.Contains(outStr, "file_name:") || !strings.Contains(outStr, `"nested/spec.proto"`) {
		t.Fatalf("expected inner message fields expanded, got:\n%s", outStr)
	}
}

// TestMarshalOptionsStructAndTimestamp verifies marshaling dynamic structpb and timestamppb.
func TestMarshalOptionsStructAndTimestamp(t *testing.T) {
	st, err := structpb.NewStruct(map[string]interface{}{
		"host": "localhost",
		"port": 8080,
	})
	if err != nil {
		t.Fatalf("structpb.NewStruct failed: %v", err)
	}

	ts := timestamppb.Now()

	opts := prototext.MarshalOptions{
		Multiline: true,
		Indent:    "  ",
	}

	stOut, err := opts.Marshal(st)
	if err != nil {
		t.Fatalf("Marshal Struct failed: %v", err)
	}
	if !strings.Contains(string(stOut), "fields:") || !strings.Contains(string(stOut), `"host"`) {
		t.Fatalf("expected struct fields in output:\n%s", string(stOut))
	}

	tsOut, err := opts.Marshal(ts)
	if err != nil {
		t.Fatalf("Marshal Timestamp failed: %v", err)
	}
	if !strings.Contains(string(tsOut), "seconds:") {
		t.Fatalf("expected seconds field in timestamp output:\n%s", string(tsOut))
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify prototext.Marshal in pkg:golang/google.golang.org/protobuf@v1.36.11",
  "kind": "HOW",
  "packages": [
    "pkg:golang/google.golang.org/protobuf@v1.36.11"
  ],
  "symbols": [
    "prototext.Marshal"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}

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

аноним