CodeSampleX

샘플

github.com/spf13/pflag v1.0.10: Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc

검증된 샘플 — golang github.com/spf13/pflag v1.0.10: Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc. go 1.26 · linux alpine/x64…

sha256:fb27f4cd8cbfb6386c53db688bd842e4e12f7cf1f8c05de50a4f5825bb3e3869

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

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
1
빌드한 서명 키
1
선언된 환경 go linux x64 go go 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-24

케이스

HOW
목표
Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc
패키지
심벌
  • FlagSet.GetNormalizeFunc
  • FlagSet.SetNormalizeFunc
  • pflag.NormalizedName
환경
go
생성일
2026-08-24T20:14:29Z

컨트랙트

  1. FlagSet.SetNormalizeFunc installs a custom name normalizer that maps alternative flag name variations during lookup and parsing.
  2. FlagSet.Lookup retrieves flag definitions using either the original or normalized flag name variants.
  3. FlagSet.Parse matches command-line arguments written with underscores to flags registered with hyphens and sets their values correctly.
  4. FlagSet.GetNormalizeFunc returns the active normalization function, allowing direct invocation for custom name translation.

파일

  • NOTES.md
  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • pflag_normalize_test.go
  • spec.json

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# Pflag Flag Name Normalization

## Prior Known Solutions
Querying known solutions for `github.com/spf13/pflag` returned:
- `sha256:d9d94f11d549d441519ec42e430f9e260ef572e5567621c82600fc80589b916d` (`FlagSet.SetInterspersed` argument parsing)
- `sha256:922657434b0768a0eafcdc138f53352c18de04eed8a691e1eba5c1a138954b04` (`ParseErrorsWhitelist.UnknownFlags` behavior)
- `sha256:c9dd90f107cef94c692f4dacfe5493d77b1416bcc38e116f18a0e4fc768304dc` (wrapped `ErrHelp` under `ExitOnError`)

This sample targets `FlagSet.SetNormalizeFunc`, `FlagSet.GetNormalizeFunc`, and `pflag.NormalizedName` to normalize flag names across hyphens and underscores during flag registration, lookup, and parsing.

## Pinned Release
- Package: `github.com/spf13/pflag`
- Version: `v1.0.10`

## Observed Behavior
1. `FlagSet.SetNormalizeFunc` installs a translation function `func(f *pflag.FlagSet, name string) pflag.NormalizedName` that is applied whenever flag names are defined, looked up, or parsed from the command line.
2. When normalize translates underscores (`_`) to hyphens (`-`), flags registered with hyphens (e.g. `--output-format`) can be looked up via `FlagSet.Lookup("output_format")` or parsed from CLI arguments formatted as `--output_format=json`.
3. `FlagSet.GetNormalizeFunc` returns the currently installed normalize function.
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: Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/spf13/pflag@v1.0.10
Demonstrate these symbols/APIs:
  - FlagSet.GetNormalizeFunc
  - FlagSet.SetNormalizeFunc
  - pflag.NormalizedName
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

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:76a4839124ce631499ce1f893ade57509aec4320294db6c2fb6bf41b821bc03c","contract":["FlagSet.SetNormalizeFunc installs a custom name normalizer that maps alternative flag name variations during lookup and parsing.","FlagSet.Lookup retrieves flag definitions using either the original or normalized flag name variants.","FlagSet.Parse matches command-line arguments written with underscores to flags registered with hyphens and sets their values correctly.","FlagSet.GetNormalizeFunc returns the active normalization function, allowing direct invocation for custom name translation."],"goal":"Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc","kind":"HOW","packages":["pkg:golang/github.com/spf13/pflag@v1.0.10"],"schemaVersion":1,"symbols":["FlagSet.GetNormalizeFunc","FlagSet.SetNormalizeFunc","pflag.NormalizedName"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/spf13/pflag@v1.0.10"],"schemaVersion":1,"symbols":["FlagSet.GetNormalizeFunc","FlagSet.SetNormalizeFunc","pflag.NormalizedName"],"verifierAdapter":"golang@1"}
go.mod
module example.com/pflag-normalize

go 1.22

require github.com/spf13/pflag v1.0.10
go.sum
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
pflag_normalize_test.go
package main

import (
	"strings"
	"testing"

	"github.com/spf13/pflag"
)

// wordSepNormalizeFunc translates underscores to hyphens for flag name normalization.
func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
	return pflag.NormalizedName(strings.ReplaceAll(name, "_", "-"))
}

func TestSetNormalizeFuncLookupAndParsing(t *testing.T) {
	fs := pflag.NewFlagSet("test_normalize", pflag.ContinueOnError)

	// Install custom normalize function
	fs.SetNormalizeFunc(wordSepNormalizeFunc)

	var outputFormat string
	var maxRetries int
	var verbose bool

	// Register flags using hyphenated and underscore naming conventions
	fs.StringVar(&outputFormat, "output-format", "table", "Output format")
	fs.IntVar(&maxRetries, "max_retries", 3, "Max retry attempts")
	fs.BoolVarP(&verbose, "verbose-logging", "v", false, "Verbose logging")

	// 1. Verify FlagSet.Lookup resolves both underscore and hyphen forms
	flagOutput := fs.Lookup("output_format")
	if flagOutput == nil || flagOutput.Name != "output-format" {
		t.Fatalf("expected Lookup(output_format) to return output-format flag, got %v", flagOutput)
	}

	flagRetries := fs.Lookup("max-retries")
	if flagRetries == nil || flagRetries.Name != "max-retries" {
		t.Fatalf("expected Lookup(max-retries) to return max-retries flag, got %v", flagRetries)
	}

	// 2. Verify FlagSet.Parse accepts CLI flags with alternate naming delimiters
	args := []string{"--output_format=json", "--max-retries=10", "-v"}
	if err := fs.Parse(args); err != nil {
		t.Fatalf("unexpected parse error: %v", err)
	}

	if outputFormat != "json" {
		t.Fatalf("expected outputFormat 'json', got %q", outputFormat)
	}
	if maxRetries != 10 {
		t.Fatalf("expected maxRetries 10, got %d", maxRetries)
	}
	if !verbose {
		t.Fatalf("expected verbose true, got false")
	}

	// 3. Verify shorthand lookup continues to function alongside normalization
	shorthandFlag := fs.ShorthandLookup("v")
	if shorthandFlag == nil || shorthandFlag.Name != "verbose-logging" {
		t.Fatalf("expected ShorthandLookup(v) to resolve verbose-logging flag, got %v", shorthandFlag)
	}
}

func TestGetNormalizeFunc(t *testing.T) {
	fs := pflag.NewFlagSet("test_get_normalize", pflag.ContinueOnError)

	// Install normalize function
	fs.SetNormalizeFunc(wordSepNormalizeFunc)

	fn := fs.GetNormalizeFunc()
	if fn == nil {
		t.Fatal("expected GetNormalizeFunc to return a non-nil function")
	}

	normalized := fn(fs, "custom_flag_name")
	if normalized != "custom-flag-name" {
		t.Fatalf("expected normalized name 'custom-flag-name', got %q", normalized)
	}
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/spf13/pflag@v1.0.10"
  ],
  "symbols": [
    "FlagSet.GetNormalizeFunc",
    "FlagSet.SetNormalizeFunc",
    "pflag.NormalizedName"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}

오리진 시더

익명