CodeSampleX

サンプル

github.com/lmittmann/tint v1.2.0

検証済みサンプル — golang github.com/lmittmann/tint v1.2.0. go 1.26 · linux alpine/x64 · docker で contract を実行し、成功しました: tint.NewTextHandler writes formatted slog…

sha256:79e2dc52cad326ab04cf907abc24c51c83e322eb98d7536d01cc40fa70d1e747

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

実行証拠

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

証拠の基準
署名済みコントラクト合格
検証レシート
2
ビルドした署名鍵
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-23
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-07

ケース

HOW
ゴール
verify pkg:golang/github.com/lmittmann/tint@v1.2.0
パッケージ
作成日
2026-08-23T06:11:21Z

コントラクト

  1. tint.NewTextHandler writes formatted slog records with 3-letter level prefixes (INF, WRN, ERR, DBG) and defaults to slog.LevelInfo
  2. Options.NoColor suppresses all ANSI escape sequences while preserving record structure and spacing
  3. Options.Level accepts an slog.LevelVar and dynamically filters logs based on the current level value
  4. Handler.WithAttrs pre-encodes attributes and Handler.WithGroup creates dot-separated prefixes for subsequent attributes
  5. Calling Handler.WithGroup with an empty string returns the handler unmodified without altering group prefixes
  6. tint.Attr attaches an 8-bit ANSI color to an attribute value and tint.Err creates an err attribute tinted in bright red (ANSI 9)
  7. Options.AddSource includes caller source file and line number in the log output
  8. Options.ReplaceAttr intercepts attributes allowing value transformation and attribute suppression by returning an empty slog.Attr
  9. appendValue safely recovers from panicking TextMarshaler or stringifier methods, emitting !PANIC instead of crashing the program

ファイル

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • spec.json
  • test/main.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/lmittmann/tint@v1.2.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/lmittmann/tint@v1.2.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:6d02aa54a417f215395045ebdfe663ca637cd4906996f2ff7b323a2c6446c343","contract":["tint.NewTextHandler writes formatted slog records with 3-letter level prefixes (INF, WRN, ERR, DBG) and defaults to slog.LevelInfo","Options.NoColor suppresses all ANSI escape sequences while preserving record structure and spacing","Options.Level accepts an slog.LevelVar and dynamically filters logs based on the current level value","Handler.WithAttrs pre-encodes attributes and Handler.WithGroup creates dot-separated prefixes for subsequent attributes","Calling Handler.WithGroup with an empty string returns the handler unmodified without altering group prefixes","tint.Attr attaches an 8-bit ANSI color to an attribute value and tint.Err creates an err attribute tinted in bright red (ANSI 9)","Options.AddSource includes caller source file and line number in the log output","Options.ReplaceAttr intercepts attributes allowing value transformation and attribute suppression by returning an empty slog.Attr","appendValue safely recovers from panicking TextMarshaler or stringifier methods, emitting !PANIC instead of crashing the program"],"goal":"verify pkg:golang/github.com/lmittmann/tint@v1.2.0","kind":"HOW","packages":["pkg:golang/github.com/lmittmann/tint@v1.2.0"],"schemaVersion":1,"symbols":["tint.Attr","tint.Err","tint.NewTextHandler","tint.Options"]},"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/lmittmann/tint@v1.2.0"],"schemaVersion":1,"subject":"pkg:golang/github.com/lmittmann/tint@v1.2.0","verifierAdapter":"golang@1"}
go.mod
module example.com/sample

go 1.22.0

require github.com/lmittmann/tint v1.2.0
go.sum
github.com/lmittmann/tint v1.2.0 h1:AogHRHy8HUJUnNJBHJlYa+fR4YY8mko2cnCp67xn9JY=
github.com/lmittmann/tint v1.2.0/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE=
spec.json
{
  "schemaVersion": 1,
  "goal": "verify pkg:golang/github.com/lmittmann/tint@v1.2.0",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/lmittmann/tint@v1.2.0"
  ]
}
test/main.go
package main

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"log/slog"
	"os"
	"strings"

	"github.com/lmittmann/tint"
)

type panickingMarshaler struct{}

func (panickingMarshaler) MarshalText() ([]byte, error) {
	panic("marshaling exploded")
}

type dummyNilPtr struct {
	field string
}

