CodeSampleX

Ejemplo

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

Muestra verificada para golang github.com/go-logfmt/logfmt v0.5.0: NewDecoder, NewEncoder. El contrato se ejecutó en go 1.26 · linux debian/x64 · docker y…

sha256:b930a6892e863e24e66cad9ef7a0e840aec7a61f8f2728be92906c300654cb05

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado linux 24 · ubuntu · glibc 2.39 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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
Paquetes
Símbolos
  • github.com/go-logfmt/logfmt.NewDecoder
  • github.com/go-logfmt/logfmt.NewEncoder
Creado
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

Archivos

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

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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 origen

anónimo