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

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. 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
}

오리진 시더

익명