func main() {
	if err := runTests(); err != nil {
		fmt.Fprintf(os.Stderr, "Contract test failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("All contract tests passed successfully.")
}

func runTests() error {
	ctx := context.Background()

	// 1. Basic formatting, default level (Info), and NoColor mode
	{
		var buf bytes.Buffer
		h := tint.NewTextHandler(&buf, &tint.Options{
			NoColor:    true,
			TimeFormat: "15:04:05",
		})
		logger := slog.New(h)

		logger.DebugContext(ctx, "debug message should be ignored by default")
		if buf.Len() != 0 {
			return fmt.Errorf("expected debug log to be ignored, got: %q", buf.String())
		}

		logger.InfoContext(ctx, "hello world", "key", "val")
		out := buf.String()
		if !strings.Contains(out, "INF hello world key=val\n") {
			return fmt.Errorf("unexpected info log format: %q", out)
		}
		if strings.Contains(out, "\x1b[") {
			return fmt.Errorf("NoColor output should not contain ANSI codes: %q", out)
		}
	}

	// 2. Dynamic log level adjustment with slog.LevelVar
	{
		var buf bytes.Buffer
		levelVar := &slog.LevelVar{}
		levelVar.Set(slog.LevelInfo)

		h := tint.NewTextHandler(&buf, &tint.Options{
			Level:   levelVar,
			NoColor: true,
		})
		logger := slog.New(h)

		logger.DebugContext(ctx, "should not appear")
		if buf.Len() != 0 {
			return fmt.Errorf("expected debug to be filtered at Info level")
		}

		levelVar.Set(slog.LevelDebug)
		logger.DebugContext(ctx, "debug now active")
		if !strings.Contains(buf.String(), "DBG debug now active\n") {
			return fmt.Errorf("expected debug log after levelVar set to Debug: %q", buf.String())
		}

		buf.Reset()
		levelVar.Set(slog.LevelWarn)
		logger.InfoContext(ctx, "info now filtered")
		if buf.Len() != 0 {
			return fmt.Errorf("expected info log to be filtered at Warn level: %q", buf.String())
		}
	}

	// 3. Group scoping and pre-formatted attributes with WithGroup and WithAttrs
	{
		var buf bytes.Buffer
		h := tint.NewTextHandler(&buf, &tint.Options{
			NoColor: true,
		})
		baseLogger := slog.New(h)

		// WithAttrs
		subLogger := baseLogger.With("app", "testapp")

		// Empty group name should leave handler unaffected
		emptyGroupLogger := subLogger.WithGroup("")
		emptyGroupLogger.InfoContext(ctx, "empty group check", "k1", "v1")
		if !strings.Contains(buf.String(), "app=testapp k1=v1\n") {
			return fmt.Errorf("empty group should not alter keys: %q", buf.String())
		}
		buf.Reset()

		// Nested groups
		groupedLogger := subLogger.WithGroup("req").With("method", "GET").WithGroup("auth")
		groupedLogger.InfoContext(ctx, "authenticated", "user", "alice")
		out := buf.String()
		if !strings.Contains(out, "app=testapp req.method=GET req.auth.user=alice\n") {
			return fmt.Errorf("nested group formatting failed: %q", out)
		}
	}

	// 4. Colorization with tint.Attr and tint.Err
	{
		var buf bytes.Buffer
		h := tint.NewTextHandler(&buf, &tint.Options{
			NoColor: false,
		})
		logger := slog.New(h)

		testErr := errors.New("database connection failed")
		logger.ErrorContext(ctx, "query failed", tint.Err(testErr), tint.Attr(33, slog.String("db", "postgres")))
		out := buf.String()

		// Check for ANSI escape sequences
		if !strings.Contains(out, "\x1b[") {
			return fmt.Errorf("expected ANSI escape sequences in colorized output: %q", out)
		}
		// tint.Err uses ANSI color 9 (bright red)
		if !strings.Contains(out, "\x1b[2;91merr=\x1b[22m\"database connection failed\"\x1b[0m") {
			return fmt.Errorf("tint.Err attribute missing or incorrect: %q", out)
		}
		// tint.Attr uses 8-bit ANSI color 38;5;33
		if !strings.Contains(out, "\x1b[2;38;5;33mdb=\x1b[22mpostgres\x1b[0m") {
			return fmt.Errorf("tint.Attr attribute missing: %q", out)
		}

		// Verify nil error handling in tint.Err
		buf.Reset()
		logger.InfoContext(ctx, "nil error test", tint.Err(nil))
		if !strings.Contains(buf.String(), "\x1b[2;91merr=\x1b[22m<nil>\x1b[0m") {
			return fmt.Errorf("tint.Err(nil) should output err=<nil>: %q", buf.String())
		}
	}

	// 5. Source location with Options.AddSource
	{
		var buf bytes.Buffer
		h := tint.NewTextHandler(&buf, &tint.Options{
			AddSource: true,
			NoColor:   true,
		})
		logger := slog.New(h)

		logger.InfoContext(ctx, "source location test")
		out := buf.String()
		if !strings.Contains(out, "main.go:") {
			return fmt.Errorf("expected source file:line in output when AddSource is true: %q", out)
		}
	}

	// 6. Attribute transformation and suppression with ReplaceAttr
	{
		var buf bytes.Buffer
		h := tint.NewTextHandler(&buf, &tint.Options{
			NoColor: true,
			ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
				if a.Key == "secret" {
					return slog.Attr{} // drop secret attribute
				}
				if a.Key == "env" {
					return slog.String("env", strings.ToUpper(a.Value.String()))
				}
				return a
			},
		})
		logger := slog.New(h)

		logger.InfoContext(ctx, "filter test", "secret", "password123", "env", "prod", "public", "data")
		out := buf.String()
		if strings.Contains(out, "password123") || strings.Contains(out, "secret=") {
			return fmt.Errorf("secret attribute should have been dropped: %q", out)
		}
		if !strings.Contains(out, "env=PROD") {
			return fmt.Errorf("env attribute should have been transformed: %q", out)
		}
		if !strings.Contains(out, "public=data") {
			return fmt.Errorf("public attribute missing: %q", out)
		}
	}

	// 7. Panic recovery for panicking marshaler and nil pointer safety
	{
		var buf bytes.Buffer
		h := tint.NewTextHandler(&buf, &tint.Options{
			NoColor: true,
		})
		logger := slog.New(h)

		logger.InfoContext(ctx, "testing panic resilience", "payload", panickingMarshaler{})
		out := buf.String()
		if !strings.Contains(out, "!PANIC: marshaling exploded") {
			return fmt.Errorf("expected panic recovery output !PANIC: %q", out)
		}

		buf.Reset()
		var nilPtr *dummyNilPtr
		logger.InfoContext(ctx, "nil pointer check", "ptr", nilPtr)
		if !strings.Contains(buf.String(), "ptr=<nil>") {
			return fmt.Errorf("nil pointer should format as <nil>: %q", buf.String())
		}
	}

	return nil
}

オリジンシーダー

匿名