CodeSampleX

サンプル

github.com/go-logfmt/logfmt v0.6.0: MarshalKeyvals, NewDecoder

検証済みサンプル — golang github.com/go-logfmt/logfmt v0.6.0: MarshalKeyvals, NewDecoder. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました.

sha256:affb4bd7f782aaf547e162386c172bb40d0487f49756f87b8a4a87fb03eb72a8

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
1
ビルドした署名鍵
1
宣言された環境 linux 24 · ubuntu · glibc 2.39 x64 go

検証実行環境

環境 コントラクト ステージ 実行日
go 1.26 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1golang:1.26-alpine@sha256:28d89ee9cc0f…
2026-08-27

ケース

HOW
ゴール
verify pkg:golang/github.com/go-logfmt/logfmt@v0.6.0
パッケージ
シンボル
  • github.com/go-logfmt/logfmt.MarshalKeyvals
  • github.com/go-logfmt/logfmt.NewDecoder
作成日
2026-08-27T21:49:51Z

コントラクト

  1. logfmt.MarshalKeyvals serializes variadic key-value pairs into logfmt format without trailing newline
  2. logfmt.MarshalKeyvals correctly formats and quotes values containing spaces, quotes, and newlines
  3. logfmt.MarshalKeyvals formats types including booleans, errors, time.Time, and fmt.Stringer
  4. logfmt.MarshalKeyvals returns ErrNilKey when a nil key is provided
  5. logfmt.MarshalKeyvals returns ErrInvalidKey when a key contains only invalid runes like spaces or equals
  6. logfmt.MarshalKeyvals handles odd number of arguments by appending null value
  7. Helper functions in sample package perform round-trip encoding and parsing accurately

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • sample.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 pkg:golang/github.com/go-logfmt/logfmt@v0.6.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/go-logfmt/logfmt@v0.6.0

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:61171752375264ac0164737d57cc9305efedafc9534a6fde6e9ad4391731faf5","contract":["logfmt.MarshalKeyvals serializes variadic key-value pairs into logfmt format without trailing newline","logfmt.MarshalKeyvals correctly formats and quotes values containing spaces, quotes, and newlines","logfmt.MarshalKeyvals formats types including booleans, errors, time.Time, and fmt.Stringer","logfmt.MarshalKeyvals returns ErrNilKey when a nil key is provided","logfmt.MarshalKeyvals returns ErrInvalidKey when a key contains only invalid runes like spaces or equals","logfmt.MarshalKeyvals handles odd number of arguments by appending null value","Helper functions in sample package perform round-trip encoding and parsing accurately"],"goal":"verify pkg:golang/github.com/go-logfmt/logfmt@v0.6.0","kind":"HOW","packages":["pkg:golang/github.com/go-logfmt/logfmt@v0.6.0"],"schemaVersion":1,"symbols":["github.com/go-logfmt/logfmt.MarshalKeyvals","github.com/go-logfmt/logfmt.NewDecoder"]},"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.6.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/go-logfmt/logfmt@v0.6.0","symbols":["github.com/go-logfmt/logfmt.MarshalKeyvals","github.com/go-logfmt/logfmt.NewDecoder"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.22

require github.com/go-logfmt/logfmt v0.6.0 // indirect
go.sum
github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4=
github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs=
sample.go
package sample

import (
	"bytes"
	"fmt"

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

// FormatLog formats alternating key-value pairs into a logfmt byte slice.
func FormatLog(keyvals ...interface{}) ([]byte, error) {
	return logfmt.MarshalKeyvals(keyvals...)
}

// FormatLogString formats alternating key-value pairs into a logfmt string.
func FormatLogString(keyvals ...interface{}) (string, error) {
	b, err := logfmt.MarshalKeyvals(keyvals...)
	if err != nil {
		return "", err
	}
	return string(b), nil
}

// ParseLogRecord parses a single logfmt record into a map of string key-values.
func ParseLogRecord(data []byte) (map[string]string, error) {
	dec := logfmt.NewDecoder(bytes.NewReader(data))
	res := make(map[string]string)
	if dec.ScanRecord() {
		for dec.ScanKeyval() {
			res[string(dec.Key())] = string(dec.Value())
		}
	}
	if err := dec.Err(); err != nil {
		return nil, fmt.Errorf("decode error: %w", err)
	}
	return res, nil
}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/go-logfmt/logfmt@v0.6.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/go-logfmt/logfmt@v0.6.0"
  ]
}
test/contract.go
package main

