CodeSampleX

Exemplo

github.com/go-logfmt/logfmt v0.5.0: NewDecoder, NewEncoder

Amostra verificada para golang github.com/go-logfmt/logfmt v0.5.0: NewDecoder, NewEncoder. O contrato rodou em go 1.26 · linux debian/x64 · docker e passou.

sha256:b930a6892e863e24e66cad9ef7a0e840aec7a61f8f2728be92906c300654cb05

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 linux 24 · ubuntu · glibc 2.39 x64 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-03

Caso

HOW
Objetivo
verify pkg:golang/github.com/go-logfmt/logfmt@v0.5.0
Pacotes
Símbolos
  • github.com/go-logfmt/logfmt.NewDecoder
  • github.com/go-logfmt/logfmt.NewEncoder
Criado
2026-09-03T18:49:22Z

Contrato

  1. logfmt.NewEncoder creates an Encoder that encodes key-value pairs and writes a terminating newline with EndRecord
  2. logfmt.NewEncoder escapes whitespace, quotes and special characters according to the logfmt specification
  3. logfmt.NewDecoder parses records and key-value pairs from an io.Reader
  4. logfmt.NewDecoder unquotes values and exposes keys and values via Key and Value methods
  5. logfmt.NewDecoder returns false without error on empty input or EOF

Arquivos

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

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

Código-fonte

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 pkg:golang/github.com/go-logfmt/logfmt@v0.5.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logfmt/logfmt@v0.5.0
Demonstrate these symbols/APIs:
  - github.com/go-logfmt/logfmt.NewDecoder
  - github.com/go-logfmt/logfmt.NewEncoder

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:52b7bb1c865c707e5c708faedd7d7110fa330b982e7bd1a4ca19fc590706ec8d","contract":["logfmt.NewEncoder creates an Encoder that encodes key-value pairs and writes a terminating newline with EndRecord","logfmt.NewEncoder escapes whitespace, quotes and special characters according to the logfmt specification","logfmt.NewDecoder parses records and key-value pairs from an io.Reader","logfmt.NewDecoder unquotes values and exposes keys and values via Key and Value methods","logfmt.NewDecoder returns false without error on empty input or EOF"],"goal":"verify pkg:golang/github.com/go-logfmt/logfmt@v0.5.0","kind":"HOW","packages":["pkg:golang/github.com/go-logfmt/logfmt@v0.5.0"],"schemaVersion":1,"symbols":["github.com/go-logfmt/logfmt.NewDecoder","github.com/go-logfmt/logfmt.NewEncoder"]},"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/go-logfmt/logfmt@v0.5.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logfmt/logfmt@v0.5.0","symbols":["github.com/go-logfmt/logfmt.NewDecoder","github.com/go-logfmt/logfmt.NewEncoder"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.6

require github.com/go-logfmt/logfmt v0.5.0 // indirect
go.sum
github.com/go-logfmt/logfmt v0.5.0 h1:TrB8swr/68K7m9CcGut2g3UOihhbcbiMAYiuTXdEih4=
github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A=
sample.go
package sample

import (
	"bytes"
	"io"
	"strings"

	"github.com/go-logfmt/logfmt"
)

// EncodeKeyvals formats alternating key and value pairs into logfmt format and writes a terminating newline.
func EncodeKeyvals(w io.Writer, keyvals ...interface{}) error {
	enc := logfmt.NewEncoder(w)
	if err := enc.EncodeKeyvals(keyvals...); err != nil {
		return err
	}
	return enc.EndRecord()
}

// DecodeRecords parses logfmt-formatted data from r into a slice of key-value maps per record.
func DecodeRecords(r io.Reader) ([]map[string]string, error) {
	dec := logfmt.NewDecoder(r)
	var records []map[string]string

	for dec.ScanRecord() {
		record := make(map[string]string)
		for dec.ScanKeyval() {
			record[string(dec.Key())] = string(dec.Value())
		}
		records = append(records, record)
	}

	if err := dec.Err(); err != nil {
		return nil, err
	}
	return records, nil
}

// FormatAndParse round-trips key-value pairs through Encoder and Decoder.
func FormatAndParse(keyvals ...interface{}) (map[string]string, error) {
	var buf bytes.Buffer
	if err := EncodeKeyvals(&buf, keyvals...); err != nil {
		return nil, err
	}
	records, err := DecodeRecords(strings.NewReader(buf.String()))
	if err != nil {
		return nil, err
	}
	if len(records) == 0 {
		return make(map[string]string), nil
	}
	return records[0], nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-logfmt/logfmt@v0.5.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logfmt/logfmt@v0.5.0"
  ],
  "symbols": [
    "github.com/go-logfmt/logfmt.NewDecoder",
    "github.com/go-logfmt/logfmt.NewEncoder"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"fmt"
	"os"
	"strings"

	"github.com/go-logfmt/logfmt"
	"sample"
)

