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. contract 在 go 1.26 · linux…

sha256:fb27f4cd8cbfb6386c53db688bd842e4e12f7cf1f8c05de50a4f5825bb3e3869

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 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"
  }
}

原始种子者

匿名