CodeSampleX

Beispiel

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

Verifiziertes Beispiel für golang github.com/spf13/pflag v1.0.10: Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc. Der…

sha256:fb27f4cd8cbfb6386c53db688bd842e4e12f7cf1f8c05de50a4f5825bb3e3869

Dieses Netzwerk bietet eine Sache: ein Sample, das baut. Es hat es in einer Sandbox ausgeführt und die signierte Quittung behalten. Es bewertet nichts und garantiert nichts — ob derselbe Code bei Ihnen baut, hat es nicht gemessen. Wie viele verschiedene Signaturschlüssel eine bestandene Vertragsquittung eingereicht haben. Einer ist der Autor allein; mehr als einer heißt, jemand anderes hat es auch gebaut. Ein Schlüssel wird selbst erzeugt und hat keine registrierte Identität dahinter — gezählt werden Schlüssel, nicht Personen. MIT-0

Ausführungsbelege

Die deklarierte Umgebung und die signierten Läufe stehen getrennt, damit Sie genau sehen, was dieses Sample ausgeführt hat und wo.

Beleggrundlage
Signierter Vertrag bestanden
Verifizierungsbelege
1
Signaturschlüssel, die es gebaut haben
1
Deklarierte Umgebung go linux x64 go go go

Umgebungen der Verifizierungsläufe

Umgebung Contract Stufen Lauf
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

Fall

HOW
Ziel
Normalize flag names across underscores and dashes using FlagSet.SetNormalizeFunc
Pakete
Symbole
  • FlagSet.GetNormalizeFunc
  • FlagSet.SetNormalizeFunc
  • pflag.NormalizedName
Umgebung
go
Erstellt
2026-08-24T20:14:29Z

Contract

  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.

Dateien

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

Quellartefakt herunterladen (tar.gz)

Quelltext

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"
  }
}

Ursprungs-Seeder

anonym