func main() {
	// Assertion 1: logfmt.NewEncoder creates an Encoder that encodes key-value pairs and writes a terminating newline with EndRecord
	var buf bytes.Buffer
	enc := logfmt.NewEncoder(&buf)
	if enc == nil {
		fmt.Fprintf(os.Stderr, "expected non-nil encoder\n")
		os.Exit(1)
	}
	if err := enc.EncodeKeyvals("level", "info", "app", "sample"); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyvals failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord failed: %v\n", err)
		os.Exit(1)
	}
	if buf.String() != "level=info app=sample\n" {
		fmt.Fprintf(os.Stderr, "unexpected output: %q\n", buf.String())
		os.Exit(1)
	}

	// Assertion 2: logfmt.NewEncoder escapes whitespace, quotes and special characters according to the logfmt specification
	buf.Reset()
	if err := enc.EncodeKeyval("msg", "hello \"world\""); err != nil {
		fmt.Fprintf(os.Stderr, "EncodeKeyval failed: %v\n", err)
		os.Exit(1)
	}
	if err := enc.EndRecord(); err != nil {
		fmt.Fprintf(os.Stderr, "EndRecord failed: %v\n", err)
		os.Exit(1)
	}
	if buf.String() != "msg=\"hello \\\"world\\\"\"\n" {
		fmt.Fprintf(os.Stderr, "escaping mismatch: %q\n", buf.String())
		os.Exit(1)
	}

	// Assertion 3: logfmt.NewDecoder parses records and key-value pairs from an io.Reader
	input := "level=info msg=\"task started\" id=101\nlevel=warn msg=\"retrying\" id=101\n"
	records, err := sample.DecodeRecords(strings.NewReader(input))
	if err != nil {
		fmt.Fprintf(os.Stderr, "DecodeRecords failed: %v\n", err)
		os.Exit(1)
	}
	if len(records) != 2 {
		fmt.Fprintf(os.Stderr, "expected 2 records, got %d\n", len(records))
		os.Exit(1)
	}
	if records[0]["level"] != "info" || records[0]["msg"] != "task started" || records[0]["id"] != "101" {
		fmt.Fprintf(os.Stderr, "record 0 mismatch: %+v\n", records[0])
		os.Exit(1)
	}
	if records[1]["level"] != "warn" || records[1]["msg"] != "retrying" {
		fmt.Fprintf(os.Stderr, "record 1 mismatch: %+v\n", records[1])
		os.Exit(1)
	}

	// Assertion 4: logfmt.NewDecoder unquotes values and exposes keys and values via Key and Value methods
	rawInput := "tag=\"alpha beta\" count=42"
	dec := logfmt.NewDecoder(strings.NewReader(rawInput))
	if !dec.ScanRecord() {
		fmt.Fprintf(os.Stderr, "expected ScanRecord true\n")
		os.Exit(1)
	}
	if !dec.ScanKeyval() || string(dec.Key()) != "tag" || string(dec.Value()) != "alpha beta" {
		fmt.Fprintf(os.Stderr, "keyval 1 mismatch: key=%s, val=%s\n", dec.Key(), dec.Value())
		os.Exit(1)
	}
	if !dec.ScanKeyval() || string(dec.Key()) != "count" || string(dec.Value()) != "42" {
		fmt.Fprintf(os.Stderr, "keyval 2 mismatch: key=%s, val=%s\n", dec.Key(), dec.Value())
		os.Exit(1)
	}
	if err := dec.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "dec.Err() unexpected: %v\n", err)
		os.Exit(1)
	}

	// Assertion 5: logfmt.NewDecoder returns false without error on empty input or EOF
	emptyDec := logfmt.NewDecoder(strings.NewReader(""))
	if emptyDec.ScanRecord() {
		fmt.Fprintf(os.Stderr, "expected false on empty ScanRecord\n")
		os.Exit(1)
	}
	if err := emptyDec.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "expected nil error on empty input, got %v\n", err)
		os.Exit(1)
	}

	// Helper round-trip check
	res, err := sample.FormatAndParse("status", "healthy", "code", 200)
	if err != nil {
		fmt.Fprintf(os.Stderr, "FormatAndParse failed: %v\n", err)
		os.Exit(1)
	}
	if res["status"] != "healthy" || res["code"] != "200" {
		fmt.Fprintf(os.Stderr, "FormatAndParse result mismatch: %+v\n", res)
		os.Exit(1)
	}

	fmt.Println("All contract assertions passed.")
}

Seeder de origem

anônimo