CodeSampleX

Ejemplo

github.com/spf13/pflag v1.0.6: Parse command line flags with shorthand and default values using FlagSet

Muestra verificada para golang github.com/spf13/pflag v1.0.6: Parse command line flags with shorthand and default values using FlagSet. El contrato se…

sha256:11618d8c713d6b6b8f7615d92d1cbe7ecfa82458b07151cb3b9ba6ce01fd4d22

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado windows 11 x64 go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-19

Caso

HOW
Objetivo
Parse command line flags with shorthand and default values using FlagSet
Paquetes
Símbolos
  • FlagSet.BoolVarP
  • FlagSet.IntVarP
  • FlagSet.Parse
  • FlagSet.StringVarP
Creado
2026-08-18T17:46:57Z

Contrato

  1. FlagSet.StringVarP binds string flag with long and shorthand names and falls back to default value
  2. FlagSet.IntVarP binds integer flag with long and shorthand names and parses integer values correctly
  3. FlagSet.BoolVarP binds boolean flag with long and shorthand names and parses boolean values correctly
  4. FlagSet.Parse parses argument slice and sets bound variables without error on valid input

Archivos

  • PROMPT.md
  • csx.json
  • go.mod
  • go.sum
  • main.go
  • spec.json
  • test/main.go

Descargar el artefacto de código fuente (tar.gz)