import (
	"bytes"
	"errors"
	"fmt"
	"os"
	"strings"
	"time"

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

type customStringer struct {
	val string
}

func (c customStringer) String() string {
	return c.val
}

func main() {
	// Assertion 1: logfmt.MarshalKeyvals serializes variadic key-value pairs into logfmt format without trailing newline
	b1, err := logfmt.MarshalKeyvals("level", "info", "app", "demo", "count", 42)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 1 error: %v\n", err)
		os.Exit(1)
	}
	expected1 := "level=info app=demo count=42"
	if string(b1) != expected1 {
		fmt.Fprintf(os.Stderr, "assertion 1 mismatch: got %q, expected %q\n", string(b1), expected1)
		os.Exit(1)
	}
	if bytes.HasSuffix(b1, []byte("\n")) {
		fmt.Fprintf(os.Stderr, "assertion 1 failed: MarshalKeyvals should not append a trailing newline\n")
		os.Exit(1)
	}

	// Assertion 2: logfmt.MarshalKeyvals correctly formats and quotes values containing spaces, quotes, and newlines
	b2, err := logfmt.MarshalKeyvals("msg", "hello world", "quote", `quoted "value"`, "newline", "line1\nline2")
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 2 error: %v\n", err)
		os.Exit(1)
	}
	got2 := string(b2)
	if !strings.Contains(got2, `msg="hello world"`) {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected quoted spaces in msg, got %q\n", got2)
		os.Exit(1)
	}
	if !strings.Contains(got2, `quote="quoted \"value\""`) {
		fmt.Fprintf(os.Stderr, "assertion 2 failed: expected escaped quotes, got %q\n", got2)
		os.Exit(1)
	}

	// Assertion 3: logfmt.MarshalKeyvals formats types including booleans, errors, time.Time, and fmt.Stringer
	ts := time.Date(2026, 8, 27, 12, 0, 0, 0, time.UTC)
	testErr := errors.New("connection reset")
	stringer := customStringer{val: "custom-val"}
	b3, err := logfmt.MarshalKeyvals("time", ts, "active", true, "err", testErr, "custom", stringer)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 3 error: %v\n", err)
		os.Exit(1)
	}
	got3 := string(b3)
	expected3 := "time=2026-08-27T12:00:00Z active=true err=\"connection reset\" custom=custom-val"
	if got3 != expected3 {
		fmt.Fprintf(os.Stderr, "assertion 3 mismatch: got %q, expected %q\n", got3, expected3)
		os.Exit(1)
	}

	// Assertion 4: logfmt.MarshalKeyvals returns ErrNilKey when a nil key is provided
	_, errNil := logfmt.MarshalKeyvals(nil, "value")
	if !errors.Is(errNil, logfmt.ErrNilKey) {
		fmt.Fprintf(os.Stderr, "assertion 4 failed: expected ErrNilKey, got %v\n", errNil)
		os.Exit(1)
	}

	// Assertion 5: logfmt.MarshalKeyvals returns ErrInvalidKey when a key contains only invalid runes like spaces or equals
	_, errInvalid := logfmt.MarshalKeyvals("   ", "value")
	if !errors.Is(errInvalid, logfmt.ErrInvalidKey) {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: expected ErrInvalidKey for whitespace key, got %v\n", errInvalid)
		os.Exit(1)
	}
	_, errInvalidEq := logfmt.MarshalKeyvals("=", "value")
	if !errors.Is(errInvalidEq, logfmt.ErrInvalidKey) {
		fmt.Fprintf(os.Stderr, "assertion 5 failed: expected ErrInvalidKey for equals key, got %v\n", errInvalidEq)
		os.Exit(1)
	}

	// Assertion 6: logfmt.MarshalKeyvals handles odd number of arguments by appending null value
	bOdd, errOdd := logfmt.MarshalKeyvals("key1", "val1", "key2")
	if errOdd != nil {
		fmt.Fprintf(os.Stderr, "assertion 6 failed with error: %v\n", errOdd)
		os.Exit(1)
	}
	if string(bOdd) != "key1=val1 key2=null" {
		fmt.Fprintf(os.Stderr, "assertion 6 mismatch: got %q, expected %q\n", string(bOdd), "key1=val1 key2=null")
		os.Exit(1)
	}

	// Assertion 7: Helper functions in sample package perform round-trip encoding and parsing accurately
	formattedStr, err := sample.FormatLogString("service", "auth", "status", "success", "latency_ms", 15)
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 7 format error: %v\n", err)
		os.Exit(1)
	}
	parsedMap, err := sample.ParseLogRecord([]byte(formattedStr))
	if err != nil {
		fmt.Fprintf(os.Stderr, "assertion 7 parse error: %v\n", err)
		os.Exit(1)
	}
	if parsedMap["service"] != "auth" || parsedMap["status"] != "success" || parsedMap["latency_ms"] != "15" {
		fmt.Fprintf(os.Stderr, "assertion 7 parsed content mismatch: %+v\n", parsedMap)
		os.Exit(1)
	}

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

オリジンシーダー

匿名