# spf13/pflag architecture

> Architecture diagram of the GitHub repository spf13/pflag, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-05-08). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/spf13/pflag
- Repository: https://github.com/spf13/pflag

## Overview

##### Project type and purpose
- This is a Go library (module) providing a drop-in, POSIX/GNU-style replacement for Go’s standard `flag` package. It parses command-line arguments into typed Go variables, supports shorthands, normalization, deprecation, and integrates with the built-in `flag` package.

##### File structure
- Top-level `.go` files are grouped by functionality:
- `flag.go`, `golangflag.go` – public API, `FlagSet` definition, top-level functions, integration hooks
- `*.go` and `*_slice.go` files – implementations of the `Value` interface for each primitive type (bool, int, string, duration, IP, etc.)
- `errors.go` – parsing and validation errors
- `count.go`, `printusage.go`, `export_test.go`, etc. – helpers, usage printing, export tests, examples
- `verify/` scripts – formatting, linting, CI checks
- No frontend/backend split; it’s a single-purpose library.

##### README for additional insights
- Confirms it is a flag-parsing library, drop-in replacement, supports custom Value types, shorthand flags, normalization functions, deprecation, hidden flags, sorting control, and Go flag integration.

##### Main components
a. External System:
- CLI (os.Args) – raw user input
- (Optional) Go’s `flag` package when integrated via `AddGoFlagSet`
b. Core Library:
- Public API Layer (flag.go)
– Top-level functions: `Int()`, `Bool()`, `Var()`, `Parse()`, etc.
– `FlagSet` type and methods
- Parser / Tokenizer (inside `FlagSet.Parse`)
– Scans `os.Args[]`, splits `--flag`, `-f`, `--flag=value`
– Handles terminator `--` and argument ordering
- FlagSet Data Structure
– Map of flag names to `*Flag` structs
– Each `Flag` holds metadata: name, shorthand, default, usage, `Value` interface, NoOptDefVal, deprecation status, hidden status
- Value Interface and Implementations
– Interface `Value` with `Set(string) error`, `String()`
– Type-specific adapters in `bool.go`, `int.go`, `string.go`, `duration.go`, `ip.go`, etc.
– Slice types (`*_slice.go`) for repeated flags
- Normalization Subsystem
– Custom `SetNormalizeFunc` on a `FlagSet`
– Transforms incoming names (`wordSepNormalizeFunc`, aliasing)
- Usage & Help Generator
– `PrintDefaults()`, automatic help text formatting
– Respects sorted/un-sorted (`SortFlags`) and hidden/deprecated flags
c. CI/Quality Gate (outside runtime)
- `verify/` scripts for gofmt, golint
- `.github/workflows/ci.yaml`, Travis config, Go Report Card

##### Relationships and data flow
1. CLI → FlagSet.Parse():
2. Parser → Flag Lookup:
- For each token, lookup by normalized name in FlagSet.map
3. Flag → Value.Set(tokenValue):
- Polymorphic call into type-specific code
- Updates user-provided pointer or slice
4. Post-Parse → FlagSet.Args():
- Returns non-flag arguments
5. Usage/Help:
- FlagSet.PrintDefaults() reads FlagSet.map, formats usage
6. (Optional) Integration with std flag:
- Go’s `flag.CommandLine` added into pflag’s `FlagSet`, then parse

##### Architectural patterns and design principles
- Interface abstraction: `Value` interface for extensibility
- Single responsibility: separate files for each type
- Plugin-style normalization and deprecation via functional hooks
- In-memory data model (map of flags) + procedural parsing

## Diagram (Mermaid)

```mermaid
flowchart TB
    CLI["CLI / os.Args"]:::external

    subgraph "Runtime"
        subgraph "Public API Layer"
            API_flag["flag.go"]:::public
            API_go["golangflag.go"]:::public
        end

        subgraph "Parsing & Data"
            Parser["Parser / Tokenizer"]:::core
            DataStore["FlagSet Data Store"]:::core
            Error["Error Handling"]:::aux
        end

        subgraph "Value Handling"
            Interface["Value Interface"]:::core
            subgraph "Primitive Values"
                Bool["bool.go"]:::core
                Int["int.go"]:::core
                String["string.go"]:::core
            end
            subgraph "Slice Values"
                BoolS["bool_slice.go"]:::core
                StringS["string_slice.go"]:::core
            end
        end

        subgraph "Auxiliary"
            Normalization["Normalization Subsystem"]:::aux
            Usage["Usage & Help Generator"]:::aux
        end

        GoFlag["Go flag integration"]:::external
    end

    CI["CI / Quality Gate"]:::external

    CLI -->|"os.Args tokens"| Parser
    Parser -->|"lookup token"| DataStore
    Parser -->|"error detection"| Error
    DataStore -->|"retrieve Value"| Interface
    Interface -->|"Set(string) call"| Bool
    Interface -->|"Set(string) call"| Int
    Interface -->|"Set(string) call"| String
    Interface -->|"Set(string) call"| BoolS
    Interface -->|"Set(string) call"| StringS
    DataStore -->|"format usage"| Usage
    GoFlag -.->|"AddGoFlagSet hook"| API_go

    click API_flag "https://github.com/spf13/pflag/blob/master/flag.go"
    click API_go "https://github.com/spf13/pflag/blob/master/golangflag.go"
    click Parser "https://github.com/spf13/pflag/blob/master/flag.go"
    click DataStore "https://github.com/spf13/pflag/blob/master/flag.go"
    click Interface "https://github.com/spf13/pflag/blob/master/flag.go"
    click Bool "https://github.com/spf13/pflag/blob/master/bool.go"
    click Int "https://github.com/spf13/pflag/blob/master/int.go"
    click String "https://github.com/spf13/pflag/blob/master/string.go"
    click BoolS "https://github.com/spf13/pflag/blob/master/bool_slice.go"
    click StringS "https://github.com/spf13/pflag/blob/master/string_slice.go"
    click Normalization "https://github.com/spf13/pflag/blob/master/flag.go"
    click Usage "https://github.com/spf13/pflag/blob/master/count.go"
    click Error "https://github.com/spf13/pflag/blob/master/errors.go"
    click CI "https://github.com/spf13/pflag/tree/master/verify/"

    classDef core fill:#cce5ff,stroke:#004085;
    classDef public fill:#d4edda,stroke:#155724;
    classDef aux fill:#fff3cd,stroke:#856404;
    classDef external fill:#e2e3e5,stroke:#6c757d;
```