Código fuente

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: Parse command line flags with shorthand and default values using FlagSet
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:golang/github.com/spf13/pflag@v1.0.6
Demonstrate these symbols/APIs:
  - FlagSet.BoolVarP
  - FlagSet.IntVarP
  - FlagSet.Parse
  - FlagSet.StringVarP

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:b269470dbe4cc35f16a9130d14f9a94d8efc01db5a09689cd48c09b59ac0cc75","contract":["FlagSet.StringVarP binds string flag with long and shorthand names and falls back to default value","FlagSet.IntVarP binds integer flag with long and shorthand names and parses integer values correctly","FlagSet.BoolVarP binds boolean flag with long and shorthand names and parses boolean values correctly","FlagSet.Parse parses argument slice and sets bound variables without error on valid input"],"goal":"Parse command line flags with shorthand and default values using FlagSet","kind":"HOW","packages":["pkg:golang/github.com/spf13/pflag@v1.0.6"],"schemaVersion":1,"symbols":["FlagSet.BoolVarP","FlagSet.IntVarP","FlagSet.Parse","FlagSet.StringVarP"]},"contractCommand":["go","run","./test"],"environment":{"arch":"x64","ecosystem":"golang","os":"windows","osVersionBucket":"11","packageManager":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/github.com/spf13/pflag@v1.0.6"],"schemaVersion":1,"symbols":["FlagSet.BoolVarP","FlagSet.IntVarP","FlagSet.Parse","FlagSet.StringVarP"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.5

require github.com/spf13/pflag v1.0.6
go.sum
github.com/spf13/pflag v1.0.6 h1:jFzHGLGAlb3ruxLB8MhbI6A8+AQX/2eW4qeyNZXNp2o=
github.com/spf13/pflag v1.0.6/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
main.go
package main

import (
	"fmt"
	"os"

	"github.com/spf13/pflag"
)

func main() {
	var host string
	var port int
	var verbose bool

	fs := pflag.NewFlagSet("server", pflag.ContinueOnError)
	fs.StringVarP(&host, "host", "h", "localhost", "Server listen address")
	fs.IntVarP(&port, "port", "p", 8080, "Server listen port")
	fs.BoolVarP(&verbose, "verbose", "v", false, "Enable verbose logging")

	args := os.Args[1:]
	if err := fs.Parse(args); err != nil {
		fmt.Fprintf(os.Stderr, "Error parsing flags: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Host: %s\n", host)
	fmt.Printf("Port: %d\n", port)
	fmt.Printf("Verbose: %t\n", verbose)
}
spec.json
{
  "schemaVersion": 1,
  "goal": "Parse command line flags with shorthand and default values using FlagSet",
  "kind": "HOW",
  "packages": [
    "pkg:golang/github.com/spf13/pflag@v1.0.6"
  ],
  "symbols": [
    "FlagSet.BoolVarP",
    "FlagSet.IntVarP",
    "FlagSet.Parse",
    "FlagSet.StringVarP"
  ]
}
test/main.go
package main

import (
	"fmt"
	"os"

	"github.com/spf13/pflag"
)

func main() {
	// Case 1: Default values when no flags are supplied
	{
		var host string
		var port int
		var verbose bool

		fs := pflag.NewFlagSet("test_default", pflag.ContinueOnError)
		fs.StringVarP(&host, "host", "h", "localhost", "listen host")
		fs.IntVarP(&port, "port", "p", 8080, "listen port")
		fs.BoolVarP(&verbose, "verbose", "v", false, "verbose output")

		if err := fs.Parse([]string{}); err != nil {
			fmt.Fprintf(os.Stderr, "Contract failure: empty parse failed: %v\n", err)
			os.Exit(1)
		}

		if host != "localhost" {
			fmt.Fprintf(os.Stderr, "Contract failure: expected default host 'localhost', got '%s'\n", host)
			os.Exit(1)
		}
		if port != 8080 {
			fmt.Fprintf(os.Stderr, "Contract failure: expected default port 8080, got %d\n", port)
			os.Exit(1)
		}
		if verbose != false {
			fmt.Fprintf(os.Stderr, "Contract failure: expected default verbose false, got %t\n", verbose)
			os.Exit(1)
		}
	}

	// Case 2: Long flags parsing
	{
		var host string
		var port int
		var verbose bool

		fs := pflag.NewFlagSet("test_long", pflag.ContinueOnError)
		fs.StringVarP(&host, "host", "h", "localhost", "listen host")
		fs.IntVarP(&port, "port", "p", 8080, "listen port")
		fs.BoolVarP(&verbose, "verbose", "v", false, "verbose output")

		args := []string{"--host", "127.0.0.1", "--port", "9000", "--verbose"}
		if err := fs.Parse(args); err != nil {
			fmt.Fprintf(os.Stderr, "Contract failure: long flags parse failed: %v\n", err)
			os.Exit(1)
		}

		if host != "127.0.0.1" {
			fmt.Fprintf(os.Stderr, "Contract failure: expected host '127.0.0.1', got '%s'\n", host)
			os.Exit(1)
		}
		if port != 9000 {
			fmt.Fprintf(os.Stderr, "Contract failure: expected port 9000, got %d\n", port)
			os.Exit(1)
		}
		if verbose != true {
			fmt.Fprintf(os.Stderr, "Contract failure: expected verbose true, got %t\n", verbose)
			os.Exit(1)
		}
	}

	// Case 3: Shorthand flags parsing
	{
		var host string
		var port int
		var verbose bool

		fs := pflag.NewFlagSet("test_short", pflag.ContinueOnError)
		fs.StringVarP(&host, "host", "h", "0.0.0.0", "listen host")
		fs.IntVarP(&port, "port", "p", 3000, "listen port")
		fs.BoolVarP(&verbose, "verbose", "v", true, "verbose output")

		args := []string{"-h", "example.com", "-p", "443", "-v=false"}
		if err := fs.Parse(args); err != nil {
			fmt.Fprintf(os.Stderr, "Contract failure: shorthand flags parse failed: %v\n", err)
			os.Exit(1)
		}

		if host != "example.com" {
			fmt.Fprintf(os.Stderr, "Contract failure: expected host 'example.com', got '%s'\n", host)
			os.Exit(1)
		}
		if port != 443 {
			fmt.Fprintf(os.Stderr, "Contract failure: expected port 443, got %d\n", port)
			os.Exit(1)
		}
		if verbose != false {
			fmt.Fprintf(os.Stderr, "Contract failure: expected verbose false, got %t\n", verbose)
			os.Exit(1)
		}
	}

	// Case 4: Non-flag arguments handling
	{
		var host string
		fs := pflag.NewFlagSet("test_args", pflag.ContinueOnError)
		fs.StringVarP(&host, "host", "h", "localhost", "listen host")

		args := []string{"--host", "node1", "extra1", "extra2"}
		if err := fs.Parse(args); err != nil {
			fmt.Fprintf(os.Stderr, "Contract failure: parse with extra args failed: %v\n", err)
			os.Exit(1)
		}

		if host != "node1" {
			fmt.Fprintf(os.Stderr, "Contract failure: expected host 'node1', got '%s'\n", host)
			os.Exit(1)
		}

		remaining := fs.Args()
		if len(remaining) != 2 || remaining[0] != "extra1" || remaining[1] != "extra2" {
			fmt.Fprintf(os.Stderr, "Contract failure: unexpected remaining args %v\n", remaining)
			os.Exit(1)
		}
	}

	// Case 5: Error handling on unknown flag and invalid int syntax
	{
		var port int
		fs := pflag.NewFlagSet("test_error", pflag.ContinueOnError)
		fs.IntVarP(&port, "port", "p", 8080, "listen port")

		if err := fs.Parse([]string{"--invalid-flag"}); err == nil {
			fmt.Fprintf(os.Stderr, "Contract failure: expected error on unknown flag, got nil\n")
			os.Exit(1)
		}

		if err := fs.Parse([]string{"--port", "not-a-number"}); err == nil {
			fmt.Fprintf(os.Stderr, "Contract failure: expected error on non-integer port, got nil\n")
			os.Exit(1)
		}
	}

	fmt.Println("PASS: all pflag FlagSet contract assertions passed")
}

Seeder de origen

anónimo