diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..b56faac --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,155 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## What this is + +`forklift` gives Postgres copy-on-write branching: a branch is a COW snapshot of a whole +cluster plus its own compute. Experimental, and deliberately separate from the PostKit +codebase — it exists to test whether branching belongs there. + +## Commands + +```bash +make build # -> bin/forklift +make test # unit tests, no root +make test-integration # storage conformance suite — run WITHOUT sudo +make install # -> /usr/local/bin/forklift (on sudo's secure_path) +make doctor # report this machine's COW capabilities +make vet fmt clean +``` + +Go lives at `/usr/local/go/bin/go` and is often **not** on the default PATH: +`export PATH=$PATH:/usr/local/go/bin`. + +**Never prefix a make target with `sudo`.** Targets that need root elevate +themselves. `sudo` replaces PATH with its `secure_path`, which excludes the Go +toolchain, so `sudo make test-integration` fails with `go: not found` before any +test runs — a failure that has already been misdiagnosed once as "this machine +cannot run the suite". + +Running a single test: + +```bash +go test ./internal/branch/ -run TestValidateName -v +sudo -E env "PATH=$PATH" go test -count=1 ./internal/storage/ -run Conformance -v +``` + +Use `-count=1` on anything you are using as evidence: cached `ok` lines have +already been mistaken for a passing rewrite that the tests never executed. + +Anything that touches the pool (`init`, `create`, `start`, `delete`, and the integration +tests) needs **root** — loop devices, `mount`, btrfs subvolumes. `list`, `inspect` and +`doctor` do not. + +Manual end-to-end check, if you changed storage or compute: + +```bash +sudo ./bin/forklift init && sudo ./bin/forklift create main +sudo ./bin/forklift create agent-a --from main # fork +sudo ./bin/forklift create deep --from agent-a # fork of a fork +sudo ./bin/forklift delete main # must be REFUSED, naming its children +``` + +`scripts/probe-cow.sh` reports a machine's COW capabilities without building; +`scripts/cow-test.sh` is a standalone end-to-end proof needing no Go. + +## Architecture + +### The layer thesis + +"Fork a database" can be built at three depths, and the choice of depth is the whole +design. Logical (rows/DDL, O(data)); **block** (8 KiB pages as device blocks, O(1), +Postgres unmodified); page (page versions by LSN, O(1) at any LSN, but requires patching +Postgres — the `smgr` hook never landed upstream). forklift works at the block layer, and +that constraint explains most decisions here: branches run **stock** `postgres:{version}` +images that have no idea they are on a clone. + +### Three interfaces, one orchestrator + +- `storage.Provider` (`internal/storage/provider.go`) — the COW backend. `btrfs.go` is the + only implementation; dm-thin/ZFS/vendor-API are intended to slot in beside it. +- `compute.Provider` (`internal/compute/docker.go`) — runs Postgres on a branch's data dir. +- `metadata.Repository` (`internal/metadata/repo.go`) — the branch registry (JSON today). + +`internal/manager` is the **only** place that knows the ordering constraints between the +three; `internal/cli` just wires flags. `internal/branch` holds the domain types and has no +dependencies on the others. + +### Invariants worth knowing before changing anything + +**A snapshot must be atomic across the entire PGDATA, including `pg_wal`.** That is what +makes cloning a *running* Postgres safe: the clone finds no `backup_label`, enters ordinary +crash recovery, replays from the last checkpoint, and repairs torn pages from full-page +images. Split PGDATA and WAL across devices and you capture two instants — works in testing, +corrupts under load. `CHECKPOINT` before a fork is an optimisation, never a correctness +requirement. + +**A cloned PGDATA needs fixups before Postgres will start.** `storage.PrepareClone` removes +`postmaster.pid` (snapshotted faithfully, naming a PID still alive in the parent), fixes +ownership, and sets 0700. Every block-level provider must call it — hence its living in +`storage`, not in `btrfs.go`. It must never touch `pg_wal`; the WAL is what makes the clone +recoverable. + +**`branch.ValidateName` must be called at the storage provider boundary**, not only in the +CLI or manager. Names reach `filepath.Join` against the pool root, so an unvalidated name +escapes the pool. `btrfs.go` re-validates every handle it receives, including ones read back +from the registry. + +**The registry must live outside the branchable data.** If branch records lived in the +database being forked, forking it would fork the registry and every child would believe it +was authoritative. This is why `metadata` is a file, not a table. + +**Do not put branch containers on a `--internal` Docker network.** It does isolate egress — +and silently drops published ports, leaving a branch that is healthy and unreachable. Until +an inbound/outbound-aware mechanism exists, Safe Mode has to be enforced inside Postgres +(`archive_mode` off, subscriptions disabled, cron neutered, FDW mappings cleared). Ports +publish on `127.0.0.1` via `Docker.BindHost`; never make that `0.0.0.0` implicitly. + +**Refuse, don't corrupt.** A COW child depends on its parent's blocks, so deleting a parent +with children returns `storage.ErrHasChildren` naming the blockers. Likewise the pool +watermark (`Manager.PoolWatermark`, 85%) fails the *fork* rather than letting a full pool +take running databases read-only. + +**Resolve external binaries through `internal/tool`, never bare `exec.LookPath`.** +`losetup`, `dmsetup` and `mkfs.btrfs` live in `/usr/sbin`, which is off a normal +non-root PATH, so a bare lookup false-negatives for unprivileged callers like +`doctor`. The resolver tries PATH then `/usr/local/sbin`, `/usr/sbin`, `/sbin`. +This is the single most repeated bug in this codebase's history — four separate +instances — and the resolver exists so a new call site cannot reintroduce it. + +**Detection is tri-state: available / unavailable / unknown.** A probe that could +not run for lack of privilege must return `unknown`, never `unavailable`, and +`Best()` must never select an unknown mechanism. Telling someone a mechanism is +unavailable when you merely could not look is worse than saying nothing — they +will go and change their machine to fix a problem that does not exist. + +**Never operate against a Docker daemon the invoking user cannot see.** Under +`sudo`, `docker` talks to root's daemon; a user running rootless Docker or a +non-default context would get branches created somewhere invisible to them. +When `SUDO_USER` is set, compare daemon IDs and refuse on a confirmed mismatch. +Querying the user's daemon needs +`--preserve-env=DOCKER_HOST,DOCKER_CONTEXT,XDG_RUNTIME_DIR`, or you inspect +root's environment and conclude they match when they do not. + +### Adding a storage backend + +Implement `storage.Provider`, add detection to `storage.Detect` with a `Preference` rank, +and make `Conformance` in `internal/storage/conformance_test.go` pass. That suite is the +contract — it covers parent isolation, depth-2 forks, and delete-refusal. Implement +`storage.Teardown` if the backend holds a mount or loop device, or test cleanup fails with +"device or resource busy". + +Mechanism preference is `dm-thin > btrfs > nbd > reflink`. dm-thin ranks first because its +per-device btree keeps read cost flat at any branch depth, where qcow2 backing chains and +classic LVM are O(depth) — but it was **absent on every machine probed so far**, which is +why backends are selected at runtime rather than assumed. + +## Known gaps (see README for detail) + +macOS is untested and is the most valuable open question — the whole portability argument +rests on the pool living inside the Linux VM. No dm-thin backend. No Safe Mode. No +diff/merge, and data merge probably should never be automatic: a three-way comparison sees +values, but an agent's write is a function of the rows it *read*, and that dependency is +invisible at the storage layer. Sibling branches collide on sequence values; the fix belongs +at fork time (disjoint ranges), not merge time. diff --git a/Makefile b/Makefile index 1fdf8f4..3297fcd 100644 --- a/Makefile +++ b/Makefile @@ -2,6 +2,7 @@ BINARY := bin/forklift PKG := ./cmd/forklift VERSION := $(shell git describe --tags --always --dirty 2>/dev/null || echo dev) GO ?= go +PREFIX ?= /usr/local .PHONY: help build install test test-integration vet fmt clean doctor @@ -14,15 +15,31 @@ build: ## Build the binary into bin/ $(GO) build -ldflags "-X main.version=$(VERSION)" -o $(BINARY) $(PKG) @echo "built $(BINARY) ($(VERSION))" -install: ## Install to GOBIN - $(GO) install -ldflags "-X main.version=$(VERSION)" $(PKG) +install: build ## Install to $(PREFIX)/bin (on sudo's secure_path) + @if [ "$$(id -u)" = 0 ]; then \ + install -m 0755 $(BINARY) $(PREFIX)/bin/forklift; \ + else \ + sudo install -m 0755 $(BINARY) $(PREFIX)/bin/forklift; \ + fi + @echo "installed $(PREFIX)/bin/forklift" test: ## Unit tests (no root needed) $(GO) test ./... -test-integration: build ## Storage conformance suite (needs root + btrfs-progs) - @echo "Running as root — the pool needs loop devices and mount." - sudo -E env "PATH=$$PATH" $(GO) test ./internal/storage/ -run Conformance -v +# Run WITHOUT sudo: this recipe elevates itself, forwarding PATH, because sudo +# resets PATH to secure_path and would lose the Go toolchain. +test-integration: ## Storage conformance suite (needs btrfs-progs; elevates itself) + @command -v $(GO) >/dev/null 2>&1 || { \ + echo "go not found on PATH."; \ + echo "If you typed 'sudo make', run 'make test-integration' instead —"; \ + echo "the recipe elevates itself and sudo strips Go from PATH."; \ + exit 1; } + @if [ "$$(id -u)" = 0 ]; then \ + $(GO) test ./internal/storage/ -run Conformance -v; \ + else \ + echo "Elevating for the pool (loop devices, mount)..."; \ + sudo -E env "PATH=$$PATH" $(GO) test ./internal/storage/ -run Conformance -v; \ + fi vet: ## go vet $(GO) vet ./... diff --git a/README.md b/README.md index 7caa0bb..a9cd597 100644 --- a/README.md +++ b/README.md @@ -87,16 +87,31 @@ universally available. Probing a plain Linux Docker host found dm-thin absent only `multipath, striped, linear, error` device-mapper targets, with an empty `/lib/modules` — plus no nbd and no reflink, since the filesystem was overlayfs. +`doctor` needs no root, but some probes do — it says so rather than guessing: + ``` $ forklift doctor -MECHANISM STATUS DETAIL -dm-thin unavailable absent; dm targets present: multipath, striped, linear, error -btrfs available validated: 210ms live snapshot, clean recovery, depth-2 verified -nbd (qcow2) unavailable absent (/dev/nbd0 missing) -reflink unavailable filesystem does not support reflink -loop devices working required by every pool-in-a-file mechanism +MECHANISM STATUS DETAIL +dm-thin unknown — re-run with sudo to determine requires root to query dm targets +btrfs available validated: 210ms live snapshot, clean recovery, depth-2 verified +nbd (qcow2) unavailable absent (/dev/nbd0 missing) +reflink unavailable filesystem does not support reflink +loop devices unknown — re-run with sudo to determine required by every pool-in-a-file mechanism +docker available context default, rootless no, id a64d6a4e-... Best available mechanism: btrfs + +Note: probes marked "unknown" could not run without root; re-run with sudo to determine them. +``` + +`unknown` is deliberately distinct from `unavailable`. Querying dm targets needs +`/dev/mapper/control`, and probing loop devices needs to attach one — neither is +possible unprivileged. Reporting those as "unavailable" would tell you a +mechanism does not work on your machine when it does. Under `sudo` they resolve: + +``` +dm-thin unavailable absent; dm targets present: multipath, striped, linear, error +loop devices available required by every pool-in-a-file mechanism ``` | Mechanism | Status | Notes | @@ -120,10 +135,18 @@ work on macOS, where a ZFS-on-the-host approach cannot — untested, see below. Requires Linux, root (loop devices, `mount`, btrfs subvolumes), `btrfs-progs`, and Docker. +`make install` deliberately targets `/usr/local/bin` rather than `GOBIN`. +`go install` puts the binary in `~/go/bin`, which is **not** on sudo's +`secure_path`, so `sudo forklift ...` would fail with `command not found` — and +every pool command needs root. Override with `make install PREFIX=/somewhere`. +If you do run it from an unusual location, forklift prints the exact +`sudo /abs/path/forklift ...` line to re-run. + ```bash -make build +make build # -> ./bin/forklift +make install # -> /usr/local/bin/forklift -sudo ./bin/forklift doctor # what can this machine do? +sudo forklift doctor # what can this machine do? sudo ./bin/forklift init # create the pool sudo ./bin/forklift create main # empty branch, runs initdb sudo ./bin/forklift create agent-a --from main @@ -164,9 +187,15 @@ child would believe it was the authoritative source of truth about all branches. ```bash make test # unit tests, no root required -make test-integration # conformance suite against btrfs; needs root +make test-integration # conformance suite against btrfs — run WITHOUT sudo ``` +`make test-integration` elevates itself. Do not prefix it with `sudo`: sudo +replaces `PATH` with its `secure_path`, which excludes the Go toolchain, so +`sudo make` fails with `go: not found` before any test runs. The target detects +that and tells you to drop the sudo. If you are already root (a CI container, +say) it runs `go test` directly instead of nesting sudo. + ## Known gaps - **macOS is untested.** The whole portability argument rests on the pool living diff --git a/go.mod b/go.mod index c2dadac..9e3d8e3 100644 --- a/go.mod +++ b/go.mod @@ -3,11 +3,13 @@ module github.com/postkitstack/forklift go 1.26.6 require ( + github.com/dennwc/btrfs v0.0.0-20260222081608-edfb8b9e4f55 github.com/lib/pq v1.12.3 github.com/spf13/cobra v1.10.2 ) require ( + github.com/dennwc/ioctl v1.0.1-0.20181021180353-017804252068 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/spf13/pflag v1.0.9 // indirect ) diff --git a/go.sum b/go.sum index c8cbff4..37f61d7 100644 --- a/go.sum +++ b/go.sum @@ -1,4 +1,8 @@ github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= +github.com/dennwc/btrfs v0.0.0-20260222081608-edfb8b9e4f55 h1:VAnGuI8RNnP8vHqCn8X1O63TexAv+QjMqffBdkLbYKU= +github.com/dennwc/btrfs v0.0.0-20260222081608-edfb8b9e4f55/go.mod h1:Kn6RQo4OP1ZEoLB3uldDJabFcf72VgDRInxEqLEo8OE= +github.com/dennwc/ioctl v1.0.1-0.20181021180353-017804252068 h1:K71w/n/Y74EQsKo91511t7TK35YRPrk9G+2anKYNPXk= +github.com/dennwc/ioctl v1.0.1-0.20181021180353-017804252068/go.mod h1:ellh2YB5ldny99SBU/VX7Nq0xiZbHphf1DrtHxxjMk0= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ= diff --git a/internal/cli/commands.go b/internal/cli/commands.go index 3a4fd4a..6f601f7 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -7,6 +7,7 @@ import ( "text/tabwriter" "time" + "github.com/postkitstack/forklift/internal/compute" "github.com/postkitstack/forklift/internal/storage" "github.com/spf13/cobra" ) @@ -27,15 +28,17 @@ multipath/striped/linear/error device-mapper targets, no nbd, and no reflink.`, w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) fmt.Fprintln(w, "MECHANISM\tSTATUS\tDETAIL") for _, m := range ms { - status := "unavailable" - if m.Available { - status = "available" - } - fmt.Fprintf(w, "%s\t%s\t%s\n", m.Name, status, m.Detail) + fmt.Fprintf(w, "%s\t%s\t%s\n", m.Name, stateWord(m.State), m.Detail) } fmt.Fprintf(w, "loop devices\t%s\t%s\n", - boolWord(storage.LoopDevicesWork(ctx), "working", "unavailable"), + stateWord(storage.LoopDevicesState(ctx)), "required by every pool-in-a-file mechanism") + if di, err := compute.InspectDaemon(ctx); err == nil { + fmt.Fprintf(w, "docker\tavailable\tcontext %s, rootless %s, id %s\n", + di.Context, boolWord(di.Rootless, "yes", "no"), di.ID) + } else { + fmt.Fprintf(w, "docker\tunavailable\t%s\n", err) + } w.Flush() fmt.Println() @@ -45,13 +48,27 @@ multipath/striped/linear/error device-mapper targets, no nbd, and no reflink.`, fmt.Println("No COW mechanism available on this machine.") } if os.Geteuid() != 0 { - fmt.Println("\nNote: not running as root, so some probes could not be attempted.") + fmt.Println("\nNote: probes marked \"unknown\" could not run without root; re-run with sudo to determine them.") } return nil }, } } +// stateWord renders a probe result. Unknown must stay visibly distinct from +// unavailable: telling a user a mechanism is absent when we merely lacked +// permission to check makes doctor lie. +func stateWord(s storage.State) string { + switch s { + case storage.StateAvailable: + return "available" + case storage.StateUnavailable: + return "unavailable" + default: + return "unknown — re-run with sudo to determine" + } +} + func newInitCmd() *cobra.Command { return &cobra.Command{ Use: "init", @@ -60,7 +77,7 @@ func newInitCmd() *cobra.Command { if err := requireRoot(); err != nil { return err } - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } @@ -83,7 +100,7 @@ func newCreateCmd() *cobra.Command { if err := requireRoot(); err != nil { return err } - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } @@ -124,7 +141,7 @@ func newListCmd() *cobra.Command { Aliases: []string{"ls"}, Short: "List branches", RunE: func(cmd *cobra.Command, _ []string) error { - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } @@ -167,7 +184,7 @@ func newInspectCmd() *cobra.Command { Short: "Show one branch in detail", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } @@ -212,7 +229,7 @@ func newStartCmd() *cobra.Command { if err := requireRoot(); err != nil { return err } - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } @@ -235,7 +252,7 @@ func newStopCmd() *cobra.Command { Short: "Stop a branch's Postgres, keeping its data", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } @@ -259,7 +276,7 @@ func newDeleteCmd() *cobra.Command { if err := requireRoot(); err != nil { return err } - m, err := buildManager() + m, err := buildManager(cmd.Context()) if err != nil { return err } diff --git a/internal/cli/root.go b/internal/cli/root.go index b84a7ae..a46c303 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -2,9 +2,11 @@ package cli import ( + "context" "fmt" "os" "path/filepath" + "strings" "github.com/postkitstack/forklift/internal/compute" "github.com/postkitstack/forklift/internal/manager" @@ -61,8 +63,13 @@ func defaultRoot() string { } // buildManager assembles the object graph. Storage is chosen here, which is -// the one place the mechanism decision is made. -func buildManager() (*manager.Manager, error) { +// the one place the mechanism decision is made. Every command that touches +// branches goes through this, so it is also the choke point for refusing a +// sudo-forked Docker daemon. +func buildManager(ctx context.Context) (*manager.Manager, error) { + if err := compute.EnsureSameDaemonAsUser(ctx); err != nil { + return nil, err + } store := storage.NewBtrfs(flagRoot, flagPoolGB) repo := metadata.NewJSONRepo(filepath.Join(flagRoot, "branches.json")) return manager.New(store, compute.NewDocker(), repo), nil @@ -70,9 +77,19 @@ func buildManager() (*manager.Manager, error) { func requireRoot() error { if os.Geteuid() != 0 { + // Resolve the binary by absolute path: `sudo forklift` fails outright + // when the binary is not on sudo's secure_path (go install lands it in + // ~/go/bin), so a bare "Re-run with sudo" would suggest a command that + // cannot work. + exe, err := os.Executable() + if err != nil || exe == "" { + exe = "forklift" + } return fmt.Errorf( - "this command needs root: the storage pool uses loop devices, mount and btrfs subvolumes.\n" + - "Re-run with sudo, or point --root at a pool you already own") + "this command needs root: the storage pool uses loop devices, mount and btrfs subvolumes.\n"+ + "Re-run: sudo %s %s\n"+ + "or point --root at a pool you already own", + exe, strings.Join(os.Args[1:], " ")) } return nil } diff --git a/internal/compute/docker.go b/internal/compute/docker.go index d5e8350..f06f8be 100644 --- a/internal/compute/docker.go +++ b/internal/compute/docker.go @@ -8,12 +8,15 @@ import ( "context" "fmt" "net" + "os" "os/exec" "strconv" "strings" + "sync" "time" "github.com/postkitstack/forklift/internal/branch" + "github.com/postkitstack/forklift/internal/tool" ) // Provider starts and stops a branch's database process. @@ -49,6 +52,10 @@ type Docker struct { PortLow int PortHigh int Password string + + exeOnce sync.Once + exePath string + exeErr error } func NewDocker() *Docker { @@ -58,6 +65,22 @@ func NewDocker() *Docker { } } +// dockerExe resolves the docker binary once. Resolution goes through the +// shared tool resolver so a docker in an sbin dir off PATH is still found. +func (d *Docker) dockerExe() (string, error) { + d.exeOnce.Do(func() { d.exePath, d.exeErr = tool.Resolve("docker") }) + return d.exePath, d.exeErr +} + +// cmd builds a docker command, or an error if docker could not be found. +func (d *Docker) cmd(ctx context.Context, args ...string) (*exec.Cmd, error) { + exe, err := d.dockerExe() + if err != nil { + return nil, err + } + return exec.CommandContext(ctx, exe, args...), nil +} + // Initdb initialises an empty data directory using the same image the branch // will later run, so the on-disk format always matches the server. func (d *Docker) Initdb(ctx context.Context, dataDir, pgVersion string) error { @@ -69,7 +92,11 @@ func (d *Docker) Initdb(ctx context.Context, dataDir, pgVersion string) error { "--entrypoint", "docker-ensure-initdb.sh", d.image(pgVersion), } - if out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput(); err != nil { + cmd, err := d.cmd(ctx, args...) + if err != nil { + return fmt.Errorf("initdb: %w", err) + } + if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("initdb: %w: %s", err, strings.TrimSpace(string(out))) } return nil @@ -93,7 +120,11 @@ func (d *Docker) Start(ctx context.Context, dataDir, pgVersion string) (branch.C "-v", dataDir + ":/var/lib/postgresql/data", d.image(pgVersion), } - out, err := exec.CommandContext(ctx, "docker", args...).CombinedOutput() + cmd, err := d.cmd(ctx, args...) + if err != nil { + return branch.ComputeRef{}, err + } + out, err := cmd.CombinedOutput() if err != nil { return branch.ComputeRef{}, fmt.Errorf("start container: %w: %s", err, strings.TrimSpace(string(out))) } @@ -111,16 +142,25 @@ func (d *Docker) Stop(ctx context.Context, ref branch.ComputeRef) error { if ref.ContainerID == "" { return nil } - _ = exec.CommandContext(ctx, "docker", "stop", ref.ContainerID).Run() - return exec.CommandContext(ctx, "docker", "rm", "-f", ref.ContainerID).Run() + if cmd, err := d.cmd(ctx, "stop", ref.ContainerID); err == nil { + _ = cmd.Run() + } + cmd, err := d.cmd(ctx, "rm", "-f", ref.ContainerID) + if err != nil { + return err + } + return cmd.Run() } func (d *Docker) Running(ctx context.Context, ref branch.ComputeRef) bool { if ref.ContainerID == "" { return false } - out, err := exec.CommandContext(ctx, "docker", "inspect", - "-f", "{{.State.Running}}", ref.ContainerID).Output() + cmd, err := d.cmd(ctx, "inspect", "-f", "{{.State.Running}}", ref.ContainerID) + if err != nil { + return false + } + out, err := cmd.Output() return err == nil && strings.TrimSpace(string(out)) == "true" } @@ -131,9 +171,8 @@ func (d *Docker) Running(ctx context.Context, ref branch.ComputeRef) bool { func (d *Docker) waitReady(ctx context.Context, ref branch.ComputeRef) error { deadline := time.Now().Add(90 * time.Second) for time.Now().Before(deadline) { - err := exec.CommandContext(ctx, "docker", "exec", ref.ContainerID, - "pg_isready", "-U", "postgres").Run() - if err == nil { + cmd, err := d.cmd(ctx, "exec", ref.ContainerID, "pg_isready", "-U", "postgres") + if err == nil && cmd.Run() == nil { return nil } select { @@ -142,16 +181,22 @@ func (d *Docker) waitReady(ctx context.Context, ref branch.ComputeRef) error { case <-time.After(time.Second): } } - logs, _ := exec.Command("docker", "logs", "--tail", "20", ref.ContainerID).CombinedOutput() + logs := []byte("docker not found") + if cmd, err := d.cmd(context.Background(), "logs", "--tail", "20", ref.ContainerID); err == nil { + logs, _ = cmd.CombinedOutput() + } return fmt.Errorf("postgres did not become ready within 90s; last logs:\n%s", strings.TrimSpace(string(logs))) } func (d *Docker) ensureNetwork(ctx context.Context) error { - if err := exec.CommandContext(ctx, "docker", "network", "inspect", d.Network).Run(); err == nil { + if cmd, err := d.cmd(ctx, "network", "inspect", d.Network); err == nil && cmd.Run() == nil { return nil } - out, err := exec.CommandContext(ctx, "docker", "network", "create", - d.Network).CombinedOutput() + cmd, err := d.cmd(ctx, "network", "create", d.Network) + if err != nil { + return fmt.Errorf("create network: %w", err) + } + out, err := cmd.CombinedOutput() if err != nil && !strings.Contains(string(out), "already exists") { return fmt.Errorf("create network: %w: %s", err, strings.TrimSpace(string(out))) } @@ -173,6 +218,108 @@ func (d *Docker) publishAddress(port int) string { return net.JoinHostPort(host, strconv.Itoa(port)) + ":5432" } +// DaemonInfo describes the Docker daemon a command would talk to. +type DaemonInfo struct { + Context string + Rootless bool + ID string +} + +// InspectDaemon queries the daemon the current process would reach. +// +// The daemon ID from `docker info -f {{.ID}}` is the comparable part: two +// docker binaries can share a context name yet point at different daemons, +// and DOCKER_HOST overrides everything. +func InspectDaemon(ctx context.Context) (DaemonInfo, error) { + exe, err := tool.Resolve("docker") + if err != nil { + return DaemonInfo{}, err + } + var info DaemonInfo + if out, err := exec.CommandContext(ctx, exe, "context", "show").Output(); err == nil { + info.Context = strings.TrimSpace(string(out)) + } + if info.Context == "" { + info.Context = "default" + } + out, err := exec.CommandContext(ctx, exe, "info", "-f", "{{.ID}}").Output() + if err != nil { + return info, fmt.Errorf("docker info failed: %w: %s", err, strings.TrimSpace(string(out))) + } + info.ID = strings.TrimSpace(string(out)) + sec, _ := exec.CommandContext(ctx, exe, "info", "-f", "{{.SecurityOptions}}").Output() + info.Rootless = strings.Contains(string(sec), "rootless") + return info, nil +} + +// EnsureSameDaemonAsUser refuses to proceed when sudo has forked the daemon. +// +// Under sudo we run docker as root. If the invoking user runs rootless Docker +// or a non-default context, root's docker is a different daemon: branches get +// created where the user cannot see them, or fail confusingly mid-create. +// When SUDO_USER is set, compare the daemon ID root sees with the one that +// user sees and fail loudly on a mismatch. If the comparison is impossible — +// no sudo binary, or the user's own query fails — stay silent rather than +// block on something we could not verify. +func EnsureSameDaemonAsUser(ctx context.Context) error { + user := os.Getenv("SUDO_USER") + if user == "" || os.Geteuid() != 0 { + return nil + } + rootDaemon, err := InspectDaemon(ctx) + if err != nil { + return nil + } + sudoExe, err := tool.Resolve("sudo") + if err != nil { + return nil + } + dockerExe, err := tool.Resolve("docker") + if err != nil { + return nil + } + // sudo -u does not inherit the target user's environment, so the usual + // daemon selectors must be forwarded explicitly or we would query root's + // daemon twice and call it a match. + cmd := exec.CommandContext(ctx, sudoExe, "-u", user, + "--preserve-env=DOCKER_HOST,DOCKER_CONTEXT,XDG_RUNTIME_DIR", + dockerExe, "info", "-f", "{{.ID}}") + out, err := cmd.CombinedOutput() + if err != nil { + return nil + } + userID := strings.TrimSpace(string(out)) + if userID == "" || userID == rootDaemon.ID { + return nil + } + userDaemon, derr := inspectDaemonAs(ctx, sudoExe, dockerExe, user) + userCtx := "unknown" + if derr == nil { + userCtx = userDaemon.Context + } + return fmt.Errorf( + "sudo is talking to a different Docker daemon than %s; branches created here would be invisible to you.\n"+ + " as root: context %s, id %s\n"+ + " as %s: context %s, id %s\n"+ + "Run forklift without sudo, or align DOCKER_HOST / docker context first.", + user, rootDaemon.Context, rootDaemon.ID, user, userCtx, userID) +} + +func inspectDaemonAs(ctx context.Context, sudoExe, dockerExe, user string) (DaemonInfo, error) { + c := exec.CommandContext(ctx, sudoExe, "-u", user, + "--preserve-env=DOCKER_HOST,DOCKER_CONTEXT,XDG_RUNTIME_DIR", + dockerExe, "context", "show") + out, err := c.Output() + if err != nil { + return DaemonInfo{}, err + } + ctxName := strings.TrimSpace(string(out)) + if ctxName == "" { + ctxName = "default" + } + return DaemonInfo{Context: ctxName}, nil +} + func (d *Docker) freePort() (int, error) { for p := d.PortLow; p <= d.PortHigh; p++ { ln, err := net.Listen("tcp", ":"+strconv.Itoa(p)) diff --git a/internal/storage/btrfs.go b/internal/storage/btrfs.go index 5374bc6..593187a 100644 --- a/internal/storage/btrfs.go +++ b/internal/storage/btrfs.go @@ -6,13 +6,21 @@ import ( "os" "os/exec" "path/filepath" - "strconv" "strings" "time" + "github.com/dennwc/btrfs" "github.com/postkitstack/forklift/internal/branch" + "github.com/postkitstack/forklift/internal/tool" ) +// Subvolume operations go through the pure-Go github.com/dennwc/btrfs library +// (kernel ioctls underneath) rather than shelling out to the btrfs CLI: the +// CLI's human-readable output is not a stable interface, and parsing it broke +// across btrfs-progs versions. Only mkfs.btrfs, mount/umount/losetup and +// modprobe still run as external commands — the kernel exposes no ioctl for +// formatting or mounting. + // Btrfs stores each branch as a btrfs subvolume inside a pool that lives in a // single loopback-mounted file. // @@ -59,20 +67,12 @@ func (b *Btrfs) Available(ctx context.Context) (bool, string) { if os.Geteuid() != 0 { return false, "requires root (loop devices, mount, btrfs subvolume)" } - fs, err := os.ReadFile("/proc/filesystems") - if err != nil { - return false, "cannot read /proc/filesystems: " + err.Error() - } - if !strings.Contains(string(fs), "btrfs") { - // Try loading it before giving up. - _ = exec.CommandContext(ctx, "modprobe", "btrfs").Run() - fs, _ = os.ReadFile("/proc/filesystems") - if !strings.Contains(string(fs), "btrfs") { - return false, "btrfs not supported by this kernel" - } + supported, why := btrfsKernelSupport(ctx) + if !supported { + return false, why } - if _, err := exec.LookPath("btrfs"); err != nil { - return false, "btrfs-progs not installed" + if _, err := tool.Resolve("mkfs.btrfs"); err != nil { + return false, "btrfs-progs not installed (mkfs.btrfs is required to format the pool)" } return true, "" } @@ -88,8 +88,14 @@ func (b *Btrfs) Init(ctx context.Context) error { return nil // already initialised } if _, err := os.Stat(b.imagePath()); os.IsNotExist(err) { - size := strconv.Itoa(b.PoolSizeGB) + "G" - if err := run(ctx, "truncate", "-s", size, b.imagePath()); err != nil { + f, err := os.Create(b.imagePath()) + if err != nil { + return fmt.Errorf("create pool image: %w", err) + } + if err := f.Close(); err != nil { + return fmt.Errorf("create pool image: %w", err) + } + if err := os.Truncate(b.imagePath(), int64(b.PoolSizeGB)<<30); err != nil { return fmt.Errorf("create pool image: %w", err) } if err := run(ctx, "mkfs.btrfs", "-q", "-f", b.imagePath()); err != nil { @@ -162,7 +168,7 @@ func (b *Btrfs) CreateRoot(ctx context.Context, name string) (branch.StorageRef, return branch.StorageRef{}, err } path := b.subvol(name) - if err := run(ctx, "btrfs", "subvolume", "create", path); err != nil { + if err := btrfs.CreateSubVolume(path); err != nil { return branch.StorageRef{}, fmt.Errorf("create subvolume: %w", err) } data := filepath.Join(path, "pgdata") @@ -191,14 +197,14 @@ func (b *Btrfs) Fork(ctx context.Context, parent branch.StorageRef, opts ForkOpt // The snapshot itself. Atomic, and the parent keeps serving throughout. started := time.Now() - if err := run(ctx, "btrfs", "subvolume", "snapshot", src, dst); err != nil { + if err := btrfs.SnapshotSubVolume(src, dst, false); err != nil { return branch.StorageRef{}, nil, fmt.Errorf("snapshot: %w", err) } data := filepath.Join(dst, "pgdata") if err := PrepareClone(data, b.PGUID, b.PGGID); err != nil { // Roll back so a failed fork does not leave storage behind. - _ = run(ctx, "btrfs", "subvolume", "delete", dst) + _ = btrfs.DeleteSubVolume(dst) return branch.StorageRef{}, nil, err } @@ -218,100 +224,82 @@ func (b *Btrfs) Delete(ctx context.Context, ref branch.StorageRef) error { if len(kids) > 0 { return &ErrHasChildren{Handle: ref.Handle, Children: kids} } - return run(ctx, "btrfs", "subvolume", "delete", b.subvol(ref.Handle)) + if err := btrfs.DeleteSubVolume(b.subvol(ref.Handle)); err != nil { + return fmt.Errorf("delete subvolume: %w", err) + } + return nil } // Children reports subvolumes forked from ref. // // btrfs tracks this through parent UUIDs rather than names, so we resolve the -// parent's UUID and match against every subvolume's Parent UUID field. +// parent's UUID and match it against every subvolume's ParentUUID in a single +// ioctl-driven walk of the pool mount (no CLI text parsing). func (b *Btrfs) Children(ctx context.Context, ref branch.StorageRef) ([]string, error) { if err := branch.ValidateName(ref.Handle); err != nil { return nil, fmt.Errorf("invalid storage handle: %w", err) } - uuid, err := b.subvolUUID(ctx, ref.Handle) - if err != nil || uuid == "" { - return nil, err + fs, err := btrfs.Open(b.mountPath(), true) + if err != nil { + return nil, fmt.Errorf("open pool mount: %w", err) } - out, err := output(ctx, "btrfs", "subvolume", "list", "-u", "-q", b.mountPath()) + defer fs.Close() + uuid, err := b.subvolUUID(fs, ref.Handle) if err != nil { return nil, err } + if uuid == (btrfs.UUID{}) { + return nil, nil + } + subs, err := fs.ListSubvolumes(nil) + if err != nil { + return nil, fmt.Errorf("list subvolumes: %w", err) + } var kids []string - for _, line := range strings.Split(out, "\n") { - if !strings.Contains(line, "parent_uuid "+uuid) { - continue - } - if i := strings.LastIndex(line, " path "); i >= 0 { - name := strings.TrimSpace(line[i+len(" path "):]) - if name != ref.Handle { - kids = append(kids, name) - } + for _, sub := range subs { + if sub.ParentUUID == uuid && sub.Path != ref.Handle { + kids = append(kids, sub.Path) } } return kids, nil } -func (b *Btrfs) subvolUUID(ctx context.Context, name string) (string, error) { - out, err := output(ctx, "btrfs", "subvolume", "show", b.subvol(name)) +func (b *Btrfs) subvolUUID(fs *btrfs.FS, name string) (btrfs.UUID, error) { + info, err := fs.SubvolumeByPath(name) if err != nil { - return "", err + return btrfs.UUID{}, fmt.Errorf("resolve subvolume %q: %w", name, err) } - for _, line := range strings.Split(out, "\n") { - line = strings.TrimSpace(line) - if strings.HasPrefix(line, "UUID:") { - return strings.TrimSpace(strings.TrimPrefix(line, "UUID:")), nil - } - } - return "", nil + return info.UUID, nil } func (b *Btrfs) Usage(ctx context.Context) (Usage, error) { var u Usage - out, err := output(ctx, "btrfs", "filesystem", "usage", "-b", b.mountPath()) + fs, err := btrfs.Open(b.mountPath(), true) if err != nil { - return u, err - } - // "Used:" carries only two fields, so guard at 2 rather than 3 — at 3 it is - // silently skipped and the pool always reports empty, which would make the - // watermark check useless exactly when it matters. - for _, line := range strings.Split(out, "\n") { - trimmed := strings.TrimSpace(line) - f := strings.Fields(trimmed) - if len(f) < 2 { - continue - } - switch { - case strings.HasPrefix(trimmed, "Device size:"): - u.TotalBytes = parseUint(f[len(f)-1]) - case strings.HasPrefix(trimmed, "Used:"): - if u.UsedBytes == 0 { - u.UsedBytes = parseUint(f[len(f)-1]) - } - } + return u, fmt.Errorf("open pool mount: %w", err) } + defer fs.Close() + usage, err := fs.Usage() + if err != nil { + return u, fmt.Errorf("query pool usage: %w", err) + } + u.UsedBytes = usage.TotalUsed + u.TotalBytes = usage.Total return u, nil } -func parseUint(s string) uint64 { - v, _ := strconv.ParseUint(strings.TrimSpace(s), 10, 64) - return v -} - +// run shells out to an external command. The binary is resolved by absolute +// path (see package tool): mount helpers live in /usr/sbin, which is off a +// normal non-root PATH and off sudo's secure_path alike. func run(ctx context.Context, name string, args ...string) error { - cmd := exec.CommandContext(ctx, name, args...) + exe, err := tool.Resolve(name) + if err != nil { + return err + } + cmd := exec.CommandContext(ctx, exe, args...) out, err := cmd.CombinedOutput() if err != nil { return fmt.Errorf("%s %s: %w: %s", name, strings.Join(args, " "), err, strings.TrimSpace(string(out))) } return nil } - -func output(ctx context.Context, name string, args ...string) (string, error) { - cmd := exec.CommandContext(ctx, name, args...) - out, err := cmd.Output() - if err != nil { - return "", fmt.Errorf("%s %s: %w", name, strings.Join(args, " "), err) - } - return string(out), nil -} diff --git a/internal/storage/detect.go b/internal/storage/detect.go index 2c024e3..afc4a07 100644 --- a/internal/storage/detect.go +++ b/internal/storage/detect.go @@ -2,17 +2,34 @@ package storage import ( "context" + "fmt" "os" "os/exec" "strings" + + "github.com/postkitstack/forklift/internal/tool" ) -// Mechanism is one candidate COW implementation, with whether this machine can -// actually provide it. +// State is what a probe actually established. Conflating these states made +// doctor lie: a probe that could not run for lack of privilege was reported +// identically to one that ran and came back negative, so users were told a +// mechanism was "unavailable" when the truth was "we could not look". +type State int + +const ( + // StateUnknown means the probe could not run from here — usually it + // needs root. It is not a negative answer. + StateUnknown State = iota + StateUnavailable + StateAvailable +) + +// Mechanism is one candidate COW implementation, with what this machine's +// probe established about it. type Mechanism struct { - Name string - Available bool - Detail string + Name string + State State + Detail string // Preference orders the candidates; lower is better. Preference int } @@ -34,12 +51,14 @@ func Detect(ctx context.Context) []Mechanism { } } -// Best returns the highest-preference available mechanism, or "" if none. +// Best returns the highest-preference mechanism that is definitely available, +// or "" if none is. Unknown mechanisms are never selected: an unprobed +// candidate must not win by accident. func Best(ms []Mechanism) string { best := "" bestPref := 1 << 30 for _, m := range ms { - if m.Available && m.Preference < bestPref { + if m.State == StateAvailable && m.Preference < bestPref { best, bestPref = m.Name, m.Preference } } @@ -49,15 +68,28 @@ func Best(ms []Mechanism) string { func detectDmThin(ctx context.Context) Mechanism { m := Mechanism{Name: "dm-thin", Preference: 1, Detail: "preferred: per-device btree, so read cost is flat at any branch depth"} - _ = exec.CommandContext(ctx, "modprobe", "dm_thin_pool").Run() - out, err := exec.CommandContext(ctx, "dmsetup", "targets").Output() + if exe, err := tool.Resolve("modprobe"); err == nil { + _ = exec.CommandContext(ctx, exe, "dm_thin_pool").Run() + } + dmsetup, err := tool.Resolve("dmsetup") if err != nil { - m.Detail = "dmsetup unavailable, cannot determine" + // Without the userspace tool we cannot look at all; that is not a + // negative answer about the kernel target. + m.State = StateUnknown + m.Detail = "dmsetup not installed; cannot determine" + return m + } + out, err := exec.CommandContext(ctx, dmsetup, "targets").Output() + if err != nil { + // As a normal user this fails with "/dev/mapper/control: open + // failed: Permission denied" even when dm-thin works fine as root. + m.State = StateUnknown + m.Detail = "requires root to query dm targets" return m } for _, line := range strings.Split(string(out), "\n") { if strings.HasPrefix(line, "thin-pool") { - m.Available = true + m.State = StateAvailable return m } } @@ -67,34 +99,80 @@ func detectDmThin(ctx context.Context) Mechanism { names = append(names, f[0]) } } + m.State = StateUnavailable m.Detail = "absent; dm targets present: " + strings.Join(names, ", ") return m } +// btrfsKernelSupport reports whether the kernel currently has btrfs, trying +// to load the module first, and explains which case actually holds. +// +// The old code discarded modprobe's error and declared "not supported by this +// kernel" on any failure — a guess. On hosts without kmod or /lib/modules +// (common in minimal containers) that assertion was unfounded: the module +// might exist but simply never have been loaded. +func btrfsKernelSupport(ctx context.Context) (bool, string) { + fs, err := os.ReadFile("/proc/filesystems") + if err != nil { + return false, "cannot read /proc/filesystems: " + err.Error() + } + if strings.Contains(string(fs), "btrfs") { + return true, "" + } + modprobe, err := tool.Resolve("modprobe") + if err != nil { + return false, "btrfs not loaded and modprobe is unavailable to load it" + } + if _, err := os.Stat("/lib/modules/" + kernelRelease()); err != nil { + return false, "this kernel has no loadable modules" + } + out, err := exec.CommandContext(ctx, modprobe, "btrfs").CombinedOutput() + if err != nil { + return false, fmt.Sprintf("btrfs not loaded; modprobe failed: %s", strings.TrimSpace(string(out))) + } + fs, _ = os.ReadFile("/proc/filesystems") + if !strings.Contains(string(fs), "btrfs") { + return false, "btrfs not loaded; modprobe succeeded but btrfs is still absent from /proc/filesystems" + } + return true, "" +} + +func kernelRelease() string { + b, err := os.ReadFile("/proc/sys/kernel/osrelease") + if err != nil { + return "" + } + return strings.TrimSpace(string(b)) +} + func detectBtrfs(ctx context.Context) Mechanism { m := Mechanism{Name: "btrfs", Preference: 2, Detail: "validated: 210ms live snapshot, clean recovery, depth-2 verified"} - _ = exec.CommandContext(ctx, "modprobe", "btrfs").Run() - fs, err := os.ReadFile("/proc/filesystems") - if err == nil && strings.Contains(string(fs), "btrfs") { - if _, err := exec.LookPath("btrfs"); err != nil { - m.Detail = "kernel supports btrfs but btrfs-progs is not installed" - return m - } - m.Available = true + supported, why := btrfsKernelSupport(ctx) + if !supported { + m.State = StateUnavailable + m.Detail = why + return m + } + if _, err := tool.Resolve("mkfs.btrfs"); err != nil { + m.State = StateUnavailable + m.Detail = "kernel supports btrfs but mkfs.btrfs is not installed" return m } - m.Detail = "not supported by this kernel" + m.State = StateAvailable return m } func detectNBD(ctx context.Context) Mechanism { m := Mechanism{Name: "nbd (qcow2)", Preference: 3, Detail: "userspace daemon in the read path; backing chains are O(depth)"} - _ = exec.CommandContext(ctx, "modprobe", "nbd").Run() + if exe, err := tool.Resolve("modprobe"); err == nil { + _ = exec.CommandContext(ctx, exe, "nbd").Run() + } if _, err := os.Stat("/dev/nbd0"); err == nil { - m.Available = true + m.State = StateAvailable } else { + m.State = StateUnavailable m.Detail = "absent (/dev/nbd0 missing)" } return m @@ -105,6 +183,7 @@ func detectReflink(ctx context.Context) Mechanism { Detail: "unprivileged floor; degrades to a full copy where unsupported"} dir, err := os.MkdirTemp("", "forklift-reflink") if err != nil { + m.State = StateUnknown m.Detail = "could not test: " + err.Error() return m } @@ -112,37 +191,58 @@ func detectReflink(ctx context.Context) Mechanism { src := dir + "/a" if err := os.WriteFile(src, []byte("x"), 0o600); err != nil { + m.State = StateUnknown + m.Detail = "could not test: " + err.Error() + return m + } + cp, err := tool.Resolve("cp") + if err != nil { + m.State = StateUnknown m.Detail = "could not test: " + err.Error() return m } - if err := exec.CommandContext(ctx, "cp", "--reflink=always", src, dir+"/b").Run(); err == nil { - m.Available = true + if err := exec.CommandContext(ctx, cp, "--reflink=always", src, dir+"/b").Run(); err == nil { + m.State = StateAvailable return m } + // The probe ran to completion; a negative here is a real answer. + m.State = StateUnavailable m.Detail = "filesystem does not support reflink" return m } -// LoopDevicesWork reports whether we can attach a loop device, which every -// pool-in-a-file mechanism depends on. -func LoopDevicesWork(ctx context.Context) bool { +// LoopDevicesState reports whether we can attach a loop device, which every +// pool-in-a-file mechanism depends on. Attaching requires root, so from an +// unprivileged process the honest answer is unknown, not no. +func LoopDevicesState(ctx context.Context) State { if os.Geteuid() != 0 { - return false + return StateUnknown } f, err := os.CreateTemp("", "forklift-loop") if err != nil { - return false + return StateUnavailable } defer os.Remove(f.Name()) f.Close() - if err := exec.CommandContext(ctx, "truncate", "-s", "16M", f.Name()).Run(); err != nil { - return false + truncate, err := tool.Resolve("truncate") + if err != nil { + return StateUnavailable } - out, err := exec.CommandContext(ctx, "losetup", "-f", "--show", f.Name()).Output() + losetup, err := tool.Resolve("losetup") if err != nil { - return false + return StateUnavailable + } + if err := exec.CommandContext(ctx, truncate, "-s", "16M", f.Name()).Run(); err != nil { + return StateUnavailable + } + out, err := exec.CommandContext(ctx, losetup, "-f", "--show", f.Name()).Output() + if err != nil { + return StateUnavailable } dev := strings.TrimSpace(string(out)) - _ = exec.CommandContext(ctx, "losetup", "-d", dev).Run() - return dev != "" + _ = exec.CommandContext(ctx, losetup, "-d", dev).Run() + if dev == "" { + return StateUnavailable + } + return StateAvailable } diff --git a/internal/tool/tool.go b/internal/tool/tool.go new file mode 100644 index 0000000..18ceff3 --- /dev/null +++ b/internal/tool/tool.go @@ -0,0 +1,35 @@ +// Package tool resolves external binaries by absolute path. +// +// sudo replaces PATH with secure_path, and /usr/sbin — home of losetup, +// dmsetup and mkfs.btrfs on Debian/Ubuntu — is off a normal non-root PATH. +// Resolving through exec.LookPath alone therefore false-negatives depending +// on who is running, which is how the mkfs.btrfs probe in doctor broke once +// already. Every shell-out goes through here so a new call site cannot get +// it wrong. +package tool + +import ( + "fmt" + "os" + "os/exec" +) + +// sbinDirs are searched after PATH. /usr/local/sbin precedes /usr/sbin to +// match the conventions both Debian and sudo's secure_path use. +var sbinDirs = []string{"/usr/local/sbin", "/usr/sbin", "/sbin"} + +// Resolve finds name on PATH, falling back to the usual sbin locations that +// non-root PATHs and sudo's secure_path omit. It returns an absolute path +// suitable for exec, or an error naming what was tried. +func Resolve(name string) (string, error) { + if path, err := exec.LookPath(name); err == nil { + return path, nil + } + for _, dir := range sbinDirs { + path := dir + "/" + name + if info, err := os.Stat(path); err == nil && !info.IsDir() && info.Mode()&0o111 != 0 { + return path, nil + } + } + return "", fmt.Errorf("%s not found on PATH or in %s", name, sbinDirs) +} diff --git a/vendor/github.com/dennwc/btrfs/LICENSE b/vendor/github.com/dennwc/btrfs/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/dennwc/btrfs/README.md b/vendor/github.com/dennwc/btrfs/README.md new file mode 100644 index 0000000..7c8481c --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/README.md @@ -0,0 +1,2 @@ +# btrfs +Btrfs library in a pure Go diff --git a/vendor/github.com/dennwc/btrfs/btrfs.go b/vendor/github.com/dennwc/btrfs/btrfs.go new file mode 100644 index 0000000..4f0d3a3 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/btrfs.go @@ -0,0 +1,387 @@ +package btrfs + +import ( + "fmt" + "io" + "os" + "path/filepath" + "strconv" + "syscall" + + "github.com/dennwc/ioctl" +) + +const SuperMagic uint32 = 0x9123683E + +func CloneFile(dst, src *os.File) error { + return iocClone(dst, src) +} + +func Open(path string, ro bool) (*FS, error) { + if ok, err := IsSubVolume(path); err != nil { + return nil, err + } else if !ok { + return nil, ErrNotBtrfs{Path: path} + } + var ( + dir *os.File + err error + ) + if ro { + dir, err = os.OpenFile(path, os.O_RDONLY|syscall.O_NOATIME, 0644) + if err != nil { + // Try without O_NOATIME as it requires ownership of the file + // or other priviliges + dir, err = os.OpenFile(path, os.O_RDONLY, 0644) + } + } else { + dir, err = os.Open(path) + } + if err != nil { + return nil, err + } else if st, err := dir.Stat(); err != nil { + dir.Close() + return nil, err + } else if !st.IsDir() { + dir.Close() + return nil, fmt.Errorf("not a directory: %s", path) + } + return &FS{f: dir}, nil +} + +type FS struct { + f *os.File +} + +func (f *FS) Close() error { + return f.f.Close() +} + +type Info struct { + MaxID uint64 + NumDevices uint64 + FSID FSID + NodeSize uint32 + SectorSize uint32 + CloneAlignment uint32 +} + +func (f *FS) SubVolumeID() (uint64, error) { + id, err := getFileRootID(f.f) + if err != nil { + return 0, err + } + return uint64(id), nil +} + +func (f *FS) Info() (out Info, err error) { + var arg btrfs_ioctl_fs_info_args + arg, err = iocFsInfo(f.f) + if err == nil { + out = Info{ + MaxID: arg.max_id, + NumDevices: arg.num_devices, + FSID: arg.fsid, + NodeSize: arg.nodesize, + SectorSize: arg.sectorsize, + CloneAlignment: arg.clone_alignment, + } + } + return +} + +type DevInfo struct { + UUID UUID + BytesUsed uint64 + TotalBytes uint64 + Path string +} + +func (f *FS) GetDevInfo(id uint64) (out DevInfo, err error) { + var arg btrfs_ioctl_dev_info_args + arg.devid = id + + if err = ioctl.Do(f.f, _BTRFS_IOC_DEV_INFO, &arg); err != nil { + return + } + out.UUID = arg.uuid + out.BytesUsed = arg.bytes_used + out.TotalBytes = arg.total_bytes + out.Path = stringFromBytes(arg.path[:]) + + return +} + +type DevStatsFlags = uint64 + +const ( + DevStatsFlagsReset DevStatsFlags = _BTRFS_DEV_STATS_RESET +) + +type DevStats struct { + WriteErrs uint64 + ReadErrs uint64 + FlushErrs uint64 + // Checksum error, bytenr error or contents is illegal: this is an + // indication that the block was damaged during read or write, or written to + // wrong location or read from wrong location. + CorruptionErrs uint64 + // An indication that blocks have not been written. + GenerationErrs uint64 + Unknown []uint64 +} + +func (f *FS) GetDevStatsWithFlags(id uint64, flags uint64) (out DevStats, err error) { + var arg btrfs_ioctl_get_dev_stats + arg.devid = id + arg.nr_items = _BTRFS_DEV_STAT_VALUES_MAX + arg.flags = flags + if err = ioctl.Do(f.f, _BTRFS_IOC_GET_DEV_STATS, &arg); err != nil { + return + } + i := 0 + out.WriteErrs = arg.values[i] + i++ + out.ReadErrs = arg.values[i] + i++ + out.FlushErrs = arg.values[i] + i++ + out.CorruptionErrs = arg.values[i] + i++ + out.GenerationErrs = arg.values[i] + i++ + if int(arg.nr_items) > i { + out.Unknown = arg.values[i:arg.nr_items] + } + return +} +func (f *FS) GetDevStats(id uint64) (out DevStats, err error) { + return f.GetDevStatsWithFlags(id, 0) +} +func (f *FS) ResetDevStats(id uint64) (err error) { + var arg btrfs_ioctl_get_dev_stats + arg.devid = id + arg.nr_items = _BTRFS_DEV_STAT_VALUES_MAX + arg.flags = DevStatsFlagsReset + return ioctl.Do(f.f, _BTRFS_IOC_GET_DEV_STATS, &arg) +} + +type ScrubProgress struct { + DataExtentsScrubbed uint64 // # of data extents scrubbed + TreeExtentsScrubbed uint64 // # of tree extents scrubbed + DataBytesScrubbed uint64 // # of data bytes scrubbed + TreeBytesScrubbed uint64 // # of tree bytes scrubbed + ReadErrors uint64 // # of read errors encountered (EIO) + CsumErrors uint64 // # of failed csum checks + // # of occurences, where the metadata of a tree block did not match the expected values, like generation or logical + VerifyErrors uint64 + // # of 4k data block for which no csum is present, probably the result of data written with nodatasum + NoCsum uint64 + CsumDiscards uint64 // # of csum for which no data was found in the extent tree. + SuperErrors uint64 // # of bad super blocks encountered + MallocErrors uint64 // # of internal kmalloc errors. These will likely cause an incomplete scrub + UncorrectableErrors uint64 // # of errors where either no intact copy was found or the writeback failed + CorrectedErrors uint64 // # of errors corrected + // last physical address scrubbed. In case a scrub was aborted, this can be used to restart the scrub + LastPhysical uint64 + // # of occurences where a read for a full (64k) bio failed, but the re- + // check succeeded for each 4k piece. Intermittent error. + UnverifiedErrors uint64 +} + +// Start a scrub on the given device, starting at start blocks and ending on end blocks +// If you want to scan the whole device, set start to 0 and end to the maximal value of uint64( for example via math.MaxUint64) +// Another option is to resume a earlier interrupted scrub, by setting the start to the same value as reported in LastPhysical (can be retrieved via .ScrubStatus) +// WARNING: This method WILL BLOCK until the scrub is done, or the scrub is cancelled +// Scrub operations requiere CAP_SYSADMIN or root +func (f *FS) ScrubStart(dev uint64, start uint64, end uint64) error { + var arg btrfs_ioctl_scrub_args + arg.devid = dev + arg.flags = 0 + arg.start = start + arg.end = end + return iocScrub(f.f, &arg) +} + +// Cancel a scrub on the given device +// Scrub operations requiere CAP_SYSADMIN or root +func (f *FS) ScrubCancel(dev uint64) error { + return iocScrubCancel(f.f) +} + +// Get the progress of a scrub on the given device +// Scrub operations requiere CAP_SYSADMIN or root +func (f *FS) ScrubStatus(dev uint64) (ScrubProgress, error) { + var arg btrfs_ioctl_scrub_args + arg.devid = dev + arg.flags = 0 + if err := iocScrubProgress(f.f, &arg); err != nil { + return ScrubProgress{}, err + } + return ScrubProgress{ + arg.progress.data_extents_scrubbed, + arg.progress.tree_extents_scrubbed, + arg.progress.data_bytes_scrubbed, + arg.progress.tree_bytes_scrubbed, + arg.progress.read_errors, + arg.progress.csum_errors, + arg.progress.verify_errors, + arg.progress.no_csum, + arg.progress.csum_discards, + arg.progress.super_errors, + arg.progress.malloc_errors, + arg.progress.uncorrectable_errors, + arg.progress.corrected_errors, + arg.progress.last_physical, + arg.progress.unverified_errors, + }, nil +} + +type FSFeatureFlags struct { + Compatible FeatureFlags + CompatibleRO FeatureFlags + Incompatible IncompatFeatures +} + +func (f *FS) GetFeatures() (out FSFeatureFlags, err error) { + var arg btrfs_ioctl_feature_flags + if err = ioctl.Do(f.f, _BTRFS_IOC_GET_FEATURES, &arg); err != nil { + return + } + out = FSFeatureFlags{ + Compatible: arg.compat_flags, + CompatibleRO: arg.compat_ro_flags, + Incompatible: arg.incompat_flags, + } + return +} + +func (f *FS) GetSupportedFeatures() (out FSFeatureFlags, err error) { + var arg [3]btrfs_ioctl_feature_flags + if err = ioctl.Do(f.f, _BTRFS_IOC_GET_SUPPORTED_FEATURES, &arg); err != nil { + return + } + out = FSFeatureFlags{ + Compatible: arg[0].compat_flags, + CompatibleRO: arg[0].compat_ro_flags, + Incompatible: arg[0].incompat_flags, + } + //for i, a := range arg { + // out[i] = FSFeatureFlags{ + // Compatible: a.compat_flags, + // CompatibleRO: a.compat_ro_flags, + // Incompatible: a.incompat_flags, + // } + //} + return +} + +func (f *FS) GetFlags() (SubvolFlags, error) { + return iocSubvolGetflags(f.f) +} + +func (f *FS) SetFlags(flags SubvolFlags) error { + return iocSubvolSetflags(f.f, flags) +} + +func (f *FS) Sync() (err error) { + if err = ioctl.Ioctl(f.f, _BTRFS_IOC_START_SYNC, 0); err != nil { + return + } + return ioctl.Ioctl(f.f, _BTRFS_IOC_WAIT_SYNC, 0) +} + +func (f *FS) CreateSubVolume(name string) error { + return CreateSubVolume(filepath.Join(f.f.Name(), name)) +} + +func (f *FS) DeleteSubVolume(name string) error { + return DeleteSubVolume(filepath.Join(f.f.Name(), name)) +} + +func (f *FS) Snapshot(dst string, ro bool) error { + return SnapshotSubVolume(f.f.Name(), filepath.Join(f.f.Name(), dst), ro) +} + +func (f *FS) SnapshotSubVolume(name string, dst string, ro bool) error { + return SnapshotSubVolume(filepath.Join(f.f.Name(), name), + filepath.Join(f.f.Name(), dst), ro) +} + +func (f *FS) Send(w io.Writer, parent string, subvols ...string) error { + if parent != "" { + parent = filepath.Join(f.f.Name(), parent) + } + sub := make([]string, 0, len(subvols)) + for _, s := range subvols { + sub = append(sub, filepath.Join(f.f.Name(), s)) + } + return Send(w, parent, sub...) +} + +func (f *FS) Receive(r io.Reader) error { + return Receive(r, f.f.Name()) +} + +func (f *FS) ReceiveTo(r io.Reader, mount string) error { + return Receive(r, filepath.Join(f.f.Name(), mount)) +} + +func (f *FS) ListSubvolumes(filter func(SubvolInfo) bool) ([]SubvolInfo, error) { + m, err := listSubVolumes(f.f, filter) + if err != nil { + return nil, err + } + out := make([]SubvolInfo, 0, len(m)) + for _, v := range m { + out = append(out, v) + } + return out, nil +} + +func (f *FS) SubvolumeByUUID(uuid UUID) (*SubvolInfo, error) { + id, err := lookupUUIDSubvolItem(f.f, uuid) + if err != nil { + return nil, err + } + return subvolSearchByRootID(f.f, id, "") +} + +func (f *FS) SubvolumeByReceivedUUID(uuid UUID) (*SubvolInfo, error) { + id, err := lookupUUIDReceivedSubvolItem(f.f, uuid) + if err != nil { + return nil, err + } + return subvolSearchByRootID(f.f, id, "") +} + +func (f *FS) SubvolumeByPath(path string) (*SubvolInfo, error) { + return subvolSearchByPath(f.f, path) +} + +func (f *FS) Usage() (UsageInfo, error) { return spaceUsage(f.f) } + +func (f *FS) Balance(flags BalanceFlags) (BalanceProgress, error) { + args := btrfs_ioctl_balance_args{flags: flags} + err := iocBalanceV2(f.f, &args) + return args.stat, err +} + +func (f *FS) Resize(size int64) error { + amount := strconv.FormatInt(size, 10) + args := &btrfs_ioctl_vol_args{} + args.SetName(amount) + if err := iocResize(f.f, args); err != nil { + return fmt.Errorf("resize failed: %v", err) + } + return nil +} + +func (f *FS) ResizeToMax() error { + args := &btrfs_ioctl_vol_args{} + args.SetName("max") + if err := iocResize(f.f, args); err != nil { + return fmt.Errorf("resize failed: %v", err) + } + return nil +} diff --git a/vendor/github.com/dennwc/btrfs/btrfs_h.go b/vendor/github.com/dennwc/btrfs/btrfs_h.go new file mode 100644 index 0000000..192af83 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/btrfs_h.go @@ -0,0 +1,73 @@ +package btrfs + +import "strings" + +const maxUint64 = 1<<64 - 1 + +const labelSize = 256 + +type FeatureFlags uint64 + +const ( + FeatureCompatROFreeSpaceTree = FeatureFlags(1 << 0) +) + +type IncompatFeatures uint64 + +func (f IncompatFeatures) String() string { + var s []string + for i, name := range incompatFeatureNames { + if uint64(f)&uint64(i) != 0 { + s = append(s, name) + } + } + return strings.Join(s, ",") +} + +var incompatFeatureNames = []string{ + "DefaultSubvol", + "MixedGroups", + "CompressLZO", + "CompressLZOv2", + "BigMetadata", + "ExtendedIRef", + "RAID56", + "SkinnyMetadata", + "NoHoles", +} + +const ( + FeatureIncompatMixedBackRef = IncompatFeatures(1 << 0) + FeatureIncompatDefaultSubvol = IncompatFeatures(1 << 1) + FeatureIncompatMixedGroups = IncompatFeatures(1 << 2) + FeatureIncompatCompressLZO = IncompatFeatures(1 << 3) + + // Some patches floated around with a second compression method + // lets save that incompat here for when they do get in. + // Note we don't actually support it, we're just reserving the number. + FeatureIncompatCompressLZOv2 = IncompatFeatures(1 << 4) + + // Older kernels tried to do bigger metadata blocks, but the + // code was pretty buggy. Lets not let them try anymore. + FeatureIncompatBigMetadata = IncompatFeatures(1 << 5) + + FeatureIncompatExtendedIRef = IncompatFeatures(1 << 6) + FeatureIncompatRAID56 = IncompatFeatures(1 << 7) + FeatureIncompatSkinnyMetadata = IncompatFeatures(1 << 8) + FeatureIncompatNoHoles = IncompatFeatures(1 << 9) +) + +// Flags definition for balance. +type BalanceFlags uint64 + +// Restriper's general type filter. +const ( + BalanceData = BalanceFlags(1 << 0) + BalanceSystem = BalanceFlags(1 << 1) + BalanceMetadata = BalanceFlags(1 << 2) + + BalanceMask = (BalanceData | BalanceSystem | BalanceMetadata) + + BalanceForce = BalanceFlags(1 << 3) + BalanceResume = BalanceFlags(1 << 4) +) diff --git a/vendor/github.com/dennwc/btrfs/btrfs_list.go b/vendor/github.com/dennwc/btrfs/btrfs_list.go new file mode 100644 index 0000000..4929fe6 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/btrfs_list.go @@ -0,0 +1,22 @@ +package btrfs + +import "os" + +func getFileRootID(file *os.File) (objectID, error) { + args := btrfs_ioctl_ino_lookup_args{ + objectid: firstFreeObjectid, + } + if err := iocInoLookup(file, &args); err != nil { + return 0, err + } + return args.treeid, nil +} + +func getPathRootID(path string) (objectID, error) { + fs, err := Open(path, true) + if err != nil { + return 0, err + } + defer fs.Close() + return getFileRootID(fs.f) +} diff --git a/vendor/github.com/dennwc/btrfs/btrfs_tree.go b/vendor/github.com/dennwc/btrfs/btrfs_tree.go new file mode 100644 index 0000000..514e8cd --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/btrfs_tree.go @@ -0,0 +1,299 @@ +package btrfs + +import ( + "fmt" + "time" + "unsafe" +) + +const ( + _BTRFS_BLOCK_GROUP_TYPE_MASK = (blockGroupData | + blockGroupSystem | + blockGroupMetadata) + _BTRFS_BLOCK_GROUP_PROFILE_MASK = (blockGroupRaid0 | + blockGroupRaid1 | + blockGroupRaid5 | + blockGroupRaid6 | + blockGroupDup | + blockGroupRaid10) + _BTRFS_BLOCK_GROUP_MASK = _BTRFS_BLOCK_GROUP_TYPE_MASK | _BTRFS_BLOCK_GROUP_PROFILE_MASK +) + +type rootRef struct { + DirID objectID + Sequence uint64 + Name string +} + +func (rootRef) btrfsSize() int { return 18 } + +func asUint64(p []byte) uint64 { + return *(*uint64)(unsafe.Pointer(&p[0])) +} + +func asUint32(p []byte) uint32 { + return *(*uint32)(unsafe.Pointer(&p[0])) +} + +func asUint16(p []byte) uint16 { + return *(*uint16)(unsafe.Pointer(&p[0])) +} + +func asRootRef(p []byte) rootRef { + const sz = 18 + // assuming that it is highly unsafe to have sizeof(struct) > len(data) + // (*btrfs_root_ref)(unsafe.Pointer(&p[0])) and sizeof(btrfs_root_ref) == 24 + ref := rootRef{ + DirID: objectID(asUint64(p[0:])), + Sequence: asUint64(p[8:]), + } + if n := asUint16(p[16:]); n > 0 { + ref.Name = string(p[sz : sz+n : sz+n]) + } + return ref +} + +var treeKeyNames = map[treeKeyType]string{ + inodeItemKey: "inodeItem", + inodeRefKey: "inodeRef", + inodeExtrefKey: "inodeExtref", + xattrItemKey: "xattrItemKey", + orphanItemKey: "orphanItem", + dirLogItemKey: "dirLogItem", + dirLogIndexKey: "dirLogIndex", + dirItemKey: "dirItem", + dirIndexKey: "dirIndex", + extentDataKey: "extentData", + extentCsumKey: "extentCsum", + rootItemKey: "rootItem", + rootBackrefKey: "rootBackref", + rootRefKey: "rootRef", + extentItemKey: "extentItem", + metadataItemKey: "metadataItem", + treeBlockRefKey: "treeBlockRef", + extentDataRefKey: "extentDataRef", + extentRefV0Key: "extentRefV0", + sharedBlockRefKey: "sharedBlockRef", + sharedDataRefKey: "sharedDataRef", + blockGroupItemKey: "blockGroupItem", + freeSpaceInfoKey: "freeSpaceInfo", + freeSpaceExtentKey: "freeSpaceExtent", + freeSpaceBitmapKey: "freeSpaceBitmap", + devExtentKey: "devExtent", + devItemKey: "devItem", + chunkItemKey: "chunkItem", + qgroupStatusKey: "qgroupStatus", + qgroupInfoKey: "qgroupInfo", + qgroupLimitKey: "qgroupLimit", + qgroupRelationKey: "qgroupRelation", + temporaryItemKey: "temporaryItem", + persistentItemKey: "persistentItem", + devReplaceKey: "devReplace", + uuidKeySubvol: "uuidKeySubvol", + uuidKeyReceivedSubvol: "uuidKeyReceivedSubvol", + stringItemKey: "stringItem", +} + +func (t treeKeyType) String() string { + if name, ok := treeKeyNames[t]; ok { + return name + } + return fmt.Sprintf("%#x", int(t)) +} + +// btrfs_disk_key_raw is a raw bytes for btrfs_disk_key structure +type btrfs_disk_key_raw [17]byte + +func (p btrfs_disk_key_raw) Decode() diskKey { + return diskKey{ + ObjectID: asUint64(p[0:]), + Type: p[8], + Offset: asUint64(p[9:]), + } +} + +type diskKey struct { + ObjectID uint64 + Type byte + Offset uint64 +} + +// btrfs_timespec_raw is a raw bytes for btrfs_timespec structure. +type btrfs_timespec_raw [12]byte + +func (t btrfs_timespec_raw) Decode() time.Time { + sec, nsec := asUint64(t[0:]), asUint32(t[8:]) + return time.Unix(int64(sec), int64(nsec)) +} + +// timeBlock is a raw set of bytes for 4 time fields. +// It is used to keep correct alignment when accessing structures from btrfs. +type timeBlock [4]btrfs_timespec_raw + +type btrfs_inode_item_raw struct { + generation uint64 + transid uint64 + size uint64 + nbytes uint64 + block_group uint64 + nlink uint32 + uid uint32 + gid uint32 + mode uint32 + rdev uint64 + flags uint64 + sequence uint64 + _ [4]uint64 // reserved + // atime btrfs_timespec + // ctime btrfs_timespec + // mtime btrfs_timespec + // otime btrfs_timespec + times timeBlock +} + +func (v btrfs_inode_item_raw) Decode() inodeItem { + return inodeItem{ + Gen: v.generation, + TransID: v.transid, + Size: v.size, + NBytes: v.nbytes, + BlockGroup: v.block_group, + NLink: v.nlink, + UID: v.uid, + GID: v.gid, + Mode: v.mode, + RDev: v.rdev, + Flags: v.flags, + Sequence: v.sequence, + ATime: v.times[0].Decode(), + CTime: v.times[1].Decode(), + MTime: v.times[2].Decode(), + OTime: v.times[3].Decode(), + } +} + +type inodeItem struct { + Gen uint64 // nfs style generation number + TransID uint64 // transid that last touched this inode + Size uint64 + NBytes uint64 + BlockGroup uint64 + NLink uint32 + UID uint32 + GID uint32 + Mode uint32 + RDev uint64 + Flags uint64 + Sequence uint64 // modification sequence number for NFS + ATime time.Time + CTime time.Time + MTime time.Time + OTime time.Time +} + +func asRootItem(p []byte) *btrfs_root_item_raw { + return (*btrfs_root_item_raw)(unsafe.Pointer(&p[0])) +} + +type btrfs_root_item_raw [439]byte + +func (p btrfs_root_item_raw) Decode() rootItem { + const ( + off2 = unsafe.Sizeof(btrfs_root_item_raw_p1{}) + off3 = off2 + 23 + ) + p1 := (*btrfs_root_item_raw_p1)(unsafe.Pointer(&p[0])) + p2 := p[off2 : off2+23] + p2_k := (*btrfs_disk_key_raw)(unsafe.Pointer(&p[off2+4])) + p2_b := p2[4+17:] + p3 := (*btrfs_root_item_raw_p3)(unsafe.Pointer(&p[off3])) + return rootItem{ + Inode: p1.inode.Decode(), + Gen: p1.generation, + RootDirID: p1.root_dirid, + ByteNr: p1.bytenr, + ByteLimit: p1.byte_limit, + BytesUsed: p1.bytes_used, + LastSnapshot: p1.last_snapshot, + Flags: p1.flags, + // from here, Go structure become misaligned with C structure + Refs: asUint32(p2[0:]), + DropProgress: p2_k.Decode(), + DropLevel: p2_b[0], + Level: p2_b[1], + // these fields are still misaligned by 1 bytes + // TODO(dennwc): it's a copy of Gen to check structure version; hide it maybe? + GenV2: p3.generation_v2, + UUID: p3.uuid, + ParentUUID: p3.parent_uuid, + ReceivedUUID: p3.received_uuid, + CTransID: p3.ctransid, + OTransID: p3.otransid, + STransID: p3.stransid, + RTransID: p3.rtransid, + CTime: p3.times[0].Decode(), + OTime: p3.times[1].Decode(), + STime: p3.times[2].Decode(), + RTime: p3.times[3].Decode(), + } +} + +type rootItem struct { + Inode inodeItem + Gen uint64 + RootDirID uint64 + ByteNr uint64 + ByteLimit uint64 + BytesUsed uint64 + LastSnapshot uint64 + Flags uint64 + Refs uint32 + DropProgress diskKey + DropLevel uint8 + Level uint8 + GenV2 uint64 + UUID UUID + ParentUUID UUID + ReceivedUUID UUID + CTransID uint64 + OTransID uint64 + STransID uint64 + RTransID uint64 + CTime time.Time + OTime time.Time + STime time.Time + RTime time.Time +} + +type btrfs_root_item_raw_p1 struct { + inode btrfs_inode_item_raw + generation uint64 + root_dirid uint64 + bytenr uint64 + byte_limit uint64 + bytes_used uint64 + last_snapshot uint64 + flags uint64 +} +type btrfs_root_item_raw_p2 struct { + refs uint32 + drop_progress btrfs_disk_key_raw + drop_level uint8 + level uint8 +} +type btrfs_root_item_raw_p3 struct { + generation_v2 uint64 + uuid UUID + parent_uuid UUID + received_uuid UUID + ctransid uint64 + otransid uint64 + stransid uint64 + rtransid uint64 + // ctime btrfs_timespec + // otime btrfs_timespec + // stime btrfs_timespec + // rtime btrfs_timespec + times timeBlock + _ [8]uint64 // reserved +} diff --git a/vendor/github.com/dennwc/btrfs/btrfs_tree_h.go b/vendor/github.com/dennwc/btrfs/btrfs_tree_h.go new file mode 100644 index 0000000..d5ebd66 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/btrfs_tree_h.go @@ -0,0 +1,745 @@ +package btrfs + +/* + * This header contains the structure definitions and constants used + * by file system objects that can be retrieved using + * the _BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that + * is needed to describe a leaf node's key or item contents. + */ + +/* holds pointers to all of the tree roots */ + +/* stores information about which extents are in use, and reference counts */ + +/* + * chunk tree stores translations from logical -> physical block numbering + * the super block points to the chunk tree + */ + +/* + * stores information about which areas of a given device are in use. + * one per device. The tree of tree roots points to the device tree + */ + +/* one per subvolume, storing files and directories */ + +/* directory objectid inside the root tree */ + +/* holds checksums of all the data extents */ + +/* holds quota configuration and tracking */ + +/* for storing items that use the _BTRFS_UUID_KEY* types */ + +/* tracks free space in block groups. */ + +/* device stats in the device tree */ + +/* for storing balance parameters in the root tree */ + +/* orhpan objectid for tracking unlinked/truncated files */ + +/* does write ahead logging to speed up fsyncs */ + +/* for space balancing */ + +/* + * extent checksums all have this objectid + * this allows them to share the logging tree + * for fsyncs + */ + +/* For storing free space cache */ + +/* + * The inode number assigned to the special inode for storing + * free ino cache + */ + +/* dummy objectid represents multiple objectids */ + +/* + * All files have objectids in this range. + */ + +/* + * the device items go into the chunk tree. The key is in the form + * [ 1 _BTRFS_DEV_ITEM_KEY device_id ] + */ + +/* + * inode items have the data typically returned from stat and store other + * info about object characteristics. There is one for every file and dir in + * the FS + */ + +/* reserve 2-15 close to the inode for later flexibility */ + +/* + * dir items are the name -> inode pointers in a directory. There is one + * for every name in a directory. + */ + +/* + * extent data is for file data + */ + +/* + * extent csums are stored in a separate tree and hold csums for + * an entire extent on disk. + */ + +/* + * root items point to tree roots. They are typically in the root + * tree used by the super block to find all the other trees + */ + +/* + * root backrefs tie subvols and snapshots to the directory entries that + * reference them + */ + +/* + * root refs make a fast index for listing all of the snapshots and + * subvolumes referenced by a given root. They point directly to the + * directory item in the root that references the subvol + */ + +/* + * extent items are in the extent map tree. These record which blocks + * are used, and how many references there are to each block + */ + +/* + * The same as the _BTRFS_EXTENT_ITEM_KEY, except it's metadata we already know + * the length, so we save the level in key->offset instead of the length. + */ + +/* + * block groups give us hints into the extent allocation trees. Which + * blocks are free etc etc + */ + +/* + * Every block group is represented in the free space tree by a free space info + * item, which stores some accounting information. It is keyed on + * (block_group_start, FREE_SPACE_INFO, block_group_length). + */ + +/* + * A free space extent tracks an extent of space that is free in a block group. + * It is keyed on (start, FREE_SPACE_EXTENT, length). + */ + +/* + * When a block group becomes very fragmented, we convert it to use bitmaps + * instead of extents. A free space bitmap is keyed on + * (start, FREE_SPACE_BITMAP, length); the corresponding item is a bitmap with + * (length / sectorsize) bits. + */ + +/* + * Records the overall state of the qgroups. + * There's only one instance of this key present, + * (0, _BTRFS_QGROUP_STATUS_KEY, 0) + */ + +/* + * Records the currently used space of the qgroup. + * One key per qgroup, (0, _BTRFS_QGROUP_INFO_KEY, qgroupid). + */ + +/* + * Contains the user configured limits for the qgroup. + * One key per qgroup, (0, _BTRFS_QGROUP_LIMIT_KEY, qgroupid). + */ + +/* + * Records the child-parent relationship of qgroups. For + * each relation, 2 keys are present: + * (childid, _BTRFS_QGROUP_RELATION_KEY, parentid) + * (parentid, _BTRFS_QGROUP_RELATION_KEY, childid) + */ + +/* + * Obsolete name, see _BTRFS_TEMPORARY_ITEM_KEY. + */ + +/* + * The key type for tree items that are stored persistently, but do not need to + * exist for extended period of time. The items can exist in any tree. + * + * [subtype, _BTRFS_TEMPORARY_ITEM_KEY, data] + * + * Existing items: + * + * - balance status item + * (_BTRFS_BALANCE_OBJECTID, _BTRFS_TEMPORARY_ITEM_KEY, 0) + */ + +/* + * Obsolete name, see _BTRFS_PERSISTENT_ITEM_KEY + */ + +/* + * The key type for tree items that are stored persistently and usually exist + * for a long period, eg. filesystem lifetime. The item kinds can be status + * information, stats or preference values. The item can exist in any tree. + * + * [subtype, _BTRFS_PERSISTENT_ITEM_KEY, data] + * + * Existing items: + * + * - device statistics, store IO stats in the device tree, one key for all + * stats + * (_BTRFS_DEV_STATS_OBJECTID, _BTRFS_DEV_STATS_KEY, 0) + */ + +/* + * Persistantly stores the device replace state in the device tree. + * The key is built like this: (0, _BTRFS_DEV_REPLACE_KEY, 0). + */ + +/* + * Stores items that allow to quickly map UUIDs to something else. + * These items are part of the filesystem UUID tree. + * The key is built like this: + * (UUID_upper_64_bits, _BTRFS_UUID_KEY*, UUID_lower_64_bits). + */ + +/* for UUIDs assigned to * received subvols */ + +/* + * string items are for debugging. They just store a short string of + * data in the FS + */ + +/* 32 bytes in various csum fields */ + +/* csum types */ + +/* + * flags definitions for directory entry item type + * + * Used by: + * struct btrfs_dir_item.type + */ + +/* + * The key defines the order in the tree, and so it also defines (optimal) + * block layout. + * + * objectid corresponds to the inode number. + * + * type tells us things about the object, and is a kind of stream selector. + * so for a given inode, keys with type of 1 might refer to the inode data, + * type of 2 may point to file data in the btree and type == 3 may point to + * extents. + * + * offset is the starting byte offset for this key in the stream. + * + * btrfs_disk_key is in disk byte order. struct btrfs_key is always + * in cpu native order. Otherwise they are identical and their sizes + * should be the same (ie both packed) + */ +type btrfs_disk_key struct { + objectid uint64 + type_ uint8 + offset uint64 +} + +type btrfs_key struct { + objectid uint64 + type_ uint8 + offset uint64 +} + +type btrfs_dev_item struct { + devid uint64 + total_bytes uint64 + bytes_used uint64 + io_align uint32 + io_width uint32 + sector_size uint32 + type_ uint64 + generation uint64 + start_offset uint64 + dev_group uint32 + seek_speed uint8 + bandwidth uint8 + uuid UUID + fsid FSID +} + +type btrfs_stripe struct { + devid uint64 + offset uint64 + dev_uuid UUID +} + +type btrfs_chunk struct { + length uint64 + owner uint64 + stripe_len uint64 + type_ uint64 + io_align uint32 + io_width uint32 + sector_size uint32 + num_stripes uint16 + sub_stripes uint16 + stripe struct { + devid uint64 + offset uint64 + dev_uuid UUID + } +} + +/* additional stripes go here */ +type btrfs_free_space_entry struct { + offset uint64 + bytes uint64 + type_ uint8 +} + +type btrfs_free_space_header struct { + location struct { + objectid uint64 + type_ uint8 + offset uint64 + } + generation uint64 + num_entries uint64 + num_bitmaps uint64 +} + +/* Super block flags */ +/* Errors detected */ + +/* + * items in the extent btree are used to record the objectid of the + * owner of the block and the number of references + */ +type btrfs_extent_item struct { + refs uint64 + generation uint64 + flags uint64 +} + +type btrfs_extent_item_v0 struct { + refs uint32 +} + +/* following flags only apply to tree blocks */ + +/* use full backrefs for extent pointers in the block */ + +/* + * this flag is only used internally by scrub and may be changed at any time + * it is only declared here to avoid collisions + */ +type btrfs_tree_block_info struct { + key struct { + objectid uint64 + type_ uint8 + offset uint64 + } + level uint8 +} + +type btrfs_extent_data_ref struct { + root uint64 + objectid uint64 + offset uint64 + count uint32 +} + +type btrfs_shared_data_ref struct { + count uint32 +} + +type btrfs_extent_inline_ref struct { + type_ uint8 + offset uint64 +} + +/* old style backrefs item */ +type btrfs_extent_ref_v0 struct { + root uint64 + generation uint64 + objectid uint64 + count uint32 +} + +/* dev extents record free space on individual devices. The owner + * field points back to the chunk allocation mapping tree that allocated + * the extent. The chunk tree uuid field is a way to double check the owner + */ +type btrfs_dev_extent struct { + chunk_tree uint64 + chunk_objectid uint64 + chunk_offset uint64 + length uint64 + chunk_tree_uuid UUID +} + +type btrfs_inode_ref struct { + index uint64 + name_len uint16 +} + +/* name goes here */ +type btrfs_inode_extref struct { + parent_objectid uint64 + index uint64 + name_len uint16 + //name [0]uint8 +} + +/* name goes here */ +type btrfs_timespec struct { + sec uint64 + nsec uint32 +} + +type btrfs_inode_item struct { + generation uint64 + transid uint64 + size uint64 + nbytes uint64 + block_group uint64 + nlink uint32 + uid uint32 + gid uint32 + mode uint32 + rdev uint64 + flags uint64 + sequence uint64 + reserved [4]uint64 + atime struct { + sec uint64 + nsec uint32 + } + ctime struct { + sec uint64 + nsec uint32 + } + mtime struct { + sec uint64 + nsec uint32 + } + otime struct { + sec uint64 + nsec uint32 + } +} + +type btrfs_dir_log_item struct { + end uint64 +} + +type btrfs_dir_item struct { + location struct { + objectid uint64 + type_ uint8 + offset uint64 + } + transid uint64 + data_len uint16 + name_len uint16 + type_ uint8 +} + +/* + * Internal in-memory flag that a subvolume has been marked for deletion but + * still visible as a directory + */ +type btrfs_root_item struct { + inode struct { + generation uint64 + transid uint64 + size uint64 + nbytes uint64 + block_group uint64 + nlink uint32 + uid uint32 + gid uint32 + mode uint32 + rdev uint64 + flags uint64 + sequence uint64 + reserved [4]uint64 + atime struct { + sec uint64 + nsec uint32 + } + ctime struct { + sec uint64 + nsec uint32 + } + mtime struct { + sec uint64 + nsec uint32 + } + otime struct { + sec uint64 + nsec uint32 + } + } + generation uint64 + root_dirid uint64 + bytenr uint64 + byte_limit uint64 + bytes_used uint64 + last_snapshot uint64 + flags uint64 + refs uint32 + drop_progress struct { + objectid uint64 + type_ uint8 + offset uint64 + } + drop_level uint8 + level uint8 + generation_v2 uint64 + uuid UUID + parent_uuid UUID + received_uuid UUID + ctransid uint64 + otransid uint64 + stransid uint64 + rtransid uint64 + ctime struct { + sec uint64 + nsec uint32 + } + otime struct { + sec uint64 + nsec uint32 + } + stime struct { + sec uint64 + nsec uint32 + } + rtime struct { + sec uint64 + nsec uint32 + } + reserved [8]uint64 +} + +/* + * this is used for both forward and backward root refs + */ +type btrfs_root_ref struct { + dirid uint64 + sequence uint64 + name_len uint16 +} + +type btrfs_disk_balance_args struct { + profiles uint64 + usage uint64 + usage_min uint32 + usage_max uint32 + devid uint64 + pstart uint64 + pend uint64 + vstart uint64 + vend uint64 + target uint64 + flags uint64 + limit uint64 + limit_min uint32 + limit_max uint32 + stripes_min uint32 + stripes_max uint32 + unused [6]uint64 +} + +/* + * store balance parameters to disk so that balance can be properly + * resumed after crash or unmount + */ +type btrfs_balance_item struct { + flags uint64 + data struct { + profiles uint64 + usage uint64 + usage_min uint32 + usage_max uint32 + devid uint64 + pstart uint64 + pend uint64 + vstart uint64 + vend uint64 + target uint64 + flags uint64 + limit uint64 + limit_min uint32 + limit_max uint32 + stripes_min uint32 + stripes_max uint32 + unused [6]uint64 + } + meta struct { + profiles uint64 + usage uint64 + usage_min uint32 + usage_max uint32 + devid uint64 + pstart uint64 + pend uint64 + vstart uint64 + vend uint64 + target uint64 + flags uint64 + limit uint64 + limit_min uint32 + limit_max uint32 + stripes_min uint32 + stripes_max uint32 + unused [6]uint64 + } + sys struct { + profiles uint64 + usage uint64 + usage_min uint32 + usage_max uint32 + devid uint64 + pstart uint64 + pend uint64 + vstart uint64 + vend uint64 + target uint64 + flags uint64 + limit uint64 + limit_min uint32 + limit_max uint32 + stripes_min uint32 + stripes_max uint32 + unused [6]uint64 + } + unused [4]uint64 +} + +type btrfs_file_extent_item struct { + generation uint64 + ram_bytes uint64 + compression uint8 + encryption uint8 + other_encoding uint16 + type_ uint8 + disk_bytenr uint64 + disk_num_bytes uint64 + offset uint64 + num_bytes uint64 +} + +type btrfs_csum_item struct { + csum uint8 +} + +type btrfs_dev_stats_item struct { + values [_BTRFS_DEV_STAT_VALUES_MAX]uint64 +} + +type btrfs_dev_replace_item struct { + src_devid uint64 + cursor_left uint64 + cursor_right uint64 + cont_reading_from_srcdev_mode uint64 + replace_state uint64 + time_started uint64 + time_stopped uint64 + num_write_errors uint64 + num_uncorrectable_read_errors uint64 +} + +/* different types of block groups (and chunks) */ +const ( + _BTRFS_RAID_RAID10 = iota + _BTRFS_RAID_RAID1 + _BTRFS_RAID_DUP + _BTRFS_RAID_RAID0 + _BTRFS_RAID_SINGLE + _BTRFS_RAID_RAID5 + _BTRFS_RAID_RAID6 + _BTRFS_NR_RAID_TYPES +) + +/* + * We need a bit for restriper to be able to tell when chunks of type + * SINGLE are available. This "extended" profile format is used in + * fs_info->avail_*_alloc_bits (in-memory) and balance item fields + * (on-disk). The corresponding on-disk bit in chunk.type is reserved + * to avoid remappings between two formats in future. + */ + +/* + * A fake block group type that is used to communicate global block reserve + * size to userspace via the SPACE_INFO ioctl. + */ +func chunk_to_extended(flags uint64) uint64 { + if flags&uint64(_BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 { + flags |= uint64(availAllocBitSingle) + } + + return flags +} + +func extended_to_chunk(flags uint64) uint64 { + return flags &^ uint64(availAllocBitSingle) +} + +type btrfs_block_group_item struct { + used uint64 + chunk_objectid uint64 + flags uint64 +} + +type btrfs_free_space_info struct { + extent_count uint32 + flags uint32 +} + +func btrfs_qgroup_level(qgroupid uint64) uint64 { + return qgroupid >> uint32(qgroupLevelShift) +} + +/* + * is subvolume quota turned on? + */ + +/* + * RESCAN is set during the initialization phase + */ + +/* + * Some qgroup entries are known to be out of date, + * either because the configuration has changed in a way that + * makes a rescan necessary, or because the fs has been mounted + * with a non-qgroup-aware version. + * Turning qouta off and on again makes it inconsistent, too. + */ +type btrfs_qgroup_status_item struct { + version uint64 + generation uint64 + flags uint64 + rescan uint64 +} + +type btrfs_qgroup_info_item struct { + generation uint64 + rfer uint64 + rfer_cmpr uint64 + excl uint64 + excl_cmpr uint64 +} + +type btrfs_qgroup_limit_item struct { + flags uint64 + max_rfer uint64 + max_excl uint64 + rsv_rfer uint64 + rsv_excl uint64 +} diff --git a/vendor/github.com/dennwc/btrfs/btrfs_tree_hc.go b/vendor/github.com/dennwc/btrfs/btrfs_tree_hc.go new file mode 100644 index 0000000..fd79932 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/btrfs_tree_hc.go @@ -0,0 +1,502 @@ +package btrfs + +// This code was auto-generated; DO NOT EDIT! + +type treeKeyType uint32 + +type objectID uint64 + +type fileType int + +type fileExtentType int + +type devReplaceItemState int + +type blockGroup uint64 + +// This header contains the structure definitions and constants used +// by file system objects that can be retrieved using +// the BTRFS_IOC_SEARCH_TREE ioctl. That means basically anything that +// is needed to describe a leaf node's key or item contents. + +const ( + // Holds pointers to all of the tree roots + rootTreeObjectid objectID = 1 + + // Stores information about which extents are in use, and reference counts + extentTreeObjectid objectID = 2 + + // Chunk tree stores translations from logical -> physical block numbering + // the super block points to the chunk tree + chunkTreeObjectid objectID = 3 + + // Stores information about which areas of a given device are in use. + // one per device. The tree of tree roots points to the device tree + devTreeObjectid objectID = 4 + + // One per subvolume, storing files and directories + fsTreeObjectid objectID = 5 + + // Directory objectid inside the root tree + rootTreeDirObjectid objectID = 6 + + // Holds checksums of all the data extents + csumTreeObjectid objectID = 7 + + // Holds quota configuration and tracking + quotaTreeObjectid objectID = 8 + + // For storing items that use the BTRFS_UUID_KEY* types + uuidTreeObjectid objectID = 9 + + // Tracks free space in block groups. + freeSpaceTreeObjectid objectID = 10 + + // Device stats in the device tree + devStatsObjectid objectID = 0 + + // For storing balance parameters in the root tree + balanceObjectid objectID = (1<<64 - 4) + + // Orhpan objectid for tracking unlinked/truncated files + orphanObjectid objectID = (1<<64 - 5) + + // Does write ahead logging to speed up fsyncs + treeLogObjectid objectID = (1<<64 - 6) + treeLogFixupObjectid objectID = (1<<64 - 7) + + // For space balancing + treeRelocObjectid objectID = (1<<64 - 8) + dataRelocTreeObjectid objectID = (1<<64 - 9) + + // Extent checksums all have this objectid + // this allows them to share the logging tree + // for fsyncs + extentCsumObjectid objectID = (1<<64 - 10) + + // For storing free space cache + freeSpaceObjectid objectID = (1<<64 - 11) + + // The inode number assigned to the special inode for storing + // free ino cache + freeInoObjectid objectID = (1<<64 - 12) + + // Dummy objectid represents multiple objectids + multipleObjectids = (1<<64 - 255) + + // All files have objectids in this range. + firstFreeObjectid objectID = 256 + lastFreeObjectid objectID = (1<<64 - 256) + firstChunkTreeObjectid objectID = 256 + + // The device items go into the chunk tree. The key is in the form + // [ 1 BTRFS_DEV_ITEM_KEY device_id ] + devItemsObjectid objectID = 1 + + btreeInodeObjectid objectID = 1 + + emptySubvolDirObjectid objectID = 2 + + devReplaceDevid = 0 + + // Inode items have the data typically returned from stat and store other + // info about object characteristics. There is one for every file and dir in + // the FS + inodeItemKey treeKeyType = 1 + inodeRefKey treeKeyType = 12 + inodeExtrefKey treeKeyType = 13 + xattrItemKey treeKeyType = 24 + orphanItemKey treeKeyType = 48 + // Reserve 2-15 close to the inode for later flexibility + + // Dir items are the name -> inode pointers in a directory. There is one + // for every name in a directory. + dirLogItemKey treeKeyType = 60 + dirLogIndexKey treeKeyType = 72 + dirItemKey treeKeyType = 84 + dirIndexKey treeKeyType = 96 + // Extent data is for file data + extentDataKey treeKeyType = 108 + + // Extent csums are stored in a separate tree and hold csums for + // an entire extent on disk. + extentCsumKey treeKeyType = 128 + + // Root items point to tree roots. They are typically in the root + // tree used by the super block to find all the other trees + rootItemKey treeKeyType = 132 + + // Root backrefs tie subvols and snapshots to the directory entries that + // reference them + rootBackrefKey treeKeyType = 144 + + // Root refs make a fast index for listing all of the snapshots and + // subvolumes referenced by a given root. They point directly to the + // directory item in the root that references the subvol + rootRefKey treeKeyType = 156 + + // Extent items are in the extent map tree. These record which blocks + // are used, and how many references there are to each block + extentItemKey treeKeyType = 168 + + // The same as the BTRFS_EXTENT_ITEM_KEY, except it's metadata we already know + // the length, so we save the level in key->offset instead of the length. + metadataItemKey treeKeyType = 169 + + treeBlockRefKey treeKeyType = 176 + + extentDataRefKey treeKeyType = 178 + + extentRefV0Key treeKeyType = 180 + + sharedBlockRefKey treeKeyType = 182 + + sharedDataRefKey treeKeyType = 184 + + // Block groups give us hints into the extent allocation trees. Which + // blocks are free etc etc + blockGroupItemKey treeKeyType = 192 + + // Every block group is represented in the free space tree by a free space info + // item, which stores some accounting information. It is keyed on + // (block_group_start, FREE_SPACE_INFO, block_group_length). + freeSpaceInfoKey treeKeyType = 198 + + // A free space extent tracks an extent of space that is free in a block group. + // It is keyed on (start, FREE_SPACE_EXTENT, length). + freeSpaceExtentKey treeKeyType = 199 + + // When a block group becomes very fragmented, we convert it to use bitmaps + // instead of extents. A free space bitmap is keyed on + // (start, FREE_SPACE_BITMAP, length); the corresponding item is a bitmap with + // (length / sectorsize) bits. + freeSpaceBitmapKey treeKeyType = 200 + + devExtentKey treeKeyType = 204 + devItemKey treeKeyType = 216 + chunkItemKey treeKeyType = 228 + + // Records the overall state of the qgroups. + // There's only one instance of this key present, + // (0, BTRFS_QGROUP_STATUS_KEY, 0) + qgroupStatusKey treeKeyType = 240 + // Records the currently used space of the qgroup. + // One key per qgroup, (0, BTRFS_QGROUP_INFO_KEY, qgroupid). + qgroupInfoKey treeKeyType = 242 + // Contains the user configured limits for the qgroup. + // One key per qgroup, (0, BTRFS_QGROUP_LIMIT_KEY, qgroupid). + qgroupLimitKey treeKeyType = 244 + // Records the child-parent relationship of qgroups. For + // each relation, 2 keys are present: + // (childid, BTRFS_QGROUP_RELATION_KEY, parentid) + // (parentid, BTRFS_QGROUP_RELATION_KEY, childid) + qgroupRelationKey treeKeyType = 246 + + // Obsolete name, see BTRFS_TEMPORARY_ITEM_KEY. + balanceItemKey treeKeyType = 248 + + // The key type for tree items that are stored persistently, but do not need to + // exist for extended period of time. The items can exist in any tree. + // [subtype, BTRFS_TEMPORARY_ITEM_KEY, data] + // Existing items: + // - balance status item + // (BTRFS_BALANCE_OBJECTID, BTRFS_TEMPORARY_ITEM_KEY, 0) + temporaryItemKey treeKeyType = 248 + + // Obsolete name, see BTRFS_PERSISTENT_ITEM_KEY + devStatsKey treeKeyType = 249 + + // The key type for tree items that are stored persistently and usually exist + // for a long period, eg. filesystem lifetime. The item kinds can be status + // information, stats or preference values. The item can exist in any tree. + // [subtype, BTRFS_PERSISTENT_ITEM_KEY, data] + // Existing items: + // - device statistics, store IO stats in the device tree, one key for all + // stats + // (BTRFS_DEV_STATS_OBJECTID, BTRFS_DEV_STATS_KEY, 0) + persistentItemKey treeKeyType = 249 + + // Persistantly stores the device replace state in the device tree. + // The key is built like this: (0, BTRFS_DEV_REPLACE_KEY, 0). + devReplaceKey treeKeyType = 250 + + // Stores items that allow to quickly map UUIDs to something else. + // These items are part of the filesystem UUID tree. + // The key is built like this: + // (UUID_upper_64_bits, BTRFS_UUID_KEY*, UUID_lower_64_bits). + uuidKeySubvol = 251 + uuidKeyReceivedSubvol = 252 + + // String items are for debugging. They just store a short string of + // data in the FS + stringItemKey treeKeyType = 253 + + // 32 bytes in various csum fields + csumSize = 32 + + // Csum types + csumTypeCrc32 = 0 + + // Flags definitions for directory entry item type + // Used by: + // struct btrfs_dir_item.type + ftUnknown fileType = 0 + ftRegFile fileType = 1 + ftDir fileType = 2 + ftChrdev fileType = 3 + ftBlkdev fileType = 4 + ftFifo fileType = 5 + ftSock fileType = 6 + ftSymlink fileType = 7 + ftXattr fileType = 8 + ftMax fileType = 9 + + // The key defines the order in the tree, and so it also defines (optimal) + // block layout. + // objectid corresponds to the inode number. + // type tells us things about the object, and is a kind of stream selector. + // so for a given inode, keys with type of 1 might refer to the inode data, + // type of 2 may point to file data in the btree and type == 3 may point to + // extents. + // offset is the starting byte offset for this key in the stream. + // btrfs_disk_key is in disk byte order. struct btrfs_key is always + // in cpu native order. Otherwise they are identical and their sizes + // should be the same (ie both packed) + + // The internal btrfs device id + + // Size of the device + + // Bytes used + + // Optimal io alignment for this device + + // Optimal io width for this device + + // Minimal io size for this device + + // Type and info about this device + + // Expected generation for this device + + // Starting byte of this partition on the device, + // to allow for stripe alignment in the future + + // Grouping information for allocation decisions + + // Seek speed 0-100 where 100 is fastest + + // Bandwidth 0-100 where 100 is fastest + + // Btrfs generated uuid for this device + + // Uuid of FS who owns this device + + // Size of this chunk in bytes + + // Objectid of the root referencing this chunk + + // Optimal io alignment for this chunk + + // Optimal io width for this chunk + + // Minimal io size for this chunk + + // 2^16 stripes is quite a lot, a second limit is the size of a single + // item in the btree + + // Sub stripes only matter for raid10 + // Additional stripes go here + + freeSpaceExtent = 1 + freeSpaceBitmap = 2 + + headerFlagWritten = (1 << 0) + headerFlagReloc = (1 << 1) + + // Super block flags + // Errors detected + superFlagError = (1 << 2) + + superFlagSeeding = (1 << 32) + superFlagMetadump = (1 << 33) + + // Items in the extent btree are used to record the objectid of the + // owner of the block and the number of references + + extentFlagData = (1 << 0) + extentFlagTreeBlock = (1 << 1) + + // Following flags only apply to tree blocks + + // Use full backrefs for extent pointers in the block + blockFlagFullBackref = (1 << 8) + + // This flag is only used internally by scrub and may be changed at any time + // it is only declared here to avoid collisions + extentFlagSuper = (1 << 48) + + // Old style backrefs item + + // Dev extents record free space on individual devices. The owner + // field points back to the chunk allocation mapping tree that allocated + // the extent. The chunk tree uuid field is a way to double check the owner + + // Name goes here + + // Name goes here + + // Nfs style generation number + // Transid that last touched this inode + + // Modification sequence number for NFS + + // A little future expansion, for more than this we can + // just grow the inode item and version it + + rootSubvolRdonly = (1 << 0) + + // Internal in-memory flag that a subvolume has been marked for deletion but + // still visible as a directory + rootSubvolDead = (1 << 48) + + // The following fields appear after subvol_uuids+subvol_times + // were introduced. + + // This generation number is used to test if the new fields are valid + // and up to date while reading the root item. Every time the root item + // is written out, the "generation" field is copied into this field. If + // anyone ever mounted the fs with an older kernel, we will have + // mismatching generation values here and thus must invalidate the + // new fields. See btrfs_update_root and btrfs_find_last_root for + // details. + // the offset of generation_v2 is also used as the start for the memset + // when invalidating the fields. + + // This is used for both forward and backward root refs + + // Profiles to operate on, single is denoted by + // BTRFS_AVAIL_ALLOC_BIT_SINGLE + + // Usage filter + // BTRFS_BALANCE_ARGS_USAGE with a single value means '0..N' + // BTRFS_BALANCE_ARGS_USAGE_RANGE - range syntax, min..max + + // Devid filter + + // Devid subset filter [pstart..pend) + + // Btrfs virtual address space subset filter [vstart..vend) + + // Profile to convert to, single is denoted by + // BTRFS_AVAIL_ALLOC_BIT_SINGLE + + // BTRFS_BALANCE_ARGS_* + + // BTRFS_BALANCE_ARGS_LIMIT with value 'limit' + // BTRFS_BALANCE_ARGS_LIMIT_RANGE - the extend version can use minimum + // and maximum + + // Process chunks that cross stripes_min..stripes_max devices, + // BTRFS_BALANCE_ARGS_STRIPES_RANGE + + // Store balance parameters to disk so that balance can be properly + // resumed after crash or unmount + // BTRFS_BALANCE_* + + fileExtentInline fileExtentType = 0 + fileExtentReg fileExtentType = 1 + fileExtentPrealloc fileExtentType = 2 + + // Transaction id that created this extent + // Max number of bytes to hold this extent in ram + // when we split a compressed extent we can't know how big + // each of the resulting pieces will be. So, this is + // an upper limit on the size of the extent in ram instead of + // an exact limit. + + // 32 bits for the various ways we might encode the data, + // including compression and encryption. If any of these + // are set to something a given disk format doesn't understand + // it is treated like an incompat flag for reading and writing, + // but not for stat. + + // Are we inline data or a real extent? + + // Disk space consumed by the extent, checksum blocks are included + // in these numbers + // At this offset in the structure, the inline extent data start. + // The logical offset in file blocks (no csums) + // this extent record is for. This allows a file extent to point + // into the middle of an existing extent on disk, sharing it + // between two snapshots (useful if some bytes in the middle of the + // extent have changed + // The logical number of file blocks (no csums included). This + // always reflects the size uncompressed and without encoding. + + // Grow this item struct at the end for future enhancements and keep + // the existing values unchanged + + devReplaceItemContReadingFromSrcdevModeAlways = 0 + devReplaceItemContReadingFromSrcdevModeAvoid = 1 + devReplaceItemStateNeverStarted devReplaceItemState = 0 + devReplaceItemStateStarted devReplaceItemState = 1 + devReplaceItemStateSuspended devReplaceItemState = 2 + devReplaceItemStateFinished devReplaceItemState = 3 + devReplaceItemStateCanceled devReplaceItemState = 4 + + // Grow this item struct at the end for future enhancements and keep + // the existing values unchanged + + // Different types of block groups (and chunks) + blockGroupData blockGroup = (1 << 0) + blockGroupSystem blockGroup = (1 << 1) + blockGroupMetadata blockGroup = (1 << 2) + blockGroupRaid0 blockGroup = (1 << 3) + blockGroupRaid1 blockGroup = (1 << 4) + blockGroupDup blockGroup = (1 << 5) + blockGroupRaid10 blockGroup = (1 << 6) + blockGroupRaid5 blockGroup = (1 << 7) + blockGroupRaid6 blockGroup = (1 << 8) + + // We need a bit for restriper to be able to tell when chunks of type + // SINGLE are available. This "extended" profile format is used in + // fs_info->avail_*_alloc_bits (in-memory) and balance item fields + // (on-disk). The corresponding on-disk bit in chunk.type is reserved + // to avoid remappings between two formats in future. + availAllocBitSingle = (1 << 48) + + // A fake block group type that is used to communicate global block reserve + // size to userspace via the SPACE_INFO ioctl. + spaceInfoGlobalRsv = (1 << 49) + + freeSpaceUsingBitmaps = (1 << 0) + + qgroupLevelShift = 48 + + // Is subvolume quota turned on? + qgroupStatusFlagOn = (1 << 0) + // RESCAN is set during the initialization phase + qgroupStatusFlagRescan = (1 << 1) + // Some qgroup entries are known to be out of date, + // either because the configuration has changed in a way that + // makes a rescan necessary, or because the fs has been mounted + // with a non-qgroup-aware version. + // Turning qouta off and on again makes it inconsistent, too. + qgroupStatusFlagInconsistent = (1 << 2) + + qgroupStatusVersion = 1 + + // The generation is updated during every commit. As older + // versions of btrfs are not aware of qgroups, it will be + // possible to detect inconsistencies by checking the + // generation on mount time + + // Flag definitions see above + + // Only used during scanning to record the progress + // of the scan. It contains a logical address + + // Only updated when any of the other values change + +) diff --git a/vendor/github.com/dennwc/btrfs/errors.go b/vendor/github.com/dennwc/btrfs/errors.go new file mode 100644 index 0000000..b852bcf --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/errors.go @@ -0,0 +1,52 @@ +package btrfs + +import ( + "errors" + "fmt" +) + +type ErrNotBtrfs struct { + Path string +} + +func (e ErrNotBtrfs) Error() string { + return fmt.Sprintf("not a btrfs filesystem: %s", e.Path) +} + +// Error codes as returned by the kernel +type ErrCode int + +func (e ErrCode) Error() string { + s, ok := errorString[e] + if ok { + return s + } + return fmt.Sprintf("error %d", int(e)) +} + +const ( + ErrDevRAID1MinNotMet = ErrCode(iota + 1) + ErrDevRAID10MinNotMet + ErrDevRAID5MinNotMet + ErrDevRAID6MinNotMet + ErrDevTargetReplace + ErrDevMissingNotFound + ErrDevOnlyWritable + ErrDevExclRunInProgress +) + +var errorString = map[ErrCode]string{ + ErrDevRAID1MinNotMet: "unable to go below two devices on raid1", + ErrDevRAID10MinNotMet: "unable to go below four devices on raid10", + ErrDevRAID5MinNotMet: "unable to go below two devices on raid5", + ErrDevRAID6MinNotMet: "unable to go below three devices on raid6", + ErrDevTargetReplace: "unable to remove the dev_replace target dev", + ErrDevMissingNotFound: "no missing devices found to remove", + ErrDevOnlyWritable: "unable to remove the only writeable device", + ErrDevExclRunInProgress: "add/delete/balance/replace/resize operation in progress", +} + +var ( + ErrNotFound = errors.New("not found") + errNotImplemented = errors.New("not implemented") +) diff --git a/vendor/github.com/dennwc/btrfs/headers.go b/vendor/github.com/dennwc/btrfs/headers.go new file mode 100644 index 0000000..2ff5713 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/headers.go @@ -0,0 +1,4 @@ +package btrfs + +//go:generate go run ./cmd/hgen.go -u -g -t BTRFS_ -p btrfs -cs=treeKeyType:uint32=_KEY,objectID:uint64=_OBJECTID -cp=fileType=FT_,fileExtentType=FILE_EXTENT_,devReplaceItemState=DEV_REPLACE_ITEM_STATE_,blockGroup:uint64=BLOCK_GROUP_ -o btrfs_tree_hc.go btrfs_tree.h +//go:generate gofmt -l -w btrfs_tree_hc.go diff --git a/vendor/github.com/dennwc/btrfs/ioctl_h.go b/vendor/github.com/dennwc/btrfs/ioctl_h.go new file mode 100644 index 0000000..d31db71 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/ioctl_h.go @@ -0,0 +1,881 @@ +package btrfs + +import ( + "encoding/binary" + "encoding/hex" + "github.com/dennwc/ioctl" + "os" + "strconv" + "strings" + "unsafe" +) + +var order = binary.LittleEndian + +const ioctlMagic = 0x94 + +const devicePathNameMax = 1024 + +const ( + FSIDSize = 16 + UUIDSize = 16 +) + +var zeroUUID UUID + +type UUID [UUIDSize]byte + +func (id UUID) IsZero() bool { return id == zeroUUID } +func (id UUID) String() string { + if id.IsZero() { + return "" + } + buf := make([]byte, UUIDSize*2+4) + i := 0 + i += hex.Encode(buf[i:], id[:4]) + buf[i] = '-' + i++ + i += hex.Encode(buf[i:], id[4:6]) + buf[i] = '-' + i++ + i += hex.Encode(buf[i:], id[6:8]) + buf[i] = '-' + i++ + i += hex.Encode(buf[i:], id[8:10]) + buf[i] = '-' + i++ + i += hex.Encode(buf[i:], id[10:]) + return string(buf) +} + +type FSID [FSIDSize]byte + +func (id FSID) String() string { return hex.EncodeToString(id[:]) } + +const volNameMax = 4087 + +// this should be 4k +type btrfs_ioctl_vol_args struct { + fd int64 + name [volNameMax + 1]byte +} + +func (arg *btrfs_ioctl_vol_args) SetName(name string) { + n := copy(arg.name[:], name) + arg.name[n] = 0 +} + +type btrfs_qgroup_limit struct { + flags uint64 + max_referenced uint64 + max_exclusive uint64 + rsv_referenced uint64 + rsv_exclusive uint64 +} + +type btrfs_qgroup_inherit struct { + flags uint64 + num_qgroups uint64 + num_ref_copies uint64 + num_excl_copies uint64 + lim btrfs_qgroup_limit + //qgroups [0]uint64 +} + +type btrfs_ioctl_qgroup_limit_args struct { + qgroupid uint64 + lim btrfs_qgroup_limit +} + +type btrfs_ioctl_vol_args_v2_u1 struct { + size uint64 + qgroup_inherit *btrfs_qgroup_inherit +} + +const subvolNameMax = 4039 + +type SubvolFlags uint64 + +// Match flags like GetFlags translates in fs/btrfs/ioctl.c `btrfs_ioctl_subvol_getflags` +const subvolReadOnlyMask = (SubvolReadOnly | SubvolRootReadOnly) + +func (f SubvolFlags) ReadOnly() bool { + return f&subvolReadOnlyMask != 0 +} +func (f SubvolFlags) String() string { + if f == 0 { + return "" + } + var out []string + + if f.ReadOnly() { + out = append(out, "RO") + f = f & (^subvolReadOnlyMask) + } + if f != 0 { + out = append(out, "0x"+strconv.FormatInt(int64(f), 16)) + } + return strings.Join(out, "|") +} + +// flags for subvolumes +// +// Used by: +// struct btrfs_ioctl_vol_args_v2.flags +// +// BTRFS_SUBVOL_RDONLY is also provided/consumed by the following ioctls: +// - BTRFS_IOC_SUBVOL_GETFLAGS +// - BTRFS_IOC_SUBVOL_SETFLAGS +const ( + subvolCreateAsync = SubvolFlags(1 << 0) // deprecated in 5.7 + SubvolRootReadOnly = SubvolFlags(1 << 0) // BTRFS_ROOT_SUBVOL_RDONLY, only present in search result copies + SubvolReadOnly = SubvolFlags(1 << 1) // BTRFS_SUBVOL_RDONLY + subvolQGroupInherit = SubvolFlags(1 << 2) +) + +type btrfs_ioctl_vol_args_v2 struct { + fd int64 + transid uint64 + flags SubvolFlags + btrfs_ioctl_vol_args_v2_u1 + unused [2]uint64 + name [subvolNameMax + 1]byte +} + +// structure to report errors and progress to userspace, either as a +// result of a finished scrub, a canceled scrub or a progress inquiry +type btrfs_scrub_progress struct { + data_extents_scrubbed uint64 // # of data extents scrubbed + tree_extents_scrubbed uint64 // # of tree extents scrubbed + data_bytes_scrubbed uint64 // # of data bytes scrubbed + tree_bytes_scrubbed uint64 // # of tree bytes scrubbed + read_errors uint64 // # of read errors encountered (EIO) + csum_errors uint64 // # of failed csum checks + // # of occurences, where the metadata of a tree block did not match the expected values, like generation or logical + verify_errors uint64 + // # of 4k data block for which no csum is present, probably the result of data written with nodatasum + no_csum uint64 + csum_discards uint64 // # of csum for which no data was found in the extent tree. + super_errors uint64 // # of bad super blocks encountered + malloc_errors uint64 // # of internal kmalloc errors. These will likely cause an incomplete scrub + uncorrectable_errors uint64 // # of errors where either no intact copy was found or the writeback failed + corrected_errors uint64 // # of errors corrected + // last physical address scrubbed. In case a scrub was aborted, this can be used to restart the scrub + last_physical uint64 + // # of occurences where a read for a full (64k) bio failed, but the re- + // check succeeded for each 4k piece. Intermittent error. + unverified_errors uint64 +} + +type btrfs_ioctl_scrub_args struct { + devid uint64 // in + start uint64 // in + end uint64 // in + flags uint64 // in + progress btrfs_scrub_progress // out + // pad to 1k + _ [1024 - 4*8 - unsafe.Sizeof(btrfs_scrub_progress{})]byte +} + +type contReadingFromSrcdevMode uint64 + +const ( + _BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_ALWAYS contReadingFromSrcdevMode = 0 + _BTRFS_IOCTL_DEV_REPLACE_CONT_READING_FROM_SRCDEV_MODE_AVOID contReadingFromSrcdevMode = 1 +) + +type btrfs_ioctl_dev_replace_start_params struct { + srcdevid uint64 // in, if 0, use srcdev_name instead + cont_reading_from_srcdev_mode contReadingFromSrcdevMode // in + srcdev_name [devicePathNameMax + 1]byte // in + tgtdev_name [devicePathNameMax + 1]byte // in +} + +type devReplaceState uint64 + +const ( + _BTRFS_IOCTL_DEV_REPLACE_STATE_NEVER_STARTED devReplaceState = 0 + _BTRFS_IOCTL_DEV_REPLACE_STATE_STARTED devReplaceState = 1 + _BTRFS_IOCTL_DEV_REPLACE_STATE_FINISHED devReplaceState = 2 + _BTRFS_IOCTL_DEV_REPLACE_STATE_CANCELED devReplaceState = 3 + _BTRFS_IOCTL_DEV_REPLACE_STATE_SUSPENDED devReplaceState = 4 +) + +type btrfs_ioctl_dev_replace_status_params struct { + replace_state devReplaceState // out + progress_1000 uint64 // out, 0 <= x <= 1000 + time_started uint64 // out, seconds since 1-Jan-1970 + time_stopped uint64 // out, seconds since 1-Jan-1970 + num_write_errors uint64 // out + num_uncorrectable_read_errors uint64 // out +} + +type btrfs_ioctl_dev_replace_args_u1 struct { + cmd uint64 // in + result uint64 // out + start btrfs_ioctl_dev_replace_start_params // in + spare [64]uint64 +} + +type btrfs_ioctl_dev_replace_args_u2 struct { + cmd uint64 // in + result uint64 // out + status btrfs_ioctl_dev_replace_status_params // out + _ [unsafe.Sizeof(btrfs_ioctl_dev_replace_start_params{}) - unsafe.Sizeof(btrfs_ioctl_dev_replace_status_params{})]byte + spare [64]uint64 +} + +type btrfs_ioctl_dev_info_args struct { + devid uint64 // in/out + uuid UUID // in/out + bytes_used uint64 // out + total_bytes uint64 // out + _ [379]uint64 // pad to 4k + path [devicePathNameMax]byte // out +} + +type btrfs_ioctl_fs_info_args struct { + max_id uint64 // out + num_devices uint64 // out + fsid FSID // out + nodesize uint32 // out + sectorsize uint32 // out + clone_alignment uint32 // out + _ [122*8 + 4]byte // pad to 1k +} + +type btrfs_ioctl_feature_flags struct { + compat_flags FeatureFlags + compat_ro_flags FeatureFlags + incompat_flags IncompatFeatures +} + +type argRange [8]byte + +func (u argRange) asN() uint64 { + return order.Uint64(u[:]) +} +func (u argRange) asMinMax() (min, max uint32) { + return order.Uint32(u[:4]), order.Uint32(u[4:]) +} + +// balance control ioctl modes +//#define BTRFS_BALANCE_CTL_PAUSE 1 +//#define BTRFS_BALANCE_CTL_CANCEL 2 +//#define BTRFS_BALANCE_CTL_RESUME 3 + +// this is packed, because it should be exactly the same as its disk +// byte order counterpart (struct btrfs_disk_balance_args) +type btrfs_balance_args struct { + profiles uint64 + // usage filter + // BTRFS_BALANCE_ARGS_USAGE with a single value means '0..N' + // BTRFS_BALANCE_ARGS_USAGE_RANGE - range syntax, min..max + usage argRange + devid uint64 + pstart uint64 + pend uint64 + vstart uint64 + vend uint64 + target uint64 + flags uint64 + // BTRFS_BALANCE_ARGS_LIMIT with value 'limit' (limit number of processed chunks) + // BTRFS_BALANCE_ARGS_LIMIT_RANGE - the extend version can use minimum and maximum + limit argRange + stripes_min uint32 + stripes_max uint32 + _ [48]byte +} + +// Report balance progress to userspace. +// +// btrfs_balance_progress +type BalanceProgress struct { + Expected uint64 // estimated # of chunks that will be relocated to fulfill the request + Considered uint64 // # of chunks we have considered so far + Completed uint64 // # of chunks relocated so far +} + +type BalanceState uint64 + +const ( + BalanceStateRunning BalanceState = (1 << 0) + BalanceStatePauseReq BalanceState = (1 << 1) + BalanceStateCancelReq BalanceState = (1 << 2) +) + +type btrfs_ioctl_balance_args struct { + flags BalanceFlags // in/out + state BalanceState // out + data btrfs_balance_args // in/out + meta btrfs_balance_args // in/out + sys btrfs_balance_args // in/out + stat BalanceProgress // out + _ [72 * 8]byte // pad to 1k +} + +const _BTRFS_INO_LOOKUP_PATH_MAX = 4080 + +type btrfs_ioctl_ino_lookup_args struct { + treeid objectID + objectid objectID + name [_BTRFS_INO_LOOKUP_PATH_MAX]byte +} + +func (arg *btrfs_ioctl_ino_lookup_args) Name() string { + n := 0 + for i, b := range arg.name { + if b == '\x00' { + n = i + break + } + } + return string(arg.name[:n]) +} + +type btrfs_ioctl_search_key struct { + tree_id objectID // which root are we searching. 0 is the tree of tree roots + // keys returned will be >= min and <= max + min_objectid objectID + max_objectid objectID + // keys returned will be >= min and <= max + min_offset uint64 + max_offset uint64 + // max and min transids to search for + min_transid uint64 + max_transid uint64 + // keys returned will be >= min and <= max + min_type treeKeyType + max_type treeKeyType + // how many items did userland ask for, and how many are we returning + nr_items uint32 + _ [36]byte +} + +type btrfs_ioctl_search_header struct { + transid uint64 + objectid objectID + offset uint64 + typ treeKeyType + len uint32 +} + +const _BTRFS_SEARCH_ARGS_BUFSIZE = (4096 - unsafe.Sizeof(btrfs_ioctl_search_key{})) + +// the buf is an array of search headers where +// each header is followed by the actual item +// the type field is expanded to 32 bits for alignment +type btrfs_ioctl_search_args struct { + key btrfs_ioctl_search_key + buf [_BTRFS_SEARCH_ARGS_BUFSIZE]byte +} + +// Extended version of TREE_SEARCH ioctl that can return more than 4k of bytes. +// The allocated size of the buffer is set in buf_size. +type btrfs_ioctl_search_args_v2 struct { + key btrfs_ioctl_search_key // in/out - search parameters + buf_size uint64 // in - size of buffer; out - on EOVERFLOW: needed size to store item + //buf [0]uint64 // out - found items +} + +// With a @src_length of zero, the range from @src_offset->EOF is cloned! +type btrfs_ioctl_clone_range_args struct { + src_fd int64 + src_offset uint64 + src_length uint64 + dest_offset uint64 +} + +// flags for the defrag range ioctl +type defragRange uint64 + +const ( + _BTRFS_DEFRAG_RANGE_COMPRESS defragRange = 1 + _BTRFS_DEFRAG_RANGE_START_IO defragRange = 2 +) + +const _BTRFS_SAME_DATA_DIFFERS = 1 + +// For extent-same ioctl +type btrfs_ioctl_same_extent_info struct { + fd int64 // in - destination file + logical_offset uint64 // in - start of extent in destination + bytes_deduped uint64 // out - total # of bytes we were able to dedupe from this file + // out; status of this dedupe operation: + // 0 if dedup succeeds + // < 0 for error + // == BTRFS_SAME_DATA_DIFFERS if data differs + status int32 + reserved uint32 +} + +type btrfs_ioctl_same_args struct { + logical_offset uint64 // in - start of extent in source + length uint64 // in - length of extent + dest_count uint16 // in - total elements in info array + _ [6]byte + //info [0]btrfs_ioctl_same_extent_info +} + +type btrfs_ioctl_defrag_range_args struct { + start uint64 // start of the defrag operation + len uint64 // number of bytes to defrag, use (u64)-1 to say all + // flags for the operation, which can include turning + // on compression for this one defrag + flags uint64 + // any extent bigger than this will be considered + // already defragged. Use 0 to take the kernel default + // Use 1 to say every single extent must be rewritten + extent_thresh uint32 + // which compression method to use if turning on compression + // for this defrag operation. If unspecified, zlib will be used + compress_type uint32 + _ [16]byte // spare for later +} + +type btrfs_ioctl_space_info struct { + flags uint64 + total_bytes uint64 + used_bytes uint64 +} + +type btrfs_ioctl_space_args struct { + space_slots uint64 + total_spaces uint64 + //spaces [0]btrfs_ioctl_space_info +} + +type btrfs_data_container struct { + bytes_left uint32 // out -- bytes not needed to deliver output + bytes_missing uint32 // out -- additional bytes needed for result + elem_cnt uint32 // out + elem_missed uint32 // out + //val [0]uint64 +} + +type btrfs_ioctl_ino_path_args struct { + inum uint64 // in + size uint64 // in + _ [32]byte + // struct btrfs_data_container *fspath; out + fspath uint64 // out +} + +type btrfs_ioctl_logical_ino_args struct { + logical uint64 // in + size uint64 // in + _ [32]byte + // struct btrfs_data_container *inodes; out + inodes uint64 +} + +// disk I/O failure stats +const ( + _BTRFS_DEV_STAT_WRITE_ERRS = iota // EIO or EREMOTEIO from lower layers + _BTRFS_DEV_STAT_READ_ERRS // EIO or EREMOTEIO from lower layers + _BTRFS_DEV_STAT_FLUSH_ERRS // EIO or EREMOTEIO from lower layers + + // stats for indirect indications for I/O failures + + // checksum error, bytenr error or contents is illegal: this is an + // indication that the block was damaged during read or write, or written to + // wrong location or read from wrong location + _BTRFS_DEV_STAT_CORRUPTION_ERRS + _BTRFS_DEV_STAT_GENERATION_ERRS // an indication that blocks have not been written + + _BTRFS_DEV_STAT_VALUES_MAX +) + +// Reset statistics after reading; needs SYS_ADMIN capability +const _BTRFS_DEV_STATS_RESET = (1 << 0) + +type btrfs_ioctl_get_dev_stats struct { + devid uint64 // in + nr_items uint64 // in/out + flags uint64 // in/out + values [_BTRFS_DEV_STAT_VALUES_MAX]uint64 // out values + _ [128 - 2 - _BTRFS_DEV_STAT_VALUES_MAX]uint64 // pad to 1k +} + +const ( + _BTRFS_QUOTA_CTL_ENABLE = 1 + _BTRFS_QUOTA_CTL_DISABLE = 2 + // 3 has formerly been reserved for BTRFS_QUOTA_CTL_RESCAN +) + +type btrfs_ioctl_quota_ctl_args struct { + cmd uint64 + status uint64 +} + +type btrfs_ioctl_quota_rescan_args struct { + flags uint64 + progress uint64 + _ [6]uint64 +} + +type btrfs_ioctl_qgroup_assign_args struct { + assign uint64 + src uint64 + dst uint64 +} + +type btrfs_ioctl_qgroup_create_args struct { + create uint64 + qgroupid uint64 +} + +type btrfs_ioctl_timespec struct { + sec uint64 + nsec uint32 +} + +type btrfs_ioctl_received_subvol_args struct { + uuid UUID // in + stransid uint64 // in + rtransid uint64 // out + stime btrfs_ioctl_timespec // in + rtime btrfs_ioctl_timespec // out + flags uint64 // in + _ [16]uint64 // in +} + +const ( + // Caller doesn't want file data in the send stream, even if the + // search of clone sources doesn't find an extent. UPDATE_EXTENT + // commands will be sent instead of WRITE commands. + _BTRFS_SEND_FLAG_NO_FILE_DATA = 0x1 + // Do not add the leading stream header. Used when multiple snapshots + // are sent back to back. + _BTRFS_SEND_FLAG_OMIT_STREAM_HEADER = 0x2 + // Omit the command at the end of the stream that indicated the end + // of the stream. This option is used when multiple snapshots are + // sent back to back. + _BTRFS_SEND_FLAG_OMIT_END_CMD = 0x4 + + _BTRFS_SEND_FLAG_MASK = _BTRFS_SEND_FLAG_NO_FILE_DATA | + _BTRFS_SEND_FLAG_OMIT_STREAM_HEADER | + _BTRFS_SEND_FLAG_OMIT_END_CMD +) + +type btrfs_ioctl_send_args struct { + send_fd int64 // in + clone_sources_count uint64 // in + clone_sources *objectID // in + parent_root objectID // in + flags uint64 // in + _ [4]uint64 // in +} + +var ( + _BTRFS_IOC_SNAP_CREATE = ioctl.IOW(ioctlMagic, 1, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_DEFRAG = ioctl.IOW(ioctlMagic, 2, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_RESIZE = ioctl.IOW(ioctlMagic, 3, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_SCAN_DEV = ioctl.IOW(ioctlMagic, 4, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_TRANS_START = ioctl.IO(ioctlMagic, 6) + _BTRFS_IOC_TRANS_END = ioctl.IO(ioctlMagic, 7) + _BTRFS_IOC_SYNC = ioctl.IO(ioctlMagic, 8) + _BTRFS_IOC_CLONE = ioctl.IOW(ioctlMagic, 9, 4) // int32 + _BTRFS_IOC_ADD_DEV = ioctl.IOW(ioctlMagic, 10, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_RM_DEV = ioctl.IOW(ioctlMagic, 11, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_BALANCE = ioctl.IOW(ioctlMagic, 12, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_CLONE_RANGE = ioctl.IOW(ioctlMagic, 13, unsafe.Sizeof(btrfs_ioctl_clone_range_args{})) + _BTRFS_IOC_SUBVOL_CREATE = ioctl.IOW(ioctlMagic, 14, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_SNAP_DESTROY = ioctl.IOW(ioctlMagic, 15, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_DEFRAG_RANGE = ioctl.IOW(ioctlMagic, 16, unsafe.Sizeof(btrfs_ioctl_defrag_range_args{})) + _BTRFS_IOC_TREE_SEARCH = ioctl.IOWR(ioctlMagic, 17, unsafe.Sizeof(btrfs_ioctl_search_args{})) + _BTRFS_IOC_INO_LOOKUP = ioctl.IOWR(ioctlMagic, 18, unsafe.Sizeof(btrfs_ioctl_ino_lookup_args{})) + _BTRFS_IOC_DEFAULT_SUBVOL = ioctl.IOW(ioctlMagic, 19, 8) // uint64 + _BTRFS_IOC_SPACE_INFO = ioctl.IOWR(ioctlMagic, 20, unsafe.Sizeof(btrfs_ioctl_space_args{})) + _BTRFS_IOC_START_SYNC = ioctl.IOR(ioctlMagic, 24, 8) // uint64 + _BTRFS_IOC_WAIT_SYNC = ioctl.IOW(ioctlMagic, 22, 8) // uint64 + _BTRFS_IOC_SNAP_CREATE_V2 = ioctl.IOW(ioctlMagic, 23, unsafe.Sizeof(btrfs_ioctl_vol_args_v2{})) + _BTRFS_IOC_SUBVOL_CREATE_V2 = ioctl.IOW(ioctlMagic, 24, unsafe.Sizeof(btrfs_ioctl_vol_args_v2{})) + _BTRFS_IOC_SUBVOL_GETFLAGS = ioctl.IOR(ioctlMagic, 25, 8) // uint64 + _BTRFS_IOC_SUBVOL_SETFLAGS = ioctl.IOW(ioctlMagic, 26, 8) // uint64 + _BTRFS_IOC_SCRUB = ioctl.IOWR(ioctlMagic, 27, unsafe.Sizeof(btrfs_ioctl_scrub_args{})) + _BTRFS_IOC_SCRUB_CANCEL = ioctl.IO(ioctlMagic, 28) + _BTRFS_IOC_SCRUB_PROGRESS = ioctl.IOWR(ioctlMagic, 29, unsafe.Sizeof(btrfs_ioctl_scrub_args{})) + _BTRFS_IOC_DEV_INFO = ioctl.IOWR(ioctlMagic, 30, unsafe.Sizeof(btrfs_ioctl_dev_info_args{})) + _BTRFS_IOC_FS_INFO = ioctl.IOR(ioctlMagic, 31, unsafe.Sizeof(btrfs_ioctl_fs_info_args{})) + _BTRFS_IOC_BALANCE_V2 = ioctl.IOWR(ioctlMagic, 32, unsafe.Sizeof(btrfs_ioctl_balance_args{})) + _BTRFS_IOC_BALANCE_CTL = ioctl.IOW(ioctlMagic, 33, 4) // int32 + _BTRFS_IOC_BALANCE_PROGRESS = ioctl.IOR(ioctlMagic, 34, unsafe.Sizeof(btrfs_ioctl_balance_args{})) + _BTRFS_IOC_INO_PATHS = ioctl.IOWR(ioctlMagic, 35, unsafe.Sizeof(btrfs_ioctl_ino_path_args{})) + _BTRFS_IOC_LOGICAL_INO = ioctl.IOWR(ioctlMagic, 36, unsafe.Sizeof(btrfs_ioctl_ino_path_args{})) + _BTRFS_IOC_SET_RECEIVED_SUBVOL = ioctl.IOWR(ioctlMagic, 37, unsafe.Sizeof(btrfs_ioctl_received_subvol_args{})) + _BTRFS_IOC_SEND = ioctl.IOW(ioctlMagic, 38, unsafe.Sizeof(btrfs_ioctl_send_args{})) + _BTRFS_IOC_DEVICES_READY = ioctl.IOR(ioctlMagic, 39, unsafe.Sizeof(btrfs_ioctl_vol_args{})) + _BTRFS_IOC_QUOTA_CTL = ioctl.IOWR(ioctlMagic, 40, unsafe.Sizeof(btrfs_ioctl_quota_ctl_args{})) + _BTRFS_IOC_QGROUP_ASSIGN = ioctl.IOW(ioctlMagic, 41, unsafe.Sizeof(btrfs_ioctl_qgroup_assign_args{})) + _BTRFS_IOC_QGROUP_CREATE = ioctl.IOW(ioctlMagic, 42, unsafe.Sizeof(btrfs_ioctl_qgroup_create_args{})) + _BTRFS_IOC_QGROUP_LIMIT = ioctl.IOR(ioctlMagic, 43, unsafe.Sizeof(btrfs_ioctl_qgroup_limit_args{})) + _BTRFS_IOC_QUOTA_RESCAN = ioctl.IOW(ioctlMagic, 44, unsafe.Sizeof(btrfs_ioctl_quota_rescan_args{})) + _BTRFS_IOC_QUOTA_RESCAN_STATUS = ioctl.IOR(ioctlMagic, 45, unsafe.Sizeof(btrfs_ioctl_quota_rescan_args{})) + _BTRFS_IOC_QUOTA_RESCAN_WAIT = ioctl.IO(ioctlMagic, 46) + _BTRFS_IOC_GET_FSLABEL = ioctl.IOR(ioctlMagic, 49, labelSize) + _BTRFS_IOC_SET_FSLABEL = ioctl.IOW(ioctlMagic, 50, labelSize) + _BTRFS_IOC_GET_DEV_STATS = ioctl.IOWR(ioctlMagic, 52, unsafe.Sizeof(btrfs_ioctl_get_dev_stats{})) + _BTRFS_IOC_DEV_REPLACE = ioctl.IOWR(ioctlMagic, 53, unsafe.Sizeof(btrfs_ioctl_dev_replace_args_u1{})) + _BTRFS_IOC_FILE_EXTENT_SAME = ioctl.IOWR(ioctlMagic, 54, unsafe.Sizeof(btrfs_ioctl_same_args{})) + _BTRFS_IOC_GET_FEATURES = ioctl.IOR(ioctlMagic, 57, unsafe.Sizeof(btrfs_ioctl_feature_flags{})) + _BTRFS_IOC_SET_FEATURES = ioctl.IOW(ioctlMagic, 57, unsafe.Sizeof([2]btrfs_ioctl_feature_flags{})) + _BTRFS_IOC_GET_SUPPORTED_FEATURES = ioctl.IOR(ioctlMagic, 57, unsafe.Sizeof([3]btrfs_ioctl_feature_flags{})) +) + +func iocSnapCreate(f *os.File, in *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_SNAP_CREATE, in) +} + +func iocSnapCreateV2(f *os.File, in *btrfs_ioctl_vol_args_v2) error { + return ioctl.Do(f, _BTRFS_IOC_SNAP_CREATE_V2, in) +} + +func iocDefrag(f *os.File, out *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_DEFRAG, out) +} + +func iocResize(f *os.File, in *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_RESIZE, in) +} + +func iocScanDev(f *os.File, out *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_SCAN_DEV, out) +} + +func iocTransStart(f *os.File) error { + return ioctl.Do(f, _BTRFS_IOC_TRANS_START, nil) +} + +func iocTransEnd(f *os.File) error { + return ioctl.Do(f, _BTRFS_IOC_TRANS_END, nil) +} + +func iocSync(f *os.File) error { + return ioctl.Do(f, _BTRFS_IOC_SYNC, nil) +} + +func iocClone(dst, src *os.File) error { + return ioctl.Ioctl(dst, _BTRFS_IOC_CLONE, src.Fd()) +} + +func iocAddDev(f *os.File, out *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_ADD_DEV, out) +} + +func iocRmDev(f *os.File, out *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_RM_DEV, out) +} + +func iocBalance(f *os.File, out *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_BALANCE, out) +} + +func iocCloneRange(f *os.File, out *btrfs_ioctl_clone_range_args) error { + return ioctl.Do(f, _BTRFS_IOC_CLONE_RANGE, out) +} + +func iocSubvolCreate(f *os.File, in *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_SUBVOL_CREATE, in) +} + +func iocSubvolCreateV2(f *os.File, in *btrfs_ioctl_vol_args_v2) error { + return ioctl.Do(f, _BTRFS_IOC_SUBVOL_CREATE, in) +} + +func iocSnapDestroy(f *os.File, in *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_SNAP_DESTROY, in) +} + +func iocDefragRange(f *os.File, out *btrfs_ioctl_defrag_range_args) error { + return ioctl.Do(f, _BTRFS_IOC_DEFRAG_RANGE, out) +} + +func iocTreeSearch(f *os.File, out *btrfs_ioctl_search_args) error { + return ioctl.Do(f, _BTRFS_IOC_TREE_SEARCH, out) +} + +func iocInoLookup(f *os.File, out *btrfs_ioctl_ino_lookup_args) error { + return ioctl.Do(f, _BTRFS_IOC_INO_LOOKUP, out) +} + +func iocDefaultSubvol(f *os.File, out *uint64) error { + return ioctl.Do(f, _BTRFS_IOC_DEFAULT_SUBVOL, out) +} + +type spaceFlags uint64 + +func (f spaceFlags) BlockGroup() blockGroup { + return blockGroup(f) & _BTRFS_BLOCK_GROUP_MASK +} + +type spaceInfo struct { + Flags spaceFlags + TotalBytes uint64 + UsedBytes uint64 +} + +func iocSpaceInfo(f *os.File) ([]spaceInfo, error) { + arg := &btrfs_ioctl_space_args{} + if err := ioctl.Do(f, _BTRFS_IOC_SPACE_INFO, arg); err != nil { + return nil, err + } + n := arg.total_spaces + if n == 0 { + return nil, nil + } + const ( + argSize = unsafe.Sizeof(btrfs_ioctl_space_args{}) + infoSize = unsafe.Sizeof(btrfs_ioctl_space_info{}) + ) + buf := make([]byte, argSize+uintptr(n)*infoSize) + basePtr := unsafe.Pointer(&buf[0]) + arg = (*btrfs_ioctl_space_args)(basePtr) + arg.space_slots = n + if err := ioctl.Do(f, _BTRFS_IOC_SPACE_INFO, arg); err != nil { + return nil, err + } else if arg.total_spaces == 0 { + return nil, nil + } + if n > arg.total_spaces { + n = arg.total_spaces + } + out := make([]spaceInfo, n) + ptr := uintptr(basePtr) + argSize + for i := 0; i < int(n); i++ { + info := (*btrfs_ioctl_space_info)(unsafe.Pointer(ptr)) + out[i] = spaceInfo{ + Flags: spaceFlags(info.flags), + TotalBytes: info.total_bytes, + UsedBytes: info.used_bytes, + } + ptr += infoSize + } + return out, nil +} + +func iocStartSync(f *os.File, out *uint64) error { + return ioctl.Do(f, _BTRFS_IOC_START_SYNC, out) +} + +func iocWaitSync(f *os.File, out *uint64) error { + return ioctl.Do(f, _BTRFS_IOC_WAIT_SYNC, out) +} + +func iocSubvolGetflags(f *os.File) (out SubvolFlags, err error) { + err = ioctl.Do(f, _BTRFS_IOC_SUBVOL_GETFLAGS, &out) + return +} + +func iocSubvolSetflags(f *os.File, flags SubvolFlags) error { + v := uint64(flags) + return ioctl.Do(f, _BTRFS_IOC_SUBVOL_SETFLAGS, &v) +} + +func iocScrub(f *os.File, out *btrfs_ioctl_scrub_args) error { + return ioctl.Do(f, _BTRFS_IOC_SCRUB, out) +} + +func iocScrubCancel(f *os.File) error { + return ioctl.Do(f, _BTRFS_IOC_SCRUB_CANCEL, nil) +} + +func iocScrubProgress(f *os.File, out *btrfs_ioctl_scrub_args) error { + return ioctl.Do(f, _BTRFS_IOC_SCRUB_PROGRESS, out) +} + +func iocFsInfo(f *os.File) (out btrfs_ioctl_fs_info_args, err error) { + err = ioctl.Do(f, _BTRFS_IOC_FS_INFO, &out) + return +} + +func iocDevInfo(f *os.File, devid uint64, uuid UUID) (out btrfs_ioctl_dev_info_args, err error) { + out.devid = devid + out.uuid = uuid + err = ioctl.Do(f, _BTRFS_IOC_DEV_INFO, &out) + return +} + +func iocBalanceV2(f *os.File, out *btrfs_ioctl_balance_args) error { + return ioctl.Do(f, _BTRFS_IOC_BALANCE_V2, out) +} + +func iocBalanceCtl(f *os.File, out *int32) error { + return ioctl.Do(f, _BTRFS_IOC_BALANCE_CTL, out) +} + +func iocBalanceProgress(f *os.File, out *btrfs_ioctl_balance_args) error { + return ioctl.Do(f, _BTRFS_IOC_BALANCE_PROGRESS, out) +} + +func iocInoPaths(f *os.File, out *btrfs_ioctl_ino_path_args) error { + return ioctl.Do(f, _BTRFS_IOC_INO_PATHS, out) +} + +func iocLogicalIno(f *os.File, out *btrfs_ioctl_ino_path_args) error { + return ioctl.Do(f, _BTRFS_IOC_LOGICAL_INO, out) +} + +func iocSetReceivedSubvol(f *os.File, out *btrfs_ioctl_received_subvol_args) error { + return ioctl.Do(f, _BTRFS_IOC_SET_RECEIVED_SUBVOL, out) +} + +func iocSend(f *os.File, in *btrfs_ioctl_send_args) error { + return ioctl.Do(f, _BTRFS_IOC_SEND, in) +} + +func iocDevicesReady(f *os.File, out *btrfs_ioctl_vol_args) error { + return ioctl.Do(f, _BTRFS_IOC_DEVICES_READY, out) +} + +func iocQuotaCtl(f *os.File, out *btrfs_ioctl_quota_ctl_args) error { + return ioctl.Do(f, _BTRFS_IOC_QUOTA_CTL, out) +} + +func iocQgroupAssign(f *os.File, out *btrfs_ioctl_qgroup_assign_args) error { + return ioctl.Do(f, _BTRFS_IOC_QGROUP_ASSIGN, out) +} + +func iocQgroupCreate(f *os.File, out *btrfs_ioctl_qgroup_create_args) error { + return ioctl.Do(f, _BTRFS_IOC_QGROUP_CREATE, out) +} + +func iocQgroupLimit(f *os.File, out *btrfs_ioctl_qgroup_limit_args) error { + return ioctl.Do(f, _BTRFS_IOC_QGROUP_LIMIT, out) +} + +func iocQuotaRescan(f *os.File, out *btrfs_ioctl_quota_rescan_args) error { + return ioctl.Do(f, _BTRFS_IOC_QUOTA_RESCAN, out) +} + +func iocQuotaRescanStatus(f *os.File, out *btrfs_ioctl_quota_rescan_args) error { + return ioctl.Do(f, _BTRFS_IOC_QUOTA_RESCAN_STATUS, out) +} + +func iocQuotaRescanWait(f *os.File) error { + return ioctl.Do(f, _BTRFS_IOC_QUOTA_RESCAN_WAIT, nil) +} + +func iocGetFslabel(f *os.File, out *[labelSize]byte) error { + return ioctl.Do(f, _BTRFS_IOC_GET_FSLABEL, out) +} + +func iocSetFslabel(f *os.File, out *[labelSize]byte) error { + return ioctl.Do(f, _BTRFS_IOC_SET_FSLABEL, out) +} + +func iocGetDevStats(f *os.File, out *btrfs_ioctl_get_dev_stats) error { + return ioctl.Do(f, _BTRFS_IOC_GET_DEV_STATS, out) +} + +//func iocDevReplace(f *os.File, out *btrfs_ioctl_dev_replace_args) error { +// return ioctl.Do(f, _BTRFS_IOC_DEV_REPLACE, out) +//} + +func iocFileExtentSame(f *os.File, out *btrfs_ioctl_same_args) error { + return ioctl.Do(f, _BTRFS_IOC_FILE_EXTENT_SAME, out) +} + +func iocSetFeatures(f *os.File, out *[2]btrfs_ioctl_feature_flags) error { + return ioctl.Do(f, _BTRFS_IOC_SET_FEATURES, out) +} diff --git a/vendor/github.com/dennwc/btrfs/mtab/mtab.go b/vendor/github.com/dennwc/btrfs/mtab/mtab.go new file mode 100644 index 0000000..e1651ed --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/mtab/mtab.go @@ -0,0 +1,43 @@ +// Package mtab contains tools to work with /etc/mtab file. +package mtab + +import ( + "bufio" + "io" + "os" + "strings" +) + +type MountPoint struct { + Dev string + Mount string + Type string + Opts string +} + +// Mounts returns a list of mount point from /etc/mtab. +func Mounts() ([]MountPoint, error) { + file, err := os.Open("/etc/mtab") + if err != nil { + return nil, err + } + defer file.Close() + r := bufio.NewReader(file) + var out []MountPoint + for { + line, err := r.ReadString('\n') + if err == io.EOF { + break + } else if err != nil { + return nil, err + } + fields := strings.Fields(line) + out = append(out, MountPoint{ + Dev: fields[0], + Mount: fields[1], + Type: fields[2], + Opts: fields[3], + }) + } + return out, nil +} diff --git a/vendor/github.com/dennwc/btrfs/receive.go b/vendor/github.com/dennwc/btrfs/receive.go new file mode 100644 index 0000000..015714a --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/receive.go @@ -0,0 +1,58 @@ +package btrfs + +import ( + "bytes" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "syscall" +) + +const nativeReceive = false + +func Receive(r io.Reader, dstDir string) error { + if !nativeReceive { + buf := bytes.NewBuffer(nil) + cmd := exec.Command("btrfs", "receive", dstDir) + cmd.Stdin = r + cmd.Stderr = buf + if err := cmd.Run(); err != nil { + if buf.Len() != 0 { + return errors.New(buf.String()) + } + return err + } + return nil + } + var err error + dstDir, err = filepath.Abs(dstDir) + if err != nil { + return err + } + realMnt, err := findMountRoot(dstDir) + if err != nil { + return err + } + dir, err := os.OpenFile(dstDir, os.O_RDONLY|syscall.O_NOATIME, 0755) + if err != nil { + return err + } + mnt, err := os.OpenFile(realMnt, os.O_RDONLY|syscall.O_NOATIME, 0755) + if err != nil { + return err + } + // We want to resolve the path to the subvolume we're sitting in + // so that we can adjust the paths of any subvols we want to receive in. + subvolID, err := getFileRootID(mnt) + if err != nil { + return err + } + //sr, err := send.NewStreamReader(r) + //if err != nil { + // return err + //} + _, _ = dir, subvolID + panic("not implemented") +} diff --git a/vendor/github.com/dennwc/btrfs/send.go b/vendor/github.com/dennwc/btrfs/send.go new file mode 100644 index 0000000..0f324bb --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/send.go @@ -0,0 +1,245 @@ +package btrfs + +import ( + "fmt" + "io" + "os" + "path/filepath" + "unsafe" +) + +func Send(w io.Writer, parent string, subvols ...string) error { + if len(subvols) == 0 { + return nil + } + // use first send subvol to determine mount_root + subvol, err := filepath.Abs(subvols[0]) + if err != nil { + return err + } + mountRoot, err := findMountRoot(subvol) + if err == os.ErrNotExist { + return fmt.Errorf("cannot find a mountpoint for %s", subvol) + } else if err != nil { + return err + } + var ( + cloneSrc []objectID + parentID objectID + ) + if parent != "" { + parent, err = filepath.Abs(parent) + if err != nil { + return err + } + id, err := getPathRootID(parent) + if err != nil { + return fmt.Errorf("cannot get parent root id: %v", err) + } + parentID = id + cloneSrc = append(cloneSrc, id) + } + // check all subvolumes + paths := make([]string, 0, len(subvols)) + for _, sub := range subvols { + sub, err = filepath.Abs(sub) + if err != nil { + return err + } + paths = append(paths, sub) + mount, err := findMountRoot(sub) + if err != nil { + return fmt.Errorf("cannot find mount root for %v: %v", sub, err) + } else if mount != mountRoot { + return fmt.Errorf("all subvolumes must be from the same filesystem (%s is not)", sub) + } + ok, err := IsReadOnly(sub) + if err != nil { + return err + } else if !ok { + return fmt.Errorf("subvolume %s is not read-only", sub) + } + } + mfs, err := Open(mountRoot, true) + if err != nil { + return err + } + defer mfs.Close() + full := len(cloneSrc) == 0 + for i, sub := range paths { + var rootID objectID + if !full && parent != "" { + rel, err := filepath.Rel(mountRoot, sub) + if err != nil { + return err + } + si, err := subvolSearchByPath(mfs.f, rel) + if err != nil { + return fmt.Errorf("cannot find subvolume %s: %v", rel, err) + } + rootID = objectID(si.RootID) + parentID, err = findGoodParent(mfs.f, rootID, cloneSrc) + if err != nil { + return fmt.Errorf("cannot find good parent for %v: %v", rel, err) + } + } + fs, err := Open(sub, true) + if err != nil { + return err + } + var flags uint64 + if i != 0 { // not first + flags |= _BTRFS_SEND_FLAG_OMIT_STREAM_HEADER + } + if i < len(paths)-1 { // not last + flags |= _BTRFS_SEND_FLAG_OMIT_END_CMD + } + err = send(w, fs.f, parentID, cloneSrc, flags) + fs.Close() + if err != nil { + return fmt.Errorf("error sending %s: %v", sub, err) + } + if !full && parent != "" { + cloneSrc = append(cloneSrc, rootID) + } + } + return nil +} + +func send(w io.Writer, subvol *os.File, parent objectID, sources []objectID, flags uint64) error { + pr, pw, err := os.Pipe() + if err != nil { + return err + } + errc := make(chan error, 1) + go func() { + defer pr.Close() + _, err := io.Copy(w, pr) + errc <- err + }() + fd := pw.Fd() + wait := func() error { + pw.Close() + return <-errc + } + args := &btrfs_ioctl_send_args{ + send_fd: int64(fd), + parent_root: parent, + flags: flags, + } + if len(sources) != 0 { + args.clone_sources = &sources[0] + args.clone_sources_count = uint64(len(sources)) + } + if err := iocSend(subvol, args); err != nil { + wait() + return err + } + return wait() +} + +// readRootItem reads a root item from the tree. +// +// TODO(dennwc): support older kernels: +// In case we detect a root item smaller then sizeof(root_item), +// we know it's an old version of the root structure and initialize all new fields to zero. +// The same happens if we detect mismatching generation numbers as then we know the root was +// once mounted with an older kernel that was not aware of the root item structure change. +func readRootItem(mnt *os.File, rootID objectID) (*rootItem, error) { + sk := btrfs_ioctl_search_key{ + tree_id: rootTreeObjectid, + // There may be more than one ROOT_ITEM key if there are + // snapshots pending deletion, we have to loop through them. + min_objectid: rootID, + max_objectid: rootID, + min_type: rootItemKey, + max_type: rootItemKey, + max_offset: maxUint64, + max_transid: maxUint64, + nr_items: 4096, + } + for ; sk.min_offset < maxUint64; sk.min_offset++ { + results, err := treeSearchRaw(mnt, sk) + if err != nil { + return nil, err + } else if len(results) == 0 { + break + } + for _, r := range results { + sk.min_objectid = r.ObjectID + sk.min_type = r.Type + sk.min_offset = r.Offset + if r.ObjectID > rootID { + break + } + if r.ObjectID == rootID && r.Type == rootItemKey { + const sz = int(unsafe.Sizeof(btrfs_root_item_raw{})) + if len(r.Data) > sz { + return nil, fmt.Errorf("btrfs_root_item is larger than expected; kernel is newer than the library") + } else if len(r.Data) < sz { // TODO + return nil, fmt.Errorf("btrfs_root_item is smaller then expected; kernel version is too old") + } + p := asRootItem(r.Data).Decode() + return &p, nil + } + } + results = nil + if sk.min_type != rootItemKey || sk.min_objectid != rootID { + break + } + } + return nil, ErrNotFound +} + +func getParent(mnt *os.File, rootID objectID) (*SubvolInfo, error) { + st, err := subvolSearchByRootID(mnt, rootID, "") + if err != nil { + return nil, fmt.Errorf("cannot find subvolume %d to determine parent: %v", rootID, err) + } + return subvolSearchByUUID(mnt, st.ParentUUID) +} + +func findGoodParent(mnt *os.File, rootID objectID, cloneSrc []objectID) (objectID, error) { + parent, err := getParent(mnt, rootID) + if err != nil { + return 0, fmt.Errorf("get parent failed: %v", err) + } + for _, id := range cloneSrc { + if id == objectID(parent.RootID) { + return objectID(parent.RootID), nil + } + } + var ( + bestParent *SubvolInfo + bestDiff uint64 = maxUint64 + ) + for _, id := range cloneSrc { + parent2, err := getParent(mnt, id) + if err == ErrNotFound { + continue + } else if err != nil { + return 0, err + } + if parent2.RootID != parent.RootID { + continue + } + parent2, err = subvolSearchByRootID(mnt, id, "") + if err != nil { + return 0, err + } + diff := int64(parent2.CTransID - parent.CTransID) + if diff < 0 { + diff = -diff + } + if uint64(diff) < bestDiff { + bestParent, bestDiff = parent2, uint64(diff) + } + } + if bestParent != nil { + return objectID(bestParent.RootID), nil + } + if !parent.ParentUUID.IsZero() { + return findGoodParent(mnt, objectID(parent.RootID), cloneSrc) + } + return 0, ErrNotFound +} diff --git a/vendor/github.com/dennwc/btrfs/subvolume.go b/vendor/github.com/dennwc/btrfs/subvolume.go new file mode 100644 index 0000000..deed0af --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/subvolume.go @@ -0,0 +1,382 @@ +package btrfs + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "syscall" + "time" +) + +func checkSubVolumeName(name string) bool { + return name != "" && name[0] != 0 && !strings.ContainsRune(name, '/') && + name != "." && name != ".." +} + +func IsSubVolume(path string) (bool, error) { + var st syscall.Stat_t + if err := syscall.Stat(path, &st); err != nil { + return false, &os.PathError{Op: "stat", Path: path, Err: err} + } + if objectID(st.Ino) != firstFreeObjectid || + st.Mode&syscall.S_IFMT != syscall.S_IFDIR { + return false, nil + } + return isBtrfs(path) +} + +func CreateSubVolume(path string) error { + var inherit *btrfs_qgroup_inherit // TODO + + cpath, err := filepath.Abs(path) + if err != nil { + return err + } + newName := filepath.Base(cpath) + dstDir := filepath.Dir(cpath) + if !checkSubVolumeName(newName) { + return fmt.Errorf("invalid subvolume name: %s", newName) + } else if len(newName) >= volNameMax { + return fmt.Errorf("subvolume name too long: %s", newName) + } + dst, err := openDir(dstDir) + if err != nil { + return err + } + defer dst.Close() + if inherit != nil { + panic("not implemented") // TODO + args := btrfs_ioctl_vol_args_v2{ + flags: subvolQGroupInherit, + btrfs_ioctl_vol_args_v2_u1: btrfs_ioctl_vol_args_v2_u1{ + //size: qgroup_inherit_size(inherit), + qgroup_inherit: inherit, + }, + } + copy(args.name[:], newName) + return iocSubvolCreateV2(dst, &args) + } + var args btrfs_ioctl_vol_args + copy(args.name[:], newName) + return iocSubvolCreate(dst, &args) +} + +func DeleteSubVolume(path string) error { + if ok, err := IsSubVolume(path); err != nil { + return err + } else if !ok { + return fmt.Errorf("not a subvolume: %s", path) + } + cpath, err := filepath.Abs(path) + if err != nil { + return err + } + dname := filepath.Dir(cpath) + vname := filepath.Base(cpath) + + dir, err := openDir(dname) + if err != nil { + return err + } + defer dir.Close() + var args btrfs_ioctl_vol_args + copy(args.name[:], vname) + return iocSnapDestroy(dir, &args) +} + +func SnapshotSubVolume(subvol, dst string, ro bool) error { + if ok, err := IsSubVolume(subvol); err != nil { + return err + } else if !ok { + return fmt.Errorf("not a subvolume: %s", subvol) + } + exists := false + if st, err := os.Stat(dst); err != nil && !os.IsNotExist(err) { + return err + } else if err == nil { + if !st.IsDir() { + return fmt.Errorf("'%s' exists and it is not a directory", dst) + } + exists = true + } + var ( + newName string + dstDir string + ) + if exists { + newName = filepath.Base(subvol) + dstDir = dst + } else { + newName = filepath.Base(dst) + dstDir = filepath.Dir(dst) + } + if !checkSubVolumeName(newName) { + return fmt.Errorf("invalid snapshot name '%s'", newName) + } else if len(newName) >= volNameMax { + return fmt.Errorf("snapshot name too long '%s'", newName) + } + fdst, err := openDir(dstDir) + if err != nil { + return err + } + defer fdst.Close() + // TODO: make SnapshotSubVolume a method on FS to use existing fd + f, err := openDir(subvol) + if err != nil { + return fmt.Errorf("cannot open dest dir: %v", err) + } + defer f.Close() + args := btrfs_ioctl_vol_args_v2{ + fd: int64(f.Fd()), + } + if ro { + args.flags |= SubvolReadOnly + } + // TODO + //if inherit != nil { + // args.flags |= subvolQGroupInherit + // args.size = qgroup_inherit_size(inherit) + // args.qgroup_inherit = inherit + //} + copy(args.name[:], newName) + if err := iocSnapCreateV2(fdst, &args); err != nil { + return fmt.Errorf("snapshot create failed: %v", err) + } + return nil +} + +func IsReadOnly(path string) (bool, error) { + f, err := GetFlags(path) + if err != nil { + return false, err + } + return f.ReadOnly(), nil +} + +func GetFlags(path string) (SubvolFlags, error) { + fs, err := Open(path, true) + if err != nil { + return 0, err + } + defer fs.Close() + return fs.GetFlags() +} + +func listSubVolumes(f *os.File, filter func(SubvolInfo) bool) (map[objectID]SubvolInfo, error) { + sk := btrfs_ioctl_search_key{ + // search in the tree of tree roots + tree_id: rootTreeObjectid, + + // Set the min and max to backref keys. The search will + // only send back this type of key now. + min_type: rootItemKey, + max_type: rootBackrefKey, + + min_objectid: firstFreeObjectid, + + // Set all the other params to the max, we'll take any objectid + // and any trans. + max_objectid: lastFreeObjectid, + max_offset: maxUint64, + max_transid: maxUint64, + + nr_items: 4096, // just a big number, doesn't matter much + } + m := make(map[objectID]SubvolInfo) + for { + out, err := treeSearchRaw(f, sk) + if err != nil { + return nil, err + } else if len(out) == 0 { + break + } + for _, obj := range out { + switch obj.Type { + //case rootBackrefKey: + // ref := asRootRef(obj.Data) + // o := m[obj.ObjectID] + // o.TransID = obj.TransID + // o.ObjectID = obj.ObjectID + // o.RefTree = obj.Offset + // o.DirID = ref.DirID + // o.Name = ref.Name + // m[obj.ObjectID] = o + case rootItemKey: + o := m[obj.ObjectID] + o.RootID = uint64(obj.ObjectID) + robj := asRootItem(obj.Data).Decode() + o.fillFromItem(&robj) + m[obj.ObjectID] = o + } + } + // record the mins in key so we can make sure the + // next search doesn't repeat this root + last := out[len(out)-1] + sk.min_objectid = last.ObjectID + sk.min_type = last.Type + sk.min_offset = last.Offset + 1 + if sk.min_offset == 0 { // overflow + sk.min_type++ + } else { + continue + } + if sk.min_type > rootBackrefKey { + sk.min_type = rootItemKey + sk.min_objectid++ + } else { + continue + } + if sk.min_objectid > sk.max_objectid { + break + } + } + // resolve paths + for id, v := range m { + if path, err := subvolidResolve(f, id); err == ErrNotFound { + delete(m, id) + continue + } else if err != nil { + return m, fmt.Errorf("cannot resolve path for %v: %v", id, err) + } else { + v.Path = path + m[id] = v + } + if filter != nil && !filter(v) { + delete(m, id) + } + } + + return m, nil +} + +type SubvolInfo struct { + RootID uint64 + + Flags SubvolFlags + + UUID UUID + ParentUUID UUID + ReceivedUUID UUID + + CTime time.Time + OTime time.Time + STime time.Time + RTime time.Time + + CTransID uint64 + OTransID uint64 + STransID uint64 + RTransID uint64 + + Path string +} + +func (s *SubvolInfo) fillFromItem(it *rootItem) { + s.UUID = it.UUID + s.ReceivedUUID = it.ReceivedUUID + s.ParentUUID = it.ParentUUID + s.Flags = SubvolFlags(it.Flags) + + s.CTime = it.CTime + s.OTime = it.OTime + s.STime = it.STime + s.RTime = it.RTime + + s.CTransID = it.CTransID + s.OTransID = it.OTransID + s.STransID = it.STransID + s.RTransID = it.RTransID +} + +func subvolSearchByUUID(mnt *os.File, uuid UUID) (*SubvolInfo, error) { + id, err := lookupUUIDSubvolItem(mnt, uuid) + if err != nil { + return nil, err + } + return subvolSearchByRootID(mnt, id, "") +} + +func subvolSearchByReceivedUUID(mnt *os.File, uuid UUID) (*SubvolInfo, error) { + id, err := lookupUUIDReceivedSubvolItem(mnt, uuid) + if err != nil { + return nil, err + } + return subvolSearchByRootID(mnt, id, "") +} + +func subvolSearchByPath(mnt *os.File, path string) (*SubvolInfo, error) { + if !filepath.IsAbs(path) { + path = filepath.Join(mnt.Name(), path) + } + id, err := getPathRootID(path) + if err != nil { + return nil, err + } + return subvolSearchByRootID(mnt, id, path) +} + +func subvolidResolve(mnt *os.File, subvolID objectID) (string, error) { + return subvolidResolveSub(mnt, "", subvolID) +} + +func subvolidResolveSub(mnt *os.File, path string, subvolID objectID) (string, error) { + if subvolID == fsTreeObjectid { + return "", nil + } + sk := btrfs_ioctl_search_key{ + tree_id: rootTreeObjectid, + min_objectid: subvolID, + max_objectid: subvolID, + min_type: rootBackrefKey, + max_type: rootBackrefKey, + max_offset: maxUint64, + max_transid: maxUint64, + nr_items: 1, + } + results, err := treeSearchRaw(mnt, sk) + if err != nil { + return "", err + } else if len(results) < 1 { + return "", ErrNotFound + } + res := results[0] + if objectID(res.Offset) != fsTreeObjectid { + spath, err := subvolidResolveSub(mnt, path, objectID(res.Offset)) + if err != nil { + return "", err + } + path = spath + "/" + } + backRef := asRootRef(res.Data) + if backRef.DirID != firstFreeObjectid { + arg := btrfs_ioctl_ino_lookup_args{ + treeid: objectID(res.Offset), + objectid: backRef.DirID, + } + if err := iocInoLookup(mnt, &arg); err != nil { + return "", err + } + path += arg.Name() + } + return path + backRef.Name, nil +} + +// subvolSearchByRootID +// +// Path is optional, and will be resolved automatically if not set. +func subvolSearchByRootID(mnt *os.File, rootID objectID, path string) (*SubvolInfo, error) { + robj, err := readRootItem(mnt, rootID) + if err != nil { + return nil, err + } + info := &SubvolInfo{ + RootID: uint64(rootID), + Path: path, + } + info.fillFromItem(robj) + if path == "" { + info.Path, err = subvolidResolve(mnt, objectID(info.RootID)) + } + return info, err +} diff --git a/vendor/github.com/dennwc/btrfs/usage.go b/vendor/github.com/dennwc/btrfs/usage.go new file mode 100644 index 0000000..792ea86 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/usage.go @@ -0,0 +1,176 @@ +package btrfs + +import ( + "os" + "sort" + "syscall" +) + +func cmpChunkBlockGroup(f1, f2 blockGroup) int { + var mask blockGroup + + if (f1 & _BTRFS_BLOCK_GROUP_TYPE_MASK) == + (f2 & _BTRFS_BLOCK_GROUP_TYPE_MASK) { + mask = _BTRFS_BLOCK_GROUP_PROFILE_MASK + } else if f2&blockGroupSystem != 0 { + return -1 + } else if f1&blockGroupSystem != 0 { + return +1 + } else { + mask = _BTRFS_BLOCK_GROUP_TYPE_MASK + } + + if (f1 & mask) > (f2 & mask) { + return +1 + } else if (f1 & mask) < (f2 & mask) { + return -1 + } else { + return 0 + } +} + +type spaceInfoByBlockGroup []spaceInfo + +func (a spaceInfoByBlockGroup) Len() int { return len(a) } +func (a spaceInfoByBlockGroup) Swap(i, j int) { a[i], a[j] = a[j], a[i] } +func (a spaceInfoByBlockGroup) Less(i, j int) bool { + return cmpChunkBlockGroup(blockGroup(a[i].Flags), blockGroup(a[j].Flags)) < 0 +} + +type UsageInfo struct { + Total uint64 + TotalUnused uint64 + TotalUsed uint64 + TotalChunks uint64 + + FreeEstimated uint64 + FreeMin uint64 + + LogicalDataChunks uint64 + RawDataChunks uint64 + RawDataUsed uint64 + + LogicalMetaChunks uint64 + RawMetaChunks uint64 + RawMetaUsed uint64 + + SystemUsed uint64 + SystemChunks uint64 + + DataRatio float64 + MetadataRatio float64 + + GlobalReserve uint64 + GlobalReserveUsed uint64 +} + +const minUnallocatedThreshold = 16 * 1024 * 1024 + +func spaceUsage(f *os.File) (UsageInfo, error) { + info, err := iocFsInfo(f) + if err != nil { + return UsageInfo{}, err + } + var u UsageInfo + for i := uint64(0); i <= info.max_id; i++ { + dev, err := iocDevInfo(f, i, UUID{}) + if err == syscall.ENODEV { + continue + } else if err != nil { + return UsageInfo{}, err + } + u.Total += dev.total_bytes + } + + spaces, err := iocSpaceInfo(f) + if err != nil { + return UsageInfo{}, err + } + sort.Sort(spaceInfoByBlockGroup(spaces)) + var ( + maxDataRatio int = 1 + mixed bool + ) + for _, s := range spaces { + ratio := 1 + bg := s.Flags.BlockGroup() + switch { + case bg&blockGroupRaid0 != 0: + ratio = 1 + case bg&blockGroupRaid1 != 0: + ratio = 2 + case bg&blockGroupRaid5 != 0: + ratio = 0 + case bg&blockGroupRaid6 != 0: + ratio = 0 + case bg&blockGroupDup != 0: + ratio = 2 + case bg&blockGroupRaid10 != 0: + ratio = 2 + } + if ratio > maxDataRatio { + maxDataRatio = ratio + } + if bg&spaceInfoGlobalRsv != 0 { + u.GlobalReserve = s.TotalBytes + u.GlobalReserveUsed = s.UsedBytes + } + if bg&(blockGroupData|blockGroupMetadata) == (blockGroupData | blockGroupMetadata) { + mixed = true + } + if bg&blockGroupData != 0 { + u.RawDataUsed += s.UsedBytes * uint64(ratio) + u.RawDataChunks += s.TotalBytes * uint64(ratio) + u.LogicalDataChunks += s.TotalBytes + } + if bg&blockGroupMetadata != 0 { + u.RawMetaUsed += s.UsedBytes * uint64(ratio) + u.RawMetaChunks += s.TotalBytes * uint64(ratio) + u.LogicalMetaChunks += s.TotalBytes + } + if bg&blockGroupSystem != 0 { + u.SystemUsed += s.UsedBytes * uint64(ratio) + u.SystemChunks += s.TotalBytes * uint64(ratio) + } + } + u.TotalChunks = u.RawDataChunks + u.SystemChunks + u.TotalUsed = u.RawDataUsed + u.SystemUsed + if !mixed { + u.TotalChunks += u.RawMetaChunks + u.TotalUsed += u.RawMetaUsed + } + u.TotalUnused = u.Total - u.TotalChunks + + u.DataRatio = float64(u.RawDataChunks) / float64(u.LogicalDataChunks) + if mixed { + u.MetadataRatio = u.DataRatio + } else { + u.MetadataRatio = float64(u.RawMetaChunks) / float64(u.LogicalMetaChunks) + } + + // We're able to fill at least DATA for the unused space + // + // With mixed raid levels, this gives a rough estimate but more + // accurate than just counting the logical free space + // (l_data_chunks - l_data_used) + // + // In non-mixed case there's no difference. + u.FreeEstimated = uint64(float64(u.RawDataChunks-u.RawDataUsed) / u.DataRatio) + + // For mixed-bg the metadata are left out in calculations thus global + // reserve would be lost. Part of it could be permanently allocated, + // we have to subtract the used bytes so we don't go under zero free. + if mixed { + u.FreeEstimated -= u.GlobalReserve - u.GlobalReserveUsed + } + u.FreeMin = u.FreeEstimated + + // Chop unallocatable space + // FIXME: must be applied per device + if u.TotalUnused >= minUnallocatedThreshold { + u.FreeEstimated += uint64(float64(u.TotalUnused) / u.DataRatio) + // Match the calculation of 'df', use the highest raid ratio + u.FreeMin += u.TotalUnused / uint64(maxDataRatio) + } + return u, nil +} diff --git a/vendor/github.com/dennwc/btrfs/utils.go b/vendor/github.com/dennwc/btrfs/utils.go new file mode 100644 index 0000000..bbf96e3 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/utils.go @@ -0,0 +1,107 @@ +package btrfs + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "syscall" + "unsafe" + + "github.com/dennwc/btrfs/mtab" +) + +func isBtrfs(path string) (bool, error) { + var stfs syscall.Statfs_t + if err := syscall.Statfs(path, &stfs); err != nil { + return false, &os.PathError{Op: "statfs", Path: path, Err: err} + } + fsType := uint32(stfs.Type) + return fsType == SuperMagic, nil +} + +func findMountRoot(path string) (string, error) { + mounts, err := mtab.Mounts() + if err != nil { + return "", err + } + longest := "" + isBtrfs := false + for _, m := range mounts { + if !strings.HasPrefix(path, m.Mount) { + continue + } + if len(longest) < len(m.Mount) { + longest = m.Mount + isBtrfs = m.Type == "btrfs" + } + } + if longest == "" { + return "", os.ErrNotExist + } else if !isBtrfs { + return "", ErrNotBtrfs{Path: longest} + } + return filepath.Abs(longest) +} + +// openDir does the following checks before calling Open: +// 1: path is in a btrfs filesystem +// 2: path is a directory +func openDir(path string) (*os.File, error) { + if ok, err := isBtrfs(path); err != nil { + return nil, err + } else if !ok { + return nil, ErrNotBtrfs{Path: path} + } + file, err := os.Open(path) + if err != nil { + return nil, err + } else if st, err := file.Stat(); err != nil { + file.Close() + return nil, err + } else if !st.IsDir() { + file.Close() + return nil, fmt.Errorf("not a directory: %s", path) + } + return file, nil +} + +type searchResult struct { + TransID uint64 + ObjectID objectID + Type treeKeyType + Offset uint64 + Data []byte +} + +func treeSearchRaw(mnt *os.File, key btrfs_ioctl_search_key) (out []searchResult, _ error) { + args := btrfs_ioctl_search_args{ + key: key, + } + if err := iocTreeSearch(mnt, &args); err != nil { + return nil, err + } + out = make([]searchResult, 0, args.key.nr_items) + buf := args.buf[:] + for i := 0; i < int(args.key.nr_items); i++ { + h := (*btrfs_ioctl_search_header)(unsafe.Pointer(&buf[0])) + buf = buf[unsafe.Sizeof(btrfs_ioctl_search_header{}):] + out = append(out, searchResult{ + TransID: h.transid, + ObjectID: h.objectid, + Offset: h.offset, + Type: h.typ, + Data: buf[:h.len:h.len], // TODO: reallocate? + }) + buf = buf[h.len:] + } + return out, nil +} + +func stringFromBytes(input []byte) string { + if i := bytes.IndexByte(input, 0); i >= 0 { + input = input[:i] + } + return string(input) +} diff --git a/vendor/github.com/dennwc/btrfs/uuid_tree.go b/vendor/github.com/dennwc/btrfs/uuid_tree.go new file mode 100644 index 0000000..4906ad0 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/uuid_tree.go @@ -0,0 +1,49 @@ +package btrfs + +import ( + "encoding/binary" + "fmt" + "os" +) + +func lookupUUIDSubvolItem(f *os.File, uuid UUID) (objectID, error) { + return uuidTreeLookupAny(f, uuid, uuidKeySubvol) +} + +func lookupUUIDReceivedSubvolItem(f *os.File, uuid UUID) (objectID, error) { + return uuidTreeLookupAny(f, uuid, uuidKeyReceivedSubvol) +} + +func (id UUID) toKey() (objID objectID, off uint64) { + objID = objectID(binary.LittleEndian.Uint64(id[:8])) + off = binary.LittleEndian.Uint64(id[8:16]) + return +} + +// uuidTreeLookupAny searches uuid tree for a given uuid in specified field. +// It returns ErrNotFound if object was not found. +func uuidTreeLookupAny(f *os.File, uuid UUID, typ treeKeyType) (objectID, error) { + objId, off := uuid.toKey() + args := btrfs_ioctl_search_key{ + tree_id: uuidTreeObjectid, + min_objectid: objId, + max_objectid: objId, + min_type: typ, + max_type: typ, + min_offset: off, + max_offset: off, + max_transid: maxUint64, + nr_items: 1, + } + res, err := treeSearchRaw(f, args) + if err != nil { + return 0, err + } else if len(res) < 1 { + return 0, ErrNotFound + } + out := res[0] + if len(out.Data) != 8 { + return 0, fmt.Errorf("btrfs: uuid item with illegal size %d", len(out.Data)) + } + return objectID(binary.LittleEndian.Uint64(out.Data)), nil +} diff --git a/vendor/github.com/dennwc/btrfs/xattr.go b/vendor/github.com/dennwc/btrfs/xattr.go new file mode 100644 index 0000000..ae4b7d2 --- /dev/null +++ b/vendor/github.com/dennwc/btrfs/xattr.go @@ -0,0 +1,66 @@ +package btrfs + +import ( + "bytes" + "os" + "syscall" +) + +const ( + xattrPrefix = "btrfs." + xattrCompression = xattrPrefix + "compression" +) + +type Compression string + +const ( + CompressionNone = Compression("") + LZO = Compression("lzo") + ZLIB = Compression("zlib") +) + +func SetCompression(path string, v Compression) error { + var value []byte + if v != CompressionNone { + var err error + value, err = syscall.ByteSliceFromString(string(v)) + if err != nil { + return err + } + } + err := syscall.Setxattr(path, xattrCompression, value, 0) + if err != nil { + return &os.PathError{Op: "setxattr", Path: path, Err: err} + } + return nil +} + +func GetCompression(path string) (Compression, error) { + var buf []byte + for { + sz, err := syscall.Getxattr(path, xattrCompression, nil) + if err == syscall.ENODATA || sz == 0 { + return CompressionNone, nil + } else if err != nil { + return CompressionNone, &os.PathError{Op: "getxattr", Path: path, Err: err} + } + if cap(buf) < sz { + buf = make([]byte, sz) + } else { + buf = buf[:sz] + } + sz, err = syscall.Getxattr(path, xattrCompression, buf) + if err == syscall.ENODATA { + return CompressionNone, nil + } else if err == syscall.ERANGE { + // xattr changed by someone else, and is larger than our current buffer + continue + } else if err != nil { + return CompressionNone, &os.PathError{Op: "getxattr", Path: path, Err: err} + } + buf = buf[:sz] + break + } + buf = bytes.TrimSuffix(buf, []byte{0}) + return Compression(buf), nil +} diff --git a/vendor/github.com/dennwc/ioctl/LICENSE b/vendor/github.com/dennwc/ioctl/LICENSE new file mode 100644 index 0000000..966062e --- /dev/null +++ b/vendor/github.com/dennwc/ioctl/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Denys Smirnov + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/dennwc/ioctl/ioctl.go b/vendor/github.com/dennwc/ioctl/ioctl.go new file mode 100644 index 0000000..9f851fb --- /dev/null +++ b/vendor/github.com/dennwc/ioctl/ioctl.go @@ -0,0 +1,82 @@ +package ioctl + +import ( + "fmt" + "os" + "reflect" + "syscall" +) + +const ( + nrBits = 8 + typeBits = 8 + sizeBits = 14 + dirBits = 2 +) + +const ( + nrMask = (1 << nrBits) - 1 + typeMask = (1 << typeBits) - 1 + sizeMask = (1 << sizeBits) - 1 + dirMask = (1 << dirBits) - 1 +) + +const ( + nrShift = 0 + typeShift = nrShift + nrBits + sizeShift = typeShift + typeBits + dirShift = sizeShift + sizeBits +) + +const ( + None = 0 + Write = 1 + Read = 2 +) + +func IOC(dir, typ, nr, size uintptr) uintptr { + return (dir << dirShift) | + (typ << typeShift) | + (nr << nrShift) | + (size << sizeShift) +} + +func IO(typ, nr uintptr) uintptr { + return IOC(None, typ, nr, 0) +} + +func IOR(typ, nr, size uintptr) uintptr { + return IOC(Read, typ, nr, size) +} + +func IOW(typ, nr, size uintptr) uintptr { + return IOC(Write, typ, nr, size) +} + +func IOWR(typ, nr, size uintptr) uintptr { + return IOC(Read|Write, typ, nr, size) +} + +func Ioctl(f *os.File, ioc uintptr, addr uintptr) error { + _, _, e := syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), ioc, addr) + if e != 0 { + return e + } + return nil +} + +func Do(f *os.File, ioc uintptr, arg interface{}) error { + var addr uintptr + if arg != nil { + v := reflect.ValueOf(arg) + switch v.Kind() { + case reflect.Ptr: + addr = v.Elem().UnsafeAddr() + case reflect.Slice: + addr = v.Index(0).UnsafeAddr() + default: + return fmt.Errorf("expected ptr or slice, got %T", arg) + } + } + return Ioctl(f, ioc, addr) +} diff --git a/vendor/github.com/inconshreveable/mousetrap/LICENSE b/vendor/github.com/inconshreveable/mousetrap/LICENSE new file mode 100644 index 0000000..5f920e9 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2022 Alan Shreve (@inconshreveable) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/inconshreveable/mousetrap/README.md b/vendor/github.com/inconshreveable/mousetrap/README.md new file mode 100644 index 0000000..7a950d1 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/README.md @@ -0,0 +1,23 @@ +# mousetrap + +mousetrap is a tiny library that answers a single question. + +On a Windows machine, was the process invoked by someone double clicking on +the executable file while browsing in explorer? + +### Motivation + +Windows developers unfamiliar with command line tools will often "double-click" +the executable for a tool. Because most CLI tools print the help and then exit +when invoked without arguments, this is often very frustrating for those users. + +mousetrap provides a way to detect these invocations so that you can provide +more helpful behavior and instructions on how to run the CLI tool. To see what +this looks like, both from an organizational and a technical perspective, see +https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/ + +### The interface + +The library exposes a single interface: + + func StartedByExplorer() (bool) diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go new file mode 100644 index 0000000..06a91f0 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/trap_others.go @@ -0,0 +1,16 @@ +//go:build !windows +// +build !windows + +package mousetrap + +// StartedByExplorer returns true if the program was invoked by the user +// double-clicking on the executable from explorer.exe +// +// It is conservative and returns false if any of the internal calls fail. +// It does not guarantee that the program was run from a terminal. It only can tell you +// whether it was launched from explorer.exe +// +// On non-Windows platforms, it always returns false. +func StartedByExplorer() bool { + return false +} diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go new file mode 100644 index 0000000..0c56880 --- /dev/null +++ b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go @@ -0,0 +1,42 @@ +package mousetrap + +import ( + "syscall" + "unsafe" +) + +func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { + snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) + if err != nil { + return nil, err + } + defer syscall.CloseHandle(snapshot) + var procEntry syscall.ProcessEntry32 + procEntry.Size = uint32(unsafe.Sizeof(procEntry)) + if err = syscall.Process32First(snapshot, &procEntry); err != nil { + return nil, err + } + for { + if procEntry.ProcessID == uint32(pid) { + return &procEntry, nil + } + err = syscall.Process32Next(snapshot, &procEntry) + if err != nil { + return nil, err + } + } +} + +// StartedByExplorer returns true if the program was invoked by the user double-clicking +// on the executable from explorer.exe +// +// It is conservative and returns false if any of the internal calls fail. +// It does not guarantee that the program was run from a terminal. It only can tell you +// whether it was launched from explorer.exe +func StartedByExplorer() bool { + pe, err := getProcessEntry(syscall.Getppid()) + if err != nil { + return false + } + return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) +} diff --git a/vendor/github.com/lib/pq/.gitattributes b/vendor/github.com/lib/pq/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/vendor/github.com/lib/pq/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/vendor/github.com/lib/pq/.gitignore b/vendor/github.com/lib/pq/.gitignore new file mode 100644 index 0000000..3243952 --- /dev/null +++ b/vendor/github.com/lib/pq/.gitignore @@ -0,0 +1,6 @@ +.db +*.test +*~ +*.swp +.idea +.vscode \ No newline at end of file diff --git a/vendor/github.com/lib/pq/CHANGELOG.md b/vendor/github.com/lib/pq/CHANGELOG.md new file mode 100644 index 0000000..f0c46a9 --- /dev/null +++ b/vendor/github.com/lib/pq/CHANGELOG.md @@ -0,0 +1,265 @@ +unreleased +---------- + + +v1.12.3 (2026-04-03) +-------------------- +- Send datestyle startup parameter, improving compatbility with database engines + that use a different default datestyle such as EnterpriseDB ([#1312]). + +[#1312]: https://github.com/lib/pq/pull/1312 + +v1.12.2 (2026-04-02) +-------------------- + +- Treat io.ErrUnexpectedEOF as driver.ErrBadConn so database/sql discards the + connection. Since v1.12.0 this could result in permanently broken connections, + especially with CockroachDB which frequently sends partial messages ([#1299]). + +[#1299]: https://github.com/lib/pq/pull/1299 + +v1.12.1 (2026-03-30) +-------------------- + +- Look for pgpass file in ~/.pgpass instead of ~/.postgresql/pgpass ([#1300]). + +- Don't clear password if directly set on pq.Config ([#1302]). + +[#1300]: https://github.com/lib/pq/pull/1300 +[#1302]: https://github.com/lib/pq/pull/1302 + +v1.12.0 (2026-03-18) +-------------------- + +- The next release may change the default sslmode from `require` to `prefer`. + See [#1271] for details. + +- `CopyIn()` and `CopyInToSchema()` have been marked as deprecated. These are + simple query builders and not needed for `COPY [..] FROM STDIN` support (which + is *not* deprecated). ([#1279]) + + // Old + tx.Prepare(CopyIn("temp", "num", "text", "blob", "nothing")) + + // Replacement + tx.Prepare(`copy temp (num, text, blob, nothing) from stdin`) + +### Features + +- Support protocol 3.2, and the `min_protocol_version` and + `max_protocol_version` DSN parameters ([#1258]). + +- Support `sslmode=prefer` and `sslmode=allow` ([#1270]). + +- Support `ssl_min_protocol_version` and `ssl_max_protocol_version` ([#1277]). + +- Support connection service file to load connection details ([#1285]). + +- Support `sslrootcert=system` and use `~/.postgresql/root.crt` as the default + value of sslrootcert ([#1280], [#1281]). + +- Add a new `pqerror` package with PostgreSQL error codes ([#1275]). + + For example, to test if an error is a UNIQUE constraint violation: + + if pqErr, ok := errors.AsType[*pq.Error](err); ok && pqErr.Code == pqerror.UniqueViolation { + log.Fatalf("email %q already exsts", email) + } + + To make this a bit more convenient, it also adds a `pq.As()` function: + + pqErr := pq.As(err, pqerror.UniqueViolation) + if pqErr != nil { + log.Fatalf("email %q already exsts", email) + } + +### Fixes + +- Fix SSL key permission check to allow modes stricter than 0600/0640#1265 ([#1265]). + +- Fix Hstore to work with binary parameters ([#1278]). + +- Clearer error when starting a new query while pq is still processing another + query ([#1272]). + +- Send intermediate CAs with client certificates, so they can be signed by an + intermediate CA ([#1267]). + +- Use `time.UTC` for UTC aliases such as `Etc/UTC` ([#1282]). + +[#1258]: https://github.com/lib/pq/pull/1258 +[#1265]: https://github.com/lib/pq/pull/1265 +[#1267]: https://github.com/lib/pq/pull/1267 +[#1270]: https://github.com/lib/pq/pull/1270 +[#1271]: https://github.com/lib/pq/pull/1271 +[#1272]: https://github.com/lib/pq/pull/1272 +[#1275]: https://github.com/lib/pq/pull/1275 +[#1277]: https://github.com/lib/pq/pull/1277 +[#1278]: https://github.com/lib/pq/pull/1278 +[#1279]: https://github.com/lib/pq/pull/1279 +[#1280]: https://github.com/lib/pq/pull/1280 +[#1281]: https://github.com/lib/pq/pull/1281 +[#1282]: https://github.com/lib/pq/pull/1282 +[#1283]: https://github.com/lib/pq/pull/1283 +[#1285]: https://github.com/lib/pq/pull/1285 + +v1.11.2 (2026-02-10) +-------------------- +This fixes two regressions: + +- Don't send startup parameters if there is no value, improving compatibility + with Supavisor ([#1260]). + +- Don't send `dbname` as a startup parameter if `database=[..]` is used in the + connection string. It's recommended to use dbname=, as database= is not a + libpq option, and only worked by accident previously. ([#1261]) + +[#1260]: https://github.com/lib/pq/pull/1260 +[#1261]: https://github.com/lib/pq/pull/1261 + +v1.11.1 (2026-01-29) +-------------------- +This fixes two regressions present in the v1.11.0 release: + +- Fix build on 32bit systems, Windows, and Plan 9 ([#1253]). + +- Named []byte types and pointers to []byte (e.g. `*[]byte`, `json.RawMessage`) + would be treated as an array instead of bytea ([#1252]). + +[#1252]: https://github.com/lib/pq/pull/1252 +[#1253]: https://github.com/lib/pq/pull/1253 + +v1.11.0 (2026-01-28) +-------------------- +This version of pq requires Go 1.21 or newer. + +pq now supports only maintained PostgreSQL releases, which is PostgreSQL 14 and +newer. Previously PostgreSQL 8.4 and newer were supported. + +### Features + +- The `pq.Error.Error()` text includes the position of the error (if reported + by PostgreSQL) and SQLSTATE code ([#1219], [#1224]): + + pq: column "columndoesntexist" does not exist at column 8 (42703) + pq: syntax error at or near ")" at position 2:71 (42601) + +- The `pq.Error.ErrorWithDetail()` method prints a more detailed multiline + message, with the Detail, Hint, and error position (if any) ([#1219]): + + ERROR: syntax error at or near ")" (42601) + CONTEXT: line 12, column 1: + + 10 | name varchar, + 11 | version varchar, + 12 | ); + ^ + +- Add `Config`, `NewConfig()`, and `NewConnectorConfig()` to supply connection + details in a more structured way ([#1240]). + +- Support `hostaddr` and `$PGHOSTADDR` ([#1243]). + +- Support multiple values in `host`, `port`, and `hostaddr`, which are each + tried in order, or randomly if `load_balance_hosts=random` is set ([#1246]). + +- Support `target_session_attrs` connection parameter ([#1246]). + +- Support [`sslnegotiation`] to use SSL without negotiation ([#1180]). + +- Allow using a custom `tls.Config`, for example for encrypted keys ([#1228]). + +- Add `PQGO_DEBUG=1` print the communication with PostgreSQL to stderr, to aid + in debugging, testing, and bug reports ([#1223]). + +- Add support for NamedValueChecker interface ([#1125], [#1238]). + + +### Fixes + +- Match HOME directory lookup logic with libpq: prefer $HOME over /etc/passwd, + ignore ENOTDIR errors, and use APPDATA on Windows ([#1214]). + +- Fix `sslmode=verify-ca` verifying the hostname anyway when connecting to a DNS + name (rather than IP) ([#1226]). + +- Correctly detect pre-protocol errors such as the server not being able to fork + or running out of memory ([#1248]). + +- Fix build with wasm ([#1184]), appengine ([#745]), and Plan 9 ([#1133]). + +- Deprecate and type alias `pq.NullTime` to `sql.NullTime` ([#1211]). + +- Enforce integer limits of the Postgres wire protocol ([#1161]). + +- Accept the `passfile` connection parameter to override `PGPASSFILE` ([#1129]). + +- Fix connecting to socket on Windows systems ([#1179]). + +- Don't perform a permission check on the .pgpass file on Windows ([#595]). + +- Warn about incorrect .pgpass permissions ([#595]). + +- Don't set extra_float_digits ([#1212]). + +- Decode bpchar into a string ([#949]). + +- Fix panic in Ping() by not requiring CommandComplete or EmptyQueryResponse in + simpleQuery() ([#1234]) + +- Recognize bit/varbit ([#743]) and float types ([#1166]) in ColumnTypeScanType(). + +- Accept `PGGSSLIB` and `PGKRBSRVNAME` environment variables ([#1143]). + +- Handle ErrorResponse in readReadyForQuery and return proper error ([#1136]). + +- Detect COPY even if the query starts with whitespace or comments ([#1198]). + +- CopyIn() and CopyInSchema() now work if the list of columns is empty, in which + case it will copy all columns ([#1239]). + +- Treat nil []byte in query parameters as nil/NULL rather than `""` ([#838]). + +- Accept multiple authentication methods before checking AuthOk, which improves + compatibility with PgPool-II ([#1188]). + +[`sslnegotiation`]: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNECT-SSLNEGOTIATION +[#595]: https://github.com/lib/pq/pull/595 +[#745]: https://github.com/lib/pq/pull/745 +[#743]: https://github.com/lib/pq/pull/743 +[#838]: https://github.com/lib/pq/pull/838 +[#949]: https://github.com/lib/pq/pull/949 +[#1125]: https://github.com/lib/pq/pull/1125 +[#1129]: https://github.com/lib/pq/pull/1129 +[#1133]: https://github.com/lib/pq/pull/1133 +[#1136]: https://github.com/lib/pq/pull/1136 +[#1143]: https://github.com/lib/pq/pull/1143 +[#1161]: https://github.com/lib/pq/pull/1161 +[#1166]: https://github.com/lib/pq/pull/1166 +[#1179]: https://github.com/lib/pq/pull/1179 +[#1180]: https://github.com/lib/pq/pull/1180 +[#1184]: https://github.com/lib/pq/pull/1184 +[#1188]: https://github.com/lib/pq/pull/1188 +[#1198]: https://github.com/lib/pq/pull/1198 +[#1211]: https://github.com/lib/pq/pull/1211 +[#1212]: https://github.com/lib/pq/pull/1212 +[#1214]: https://github.com/lib/pq/pull/1214 +[#1219]: https://github.com/lib/pq/pull/1219 +[#1223]: https://github.com/lib/pq/pull/1223 +[#1224]: https://github.com/lib/pq/pull/1224 +[#1226]: https://github.com/lib/pq/pull/1226 +[#1228]: https://github.com/lib/pq/pull/1228 +[#1234]: https://github.com/lib/pq/pull/1234 +[#1238]: https://github.com/lib/pq/pull/1238 +[#1239]: https://github.com/lib/pq/pull/1239 +[#1240]: https://github.com/lib/pq/pull/1240 +[#1243]: https://github.com/lib/pq/pull/1243 +[#1246]: https://github.com/lib/pq/pull/1246 +[#1248]: https://github.com/lib/pq/pull/1248 + + +v1.10.9 (2023-04-26) +-------------------- +- Fixes backwards incompat bug with 1.13. + +- Fixes pgpass issue diff --git a/vendor/github.com/lib/pq/LICENSE b/vendor/github.com/lib/pq/LICENSE new file mode 100644 index 0000000..6a77dc4 --- /dev/null +++ b/vendor/github.com/lib/pq/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2011-2013, 'pq' Contributors. Portions Copyright (c) 2011 Blake Mizerany + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/lib/pq/README.md b/vendor/github.com/lib/pq/README.md new file mode 100644 index 0000000..159b867 --- /dev/null +++ b/vendor/github.com/lib/pq/README.md @@ -0,0 +1,312 @@ +pq is a Go PostgreSQL driver for database/sql. + +All [maintained versions of PostgreSQL] are supported. Older versions may work, +but this is not tested. [API docs]. + +[maintained versions of PostgreSQL]: https://www.postgresql.org/support/versioning +[API docs]: https://pkg.go.dev/github.com/lib/pq + +Connecting +---------- +Use the `postgres` driver name in the `sql.Open()` call: + +```go +package main + +import ( + "database/sql" + "log" + + _ "github.com/lib/pq" // To register the driver. +) + +func main() { + // Or as URL: postgresql://localhost/pqgo + db, err := sql.Open("postgres", "host=localhost dbname=pqgo") + if err != nil { + log.Fatal(err) + } + defer db.Close() + + // db.Open() only creates a connection pool, and doesn't actually establish + // a connection. To ensure the connection works you need to do *something* + // with a connection. + err = db.Ping() + if err != nil { + log.Fatal(err) + } +} +``` + +You can also use the `pq.Config` struct: + +```go +cfg := pq.Config{ + Host: "localhost", + Port: 5432, + User: "pqgo", +} +// Or: create a new Config from the defaults, environment, and DSN. +// cfg, err := pq.NewConfig("host=postgres dbname=pqgo") +// if err != nil { +// log.Fatal(err) +// } + +c, err := pq.NewConnectorConfig(cfg) +if err != nil { + log.Fatal(err) +} + +// Create connection pool. +db := sql.OpenDB(c) +defer db.Close() + +// Make sure it works. +err = db.Ping() +if err != nil { + log.Fatal(err) +} +``` + +The DSN is identical to PostgreSQL's libpq; most parameters are supported and +should behave identical. Both key=value and postgres:// URL-style connection +strings are supported. See the doc comments on the [Config struct] for the full +list and documentation. + +The most notable difference is that you can use any [run-time parameter] such as +`search_path` or `work_mem` in the connection string. This is different from +libpq, which uses the `options` parameter for this (which also works in pq). + +For example: + + sql.Open("postgres", "dbname=pqgo work_mem=100kB search_path=xyz") + +The libpq way (which also works in pq) is to use `options='-c k=v'` like so: + + sql.Open("postgres", "dbname=pqgo options='-c work_mem=100kB -c search_path=xyz'") + +[Config struct]: https://pkg.go.dev/github.com/lib/pq#Config +[run-time parameter]: http://www.postgresql.org/docs/current/static/runtime-config.html + +Errors +------ +Errors from PostgreSQL are returned as [pq.Error]; [pq.As] can be used to +convert an error to `pq.Error`: + +```go +pqErr := pq.As(err, pqerror.UniqueViolation) +if pqErr != nil { + return fmt.Errorf("email %q already exsts", email) +} +``` + +the Error() string contains the error message and code: + + pq: duplicate key value violates unique constraint "users_lower_idx" (23505) + +The ErrorWithDetail() string also contains the DETAIL and CONTEXT fields, if +present. For example for the above error this helpfully contains the duplicate +value: + + ERROR: duplicate key value violates unique constraint "users_lower_idx" (23505) + DETAIL: Key (lower(email))=(a@example.com) already exists. + +Or for an invalid syntax error like this: + + pq: invalid input syntax for type json (22P02) + +It contains the context where this error occurred: + + ERROR: invalid input syntax for type json (22P02) + DETAIL: Token "asd" is invalid. + CONTEXT: line 5, column 8: + + 3 | 'def', + 4 | 123, + 5 | 'foo', 'asd'::jsonb + ^ + +[pq.Error]: https://pkg.go.dev/github.com/lib/pq#Error +[pq.As]: https://pkg.go.dev/github.com/lib/pq#As + +PostgreSQL features +------------------- + +### Authentication +pq supports PASSWORD, MD5, and SCRAM-SHA256 authentication out of the box. If +you need GSS/Kerberos authentication you'll need to import the `auth/kerberos` +module: package: + + import "github.com/lib/pq/auth/kerberos" + + func init() { + pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() }) + } + +This is in a separate module so that users who don't need Kerberos (i.e. most +users) don't have to add unnecessary dependencies. + +Reading a [password file] (pgpass) is also supported. + +[password file]: http://www.postgresql.org/docs/current/static/libpq-pgpass.html + +### Bulk imports with `COPY [..] FROM STDIN` +You can perform bulk imports by preparing a `COPY [..] FROM STDIN` statement +inside a transaction. The returned `sql.Stmt` can then be repeatedly executed to +copy data. After all data has been processed you should call Exec() once with no +arguments to flush all buffered data. + +[Further documentation][copy-doc] and [example][copy-ex]. + +[copy-doc]: https://pkg.go.dev/github.com/lib/pq#hdr-Bulk_imports +[copy-ex]: https://pkg.go.dev/github.com/lib/pq#example-package-CopyFromStdin + +### NOTICE errors +PostgreSQL has "NOTICE" errors for informational messages. For example from the +psql CLI: + + pqgo=# drop table if exists doesnotexist; + NOTICE: table "doesnotexist" does not exist, skipping + DROP TABLE + +These errors are not returned because they're not really errors but, well, +notices. + +You can register a callback for these notices with [ConnectorWithNoticeHandler] + +[ConnectorWithNoticeHandler]: https://pkg.go.dev/github.com/lib/pq#ConnectorWithNoticeHandler + +### Using `LISTEN`/`NOTIFY` +With [pq.Listener] notifications are send on a channel. For example: + +```go +l := pq.NewListener("dbname=pqgo", time.Second, time.Minute, nil) +defer l.Close() + +err := l.Listen("coconut") +if err != nil { + log.Fatal(err) +} + +for { + n := <-l.Notify: + if n == nil { + fmt.Println("nil notify: closing Listener") + return + } + fmt.Printf("notification on %q with data %q\n", n.Channel, n.Extra) +} +``` + +And you'll get a notification for every `notify coconut`. + +See the API docs for a more complete example. + +[pq.Listener]: https://pkg.go.dev/github.com/lib/pq#Listener + + +Caveats +------- +### LastInsertId +sql.Result.LastInsertId() is not supported, because the PostgreSQL protocol does +not have this facility. Use `insert [..] returning [cols]` instead: + + db.QueryRow(`insert into tbl [..] returning id_col`).Scan(..) + // Or multiple rows: + db.Query(`insert into tbl (row1), (row2) returning id_col`) + +This will also work in SQLite and MariaDB with the same syntax. MS-SQL and +Oracle have a similar facility (with a different syntax). + +### timestamps +For timestamps with a timezone (`timestamptz`/`timestamp with time zone`), pq +uses the timezone configured in the server, as libpq. You can change this with +`timestamp=[..]` in the connection string. It's generally recommended to use +UTC. + +For timestamps without a timezone (`timestamp`/`timestamp without time zone`), +pq always uses `time.FixedZone("", 0)` as the timezone; the timestamp parameter +has no effect here. This is intentionally not equal to time.UTC, as it's not a +UTC time: it's a time without a timezone. Go's time package does not really +support this concept, so this is the best we can do This will print `+0000` +twice (e.g. `2026-03-15 17:45:47 +0000 +0000`; having a clearer name would have +been better, but is not compatible change). See [this comment][ts] for some +options on how to deal with this. + +Also see the examples for [timestamptz] and [timestamp] + +[ts]: https://github.com/lib/pq/issues/329#issuecomment-4025733506 +[timestamptz]: https://pkg.go.dev/github.com/lib/pq#example-package-TimestampWithTimezone +[timestamp]: https://pkg.go.dev/github.com/lib/pq#example-package-TimestampWithoutTimezone + +### bytea with copy +All `[]byte` parameters are encoded as `bytea` when using `copy [..] from +stdin`, which may result in errors for e.g. `jsonb` columns. The solution is to +use a string instead of []byte. See #1023 + +Development +----------- +### Running tests +Tests need to be run against a PostgreSQL database; you can use Docker compose +to start one: + + docker compose up -d + +This starts the latest PostgreSQL; use `docker compose up -d pg«v»` to start a +different version. + +In addition, your `/etc/hosts` needs an entry: + + 127.0.0.1 postgres postgres-invalid + +Or you can use any other PostgreSQL instance; see +`testdata/postgres/docker-entrypoint-initdb.d` for the required setup. You can use +the standard `PG*` environment variables to control the connection details; it +uses the following defaults: + + PGHOST=localhost + PGDATABASE=pqgo + PGUSER=pqgo + PGSSLMODE=disable + PGCONNECT_TIMEOUT=20 + +`PQTEST_BINARY_PARAMETERS` can be used to add `binary_parameters=yes` to all +connection strings: + + PQTEST_BINARY_PARAMETERS=1 go test + +Tests can be run against pgbouncer with: + + docker compose up -d pgbouncer pg18 + PGPORT=6432 go test ./... + +and pgpool with: + + docker compose up -d pgpool pg18 + PGPORT=7432 go test ./... + +### Protocol debug output +You can use PQGO_DEBUG=1 to make the driver print the communication with +PostgreSQL to stderr; this works anywhere (test or applications) and can be +useful to debug protocol problems. + +For example: + + % PQGO_DEBUG=1 go test -run TestSimpleQuery + CLIENT → Startup 69 "\x00\x03\x00\x00database\x00pqgo\x00user [..]" + SERVER ← (R) AuthRequest 4 "\x00\x00\x00\x00" + SERVER ← (S) ParamStatus 19 "in_hot_standby\x00off\x00" + [..] + SERVER ← (Z) ReadyForQuery 1 "I" + START conn.query + START conn.simpleQuery + CLIENT → (Q) Query 9 "select 1\x00" + SERVER ← (T) RowDescription 29 "\x00\x01?column?\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x17\x00\x04\xff\xff\xff\xff\x00\x00" + SERVER ← (D) DataRow 7 "\x00\x01\x00\x00\x00\x011" + END conn.simpleQuery + END conn.query + SERVER ← (C) CommandComplete 9 "SELECT 1\x00" + SERVER ← (Z) ReadyForQuery 1 "I" + CLIENT → (X) Terminate 0 "" + PASS + ok github.com/lib/pq 0.010s diff --git a/vendor/github.com/lib/pq/array.go b/vendor/github.com/lib/pq/array.go new file mode 100644 index 0000000..4a53286 --- /dev/null +++ b/vendor/github.com/lib/pq/array.go @@ -0,0 +1,903 @@ +package pq + +import ( + "bytes" + "database/sql" + "database/sql/driver" + "encoding/hex" + "fmt" + "reflect" + "strconv" + "strings" +) + +var typeByteSlice = reflect.TypeOf([]byte{}) +var typeDriverValuer = reflect.TypeOf((*driver.Valuer)(nil)).Elem() +var typeSQLScanner = reflect.TypeOf((*sql.Scanner)(nil)).Elem() + +// Array returns the optimal driver.Valuer and sql.Scanner for an array or +// slice of any dimension. +// +// For example: +// +// db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401})) +// +// var x []sql.NullInt64 +// db.QueryRow(`SELECT ARRAY[235, 401]`).Scan(pq.Array(&x)) +// +// Scanning multi-dimensional arrays is not supported. Arrays where the lower +// bound is not one (such as `[0:0]={1}') are not supported. +func Array(a any) interface { + driver.Valuer + sql.Scanner +} { + switch a := a.(type) { + case []bool: + return (*BoolArray)(&a) + case []float64: + return (*Float64Array)(&a) + case []float32: + return (*Float32Array)(&a) + case []int64: + return (*Int64Array)(&a) + case []int32: + return (*Int32Array)(&a) + case []string: + return (*StringArray)(&a) + case [][]byte: + return (*ByteaArray)(&a) + + case *[]bool: + return (*BoolArray)(a) + case *[]float64: + return (*Float64Array)(a) + case *[]float32: + return (*Float32Array)(a) + case *[]int64: + return (*Int64Array)(a) + case *[]int32: + return (*Int32Array)(a) + case *[]string: + return (*StringArray)(a) + case *[][]byte: + return (*ByteaArray)(a) + } + + return GenericArray{a} +} + +// ArrayDelimiter may be optionally implemented by driver.Valuer or sql.Scanner +// to override the array delimiter used by GenericArray. +type ArrayDelimiter interface { + // ArrayDelimiter returns the delimiter character(s) for this element's type. + ArrayDelimiter() string +} + +// BoolArray represents a one-dimensional array of the PostgreSQL boolean type. +type BoolArray []bool + +// Scan implements the sql.Scanner interface. +func (a *BoolArray) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to BoolArray", src) +} + +func (a *BoolArray) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "BoolArray") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(BoolArray, len(elems)) + for i, v := range elems { + if len(v) != 1 { + return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) + } + switch v[0] { + case 't': + b[i] = true + case 'f': + b[i] = false + default: + return fmt.Errorf("pq: could not parse boolean array index %d: invalid boolean %q", i, v) + } + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. +func (a BoolArray) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be exactly two curly brackets, N bytes of values, + // and N-1 bytes of delimiters. + b := make([]byte, 1+2*n) + + for i := 0; i < n; i++ { + b[2*i] = ',' + if a[i] { + b[1+2*i] = 't' + } else { + b[1+2*i] = 'f' + } + } + + b[0] = '{' + b[2*n] = '}' + + return string(b), nil + } + + return "{}", nil +} + +// ByteaArray represents a one-dimensional array of the PostgreSQL bytea type. +type ByteaArray [][]byte + +// Scan implements the sql.Scanner interface. +func (a *ByteaArray) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to ByteaArray", src) +} + +func (a *ByteaArray) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "ByteaArray") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(ByteaArray, len(elems)) + for i, v := range elems { + b[i], err = parseBytea(v) + if err != nil { + return fmt.Errorf("could not parse bytea array index %d: %w", i, err) + } + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. It uses the "hex" format which +// is only supported on PostgreSQL 9.0 or newer. +func (a ByteaArray) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be at least two curly brackets, 2*N bytes of quotes, + // 3*N bytes of hex formatting, and N-1 bytes of delimiters. + size := 1 + 6*n + for _, x := range a { + size += hex.EncodedLen(len(x)) + } + + b := make([]byte, size) + + for i, s := 0, b; i < n; i++ { + o := copy(s, `,"\\x`) + o += hex.Encode(s[o:], a[i]) + s[o] = '"' + s = s[o+1:] + } + + b[0] = '{' + b[size-1] = '}' + + return string(b), nil + } + + return "{}", nil +} + +// Float64Array represents a one-dimensional array of the PostgreSQL double +// precision type. +type Float64Array []float64 + +// Scan implements the sql.Scanner interface. +func (a *Float64Array) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to Float64Array", src) +} + +func (a *Float64Array) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "Float64Array") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(Float64Array, len(elems)) + for i, v := range elems { + b[i], err = strconv.ParseFloat(string(v), 64) + if err != nil { + return fmt.Errorf("pq: parsing array element index %d: %w", i, err) + } + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. +func (a Float64Array) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be at least two curly brackets, N bytes of values, + // and N-1 bytes of delimiters. + b := make([]byte, 1, 1+2*n) + b[0] = '{' + + b = strconv.AppendFloat(b, a[0], 'f', -1, 64) + for i := 1; i < n; i++ { + b = append(b, ',') + b = strconv.AppendFloat(b, a[i], 'f', -1, 64) + } + + return string(append(b, '}')), nil + } + + return "{}", nil +} + +// Float32Array represents a one-dimensional array of the PostgreSQL double +// precision type. +type Float32Array []float32 + +// Scan implements the sql.Scanner interface. +func (a *Float32Array) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to Float32Array", src) +} + +func (a *Float32Array) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "Float32Array") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(Float32Array, len(elems)) + for i, v := range elems { + x, err := strconv.ParseFloat(string(v), 32) + if err != nil { + return fmt.Errorf("pq: parsing array element index %d: %w", i, err) + } + b[i] = float32(x) + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. +func (a Float32Array) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be at least two curly brackets, N bytes of values, + // and N-1 bytes of delimiters. + b := make([]byte, 1, 1+2*n) + b[0] = '{' + + b = strconv.AppendFloat(b, float64(a[0]), 'f', -1, 32) + for i := 1; i < n; i++ { + b = append(b, ',') + b = strconv.AppendFloat(b, float64(a[i]), 'f', -1, 32) + } + + return string(append(b, '}')), nil + } + + return "{}", nil +} + +// GenericArray implements the driver.Valuer and sql.Scanner interfaces for +// an array or slice of any dimension. +type GenericArray struct{ A any } + +func (GenericArray) evaluateDestination(rt reflect.Type) (reflect.Type, func([]byte, reflect.Value) error, string) { + var assign func([]byte, reflect.Value) error + var del = "," + + // TODO calculate the assign function for other types + // TODO repeat this section on the element type of arrays or slices (multidimensional) + { + if reflect.PointerTo(rt).Implements(typeSQLScanner) { + // dest is always addressable because it is an element of a slice. + assign = func(src []byte, dest reflect.Value) (err error) { + ss := dest.Addr().Interface().(sql.Scanner) + if src == nil { + err = ss.Scan(nil) + } else { + err = ss.Scan(src) + } + return + } + goto FoundType + } + + assign = func([]byte, reflect.Value) error { + return fmt.Errorf("pq: scanning to %s is not implemented; only sql.Scanner", rt) + } + } + +FoundType: + + if ad, ok := reflect.Zero(rt).Interface().(ArrayDelimiter); ok { + del = ad.ArrayDelimiter() + } + + return rt, assign, del +} + +// Scan implements the sql.Scanner interface. +func (a GenericArray) Scan(src any) error { + dpv := reflect.ValueOf(a.A) + switch { + case dpv.Kind() != reflect.Pointer: + return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) + case dpv.IsNil(): + return fmt.Errorf("pq: destination %T is nil", a.A) + } + + dv := dpv.Elem() + switch dv.Kind() { + case reflect.Slice: + case reflect.Array: + default: + return fmt.Errorf("pq: destination %T is not a pointer to array or slice", a.A) + } + + switch src := src.(type) { + case []byte: + return a.scanBytes(src, dv) + case string: + return a.scanBytes([]byte(src), dv) + case nil: + if dv.Kind() == reflect.Slice { + dv.Set(reflect.Zero(dv.Type())) + return nil + } + } + + return fmt.Errorf("pq: cannot convert %T to %s", src, dv.Type()) +} + +func (a GenericArray) scanBytes(src []byte, dv reflect.Value) error { + dtype, assign, del := a.evaluateDestination(dv.Type().Elem()) + dims, elems, err := parseArray(src, []byte(del)) + if err != nil { + return err + } + + // TODO allow multidimensional + + if len(dims) > 1 { + return fmt.Errorf("pq: scanning from multidimensional ARRAY%s is not implemented", + strings.Replace(fmt.Sprint(dims), " ", "][", -1)) + } + + // Treat a zero-dimensional array like an array with a single dimension of zero. + if len(dims) == 0 { + dims = append(dims, 0) + } + + for i, rt := 0, dv.Type(); i < len(dims); i, rt = i+1, rt.Elem() { + switch rt.Kind() { + case reflect.Slice: + case reflect.Array: + if rt.Len() != dims[i] { + return fmt.Errorf("pq: cannot convert ARRAY%s to %s", + strings.Replace(fmt.Sprint(dims), " ", "][", -1), dv.Type()) + } + default: + // TODO handle multidimensional + } + } + + values := reflect.MakeSlice(reflect.SliceOf(dtype), len(elems), len(elems)) + for i, e := range elems { + err := assign(e, values.Index(i)) + if err != nil { + return fmt.Errorf("pq: parsing array element index %d: %w", i, err) + } + } + + // TODO handle multidimensional + + switch dv.Kind() { + case reflect.Slice: + dv.Set(values.Slice(0, dims[0])) + case reflect.Array: + for i := 0; i < dims[0]; i++ { + dv.Index(i).Set(values.Index(i)) + } + } + + return nil +} + +// Value implements the driver.Valuer interface. +func (a GenericArray) Value() (driver.Value, error) { + if a.A == nil { + return nil, nil + } + + rv := reflect.ValueOf(a.A) + + switch rv.Kind() { + case reflect.Slice: + if rv.IsNil() { + return nil, nil + } + case reflect.Array: + default: + return nil, fmt.Errorf("pq: unable to convert %T to array", a.A) + } + + if n := rv.Len(); n > 0 { + // There will be at least two curly brackets, N bytes of values, + // and N-1 bytes of delimiters. + b := make([]byte, 0, 1+2*n) + + b, _, err := appendArray(b, rv, n) + return string(b), err + } + + return "{}", nil +} + +// Int64Array represents a one-dimensional array of the PostgreSQL integer types. +type Int64Array []int64 + +// Scan implements the sql.Scanner interface. +func (a *Int64Array) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to Int64Array", src) +} + +func (a *Int64Array) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "Int64Array") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(Int64Array, len(elems)) + for i, v := range elems { + b[i], err = strconv.ParseInt(string(v), 10, 64) + if err != nil { + return fmt.Errorf("pq: parsing array element index %d: %w", i, err) + } + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. +func (a Int64Array) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be at least two curly brackets, N bytes of values, + // and N-1 bytes of delimiters. + b := make([]byte, 1, 1+2*n) + b[0] = '{' + + b = strconv.AppendInt(b, a[0], 10) + for i := 1; i < n; i++ { + b = append(b, ',') + b = strconv.AppendInt(b, a[i], 10) + } + + return string(append(b, '}')), nil + } + + return "{}", nil +} + +// Int32Array represents a one-dimensional array of the PostgreSQL integer types. +type Int32Array []int32 + +// Scan implements the sql.Scanner interface. +func (a *Int32Array) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to Int32Array", src) +} + +func (a *Int32Array) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "Int32Array") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(Int32Array, len(elems)) + for i, v := range elems { + x, err := strconv.ParseInt(string(v), 10, 32) + if err != nil { + return fmt.Errorf("pq: parsing array element index %d: %w", i, err) + } + b[i] = int32(x) + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. +func (a Int32Array) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be at least two curly brackets, N bytes of values, + // and N-1 bytes of delimiters. + b := make([]byte, 1, 1+2*n) + b[0] = '{' + + b = strconv.AppendInt(b, int64(a[0]), 10) + for i := 1; i < n; i++ { + b = append(b, ',') + b = strconv.AppendInt(b, int64(a[i]), 10) + } + + return string(append(b, '}')), nil + } + + return "{}", nil +} + +// StringArray represents a one-dimensional array of the PostgreSQL character types. +type StringArray []string + +// Scan implements the sql.Scanner interface. +func (a *StringArray) Scan(src any) error { + switch src := src.(type) { + case []byte: + return a.scanBytes(src) + case string: + return a.scanBytes([]byte(src)) + case nil: + *a = nil + return nil + } + + return fmt.Errorf("pq: cannot convert %T to StringArray", src) +} + +func (a *StringArray) scanBytes(src []byte) error { + elems, err := scanLinearArray(src, []byte{','}, "StringArray") + if err != nil { + return err + } + if *a != nil && len(elems) == 0 { + *a = (*a)[:0] + } else { + b := make(StringArray, len(elems)) + for i, v := range elems { + if b[i] = string(v); v == nil { + return fmt.Errorf("pq: parsing array element index %d: cannot convert nil to string", i) + } + } + *a = b + } + return nil +} + +// Value implements the driver.Valuer interface. +func (a StringArray) Value() (driver.Value, error) { + if a == nil { + return nil, nil + } + + if n := len(a); n > 0 { + // There will be at least two curly brackets, 2*N bytes of quotes, + // and N-1 bytes of delimiters. + b := make([]byte, 1, 1+3*n) + b[0] = '{' + + b = appendArrayQuotedBytes(b, []byte(a[0])) + for i := 1; i < n; i++ { + b = append(b, ',') + b = appendArrayQuotedBytes(b, []byte(a[i])) + } + + return string(append(b, '}')), nil + } + + return "{}", nil +} + +// appendArray appends rv to the buffer, returning the extended buffer and the +// delimiter used between elements. +// +// Returns an error when n <= 0 or rv is not a reflect.Array or reflect.Slice. +func appendArray(b []byte, rv reflect.Value, n int) ([]byte, string, error) { + var del string + var err error + + b = append(b, '{') + + if b, del, err = appendArrayElement(b, rv.Index(0)); err != nil { + return b, del, err + } + + for i := 1; i < n; i++ { + b = append(b, del...) + if b, del, err = appendArrayElement(b, rv.Index(i)); err != nil { + return b, del, err + } + } + + return append(b, '}'), del, nil +} + +// appendArrayElement appends rv to the buffer, returning the extended buffer +// and the delimiter to use before the next element. +// +// When rv's Kind is neither reflect.Array nor reflect.Slice, it is converted +// using driver.DefaultParameterConverter and the resulting []byte or string +// is double-quoted. +// +// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO +func appendArrayElement(b []byte, rv reflect.Value) ([]byte, string, error) { + if k := rv.Kind(); k == reflect.Array || k == reflect.Slice { + if t := rv.Type(); t != typeByteSlice && !t.Implements(typeDriverValuer) { + if n := rv.Len(); n > 0 { + return appendArray(b, rv, n) + } + + return b, "", nil + } + } + + var del = "," + var err error + var iv = rv.Interface() + + if ad, ok := iv.(ArrayDelimiter); ok { + del = ad.ArrayDelimiter() + } + + if iv, err = driver.DefaultParameterConverter.ConvertValue(iv); err != nil { + return b, del, err + } + + switch v := iv.(type) { + case nil: + return append(b, "NULL"...), del, nil + case []byte: + return appendArrayQuotedBytes(b, v), del, nil + case string: + return appendArrayQuotedBytes(b, []byte(v)), del, nil + } + + b, err = appendValue(b, iv) + return b, del, err +} + +func appendArrayQuotedBytes(b, v []byte) []byte { + b = append(b, '"') + for { + i := bytes.IndexAny(v, `"\`) + if i < 0 { + b = append(b, v...) + break + } + if i > 0 { + b = append(b, v[:i]...) + } + b = append(b, '\\', v[i]) + v = v[i+1:] + } + return append(b, '"') +} + +func appendValue(b []byte, v driver.Value) ([]byte, error) { + enc, err := encode(v, 0) + if err != nil { + return nil, err + } + return append(b, enc...), nil +} + +// parseArray extracts the dimensions and elements of an array represented in +// text format. Only representations emitted by the backend are supported. +// Notably, whitespace around brackets and delimiters is significant, and NULL +// is case-sensitive. +// +// See http://www.postgresql.org/docs/current/static/arrays.html#ARRAYS-IO +func parseArray(src, del []byte) (dims []int, elems [][]byte, err error) { + var depth, i int + + if len(src) < 1 || src[0] != '{' { + return nil, nil, fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '{', 0) + } + +Open: + for i < len(src) { + switch src[i] { + case '{': + depth++ + i++ + case '}': + elems = make([][]byte, 0) + goto Close + default: + break Open + } + } + dims = make([]int, i) + +Element: + for i < len(src) { + switch src[i] { + case '{': + if depth == len(dims) { + break Element + } + depth++ + dims[depth-1] = 0 + i++ + case '"': + var elem = []byte{} + var escape bool + for i++; i < len(src); i++ { + if escape { + elem = append(elem, src[i]) + escape = false + } else { + switch src[i] { + default: + elem = append(elem, src[i]) + case '\\': + escape = true + case '"': + elems = append(elems, elem) + i++ + break Element + } + } + } + default: + for start := i; i < len(src); i++ { + if bytes.HasPrefix(src[i:], del) || src[i] == '}' { + elem := src[start:i] + if len(elem) == 0 { + return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) + } + if bytes.Equal(elem, []byte("NULL")) { + elem = nil + } + elems = append(elems, elem) + break Element + } + } + } + } + + for i < len(src) { + if bytes.HasPrefix(src[i:], del) && depth > 0 { + dims[depth-1]++ + i += len(del) + goto Element + } else if src[i] == '}' && depth > 0 { + dims[depth-1]++ + depth-- + i++ + } else { + return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) + } + } + +Close: + for i < len(src) { + if src[i] == '}' && depth > 0 { + depth-- + i++ + } else { + return nil, nil, fmt.Errorf("pq: unable to parse array; unexpected %q at offset %d", src[i], i) + } + } + if depth > 0 { + err = fmt.Errorf("pq: unable to parse array; expected %q at offset %d", '}', i) + } + if err == nil { + for _, d := range dims { + if (len(elems) % d) != 0 { + err = fmt.Errorf("pq: multidimensional arrays must have elements with matching dimensions") + } + } + } + return +} + +func scanLinearArray(src, del []byte, typ string) (elems [][]byte, err error) { + dims, elems, err := parseArray(src, del) + if err != nil { + return nil, err + } + if len(dims) > 1 { + return nil, fmt.Errorf("pq: cannot convert ARRAY%s to %s", strings.Replace(fmt.Sprint(dims), " ", "][", -1), typ) + } + return elems, err +} diff --git a/vendor/github.com/lib/pq/as.go b/vendor/github.com/lib/pq/as.go new file mode 100644 index 0000000..1ea0ee5 --- /dev/null +++ b/vendor/github.com/lib/pq/as.go @@ -0,0 +1,26 @@ +//go:build !go1.26 + +package pq + +import ( + "errors" + "slices" +) + +// As asserts that the given error is [pq.Error] and returns it, returning nil +// if it's not a pq.Error. +// +// It will return nil if the pq.Error is not one of the given error codes. If no +// codes are given it will always return the Error. +// +// This is safe to call with a nil error. +func As(err error, codes ...ErrorCode) *Error { + if err == nil { // Not strictly needed, but prevents alloc for nil errors. + return nil + } + pqErr := new(Error) + if errors.As(err, &pqErr) && (len(codes) == 0 || slices.Contains(codes, pqErr.Code)) { + return pqErr + } + return nil +} diff --git a/vendor/github.com/lib/pq/as_go126.go b/vendor/github.com/lib/pq/as_go126.go new file mode 100644 index 0000000..18ffbc3 --- /dev/null +++ b/vendor/github.com/lib/pq/as_go126.go @@ -0,0 +1,23 @@ +//go:build go1.26 + +package pq + +import ( + "errors" + "github.com/lib/pq/pqerror" + "slices" +) + +// As asserts that the given error is [pq.Error] and returns it, returning nil +// if it's not a pq.Error. +// +// It will return nil if the pq.Error is not one of the given error codes. If no +// codes are given it will always return the Error. +// +// This is safe to call with a nil error. +func As(err error, codes ...pqerror.Code) *Error { + if pqErr, ok := errors.AsType[*Error](err); ok && (len(codes) == 0 || slices.Contains(codes, pqErr.Code)) { + return pqErr + } + return nil +} diff --git a/vendor/github.com/lib/pq/buf.go b/vendor/github.com/lib/pq/buf.go new file mode 100644 index 0000000..67ca60c --- /dev/null +++ b/vendor/github.com/lib/pq/buf.go @@ -0,0 +1,100 @@ +package pq + +import ( + "bytes" + "encoding/binary" + "errors" + "fmt" + + "github.com/lib/pq/internal/proto" + "github.com/lib/pq/oid" +) + +type readBuf []byte + +func (b *readBuf) int32() (n int) { + n = int(int32(binary.BigEndian.Uint32(*b))) + *b = (*b)[4:] + return +} + +func (b *readBuf) oid() (n oid.Oid) { + n = oid.Oid(binary.BigEndian.Uint32(*b)) + *b = (*b)[4:] + return +} + +// N.B: this is actually an unsigned 16-bit integer, unlike int32 +func (b *readBuf) int16() (n int) { + n = int(binary.BigEndian.Uint16(*b)) + *b = (*b)[2:] + return +} + +func (b *readBuf) string() string { + i := bytes.IndexByte(*b, 0) + if i < 0 { + panic(errors.New("pq: invalid message format; expected string terminator")) + } + s := (*b)[:i] + *b = (*b)[i+1:] + return string(s) +} + +func (b *readBuf) next(n int) (v []byte) { + v = (*b)[:n] + *b = (*b)[n:] + return +} + +func (b *readBuf) byte() byte { + return b.next(1)[0] +} + +type writeBuf struct { + buf []byte + pos int +} + +func (b *writeBuf) int32(n int) { + x := make([]byte, 4) + binary.BigEndian.PutUint32(x, uint32(n)) + b.buf = append(b.buf, x...) +} + +func (b *writeBuf) int16(n int) { + x := make([]byte, 2) + binary.BigEndian.PutUint16(x, uint16(n)) + b.buf = append(b.buf, x...) +} + +func (b *writeBuf) string(s string) { + b.buf = append(append(b.buf, s...), '\000') +} + +func (b *writeBuf) byte(c proto.RequestCode) { + b.buf = append(b.buf, byte(c)) +} + +func (b *writeBuf) bytes(v []byte) { + b.buf = append(b.buf, v...) +} + +func (b *writeBuf) wrap() []byte { + p := b.buf[b.pos:] + if len(p) > proto.MaxUint32 { + panic(fmt.Errorf("pq: message too large (%d > math.MaxUint32)", len(p))) + } + binary.BigEndian.PutUint32(p, uint32(len(p))) + return b.buf +} + +func (b *writeBuf) next(c proto.RequestCode) { + p := b.buf[b.pos:] + if len(p) > proto.MaxUint32 { + panic(fmt.Errorf("pq: message too large (%d > math.MaxUint32)", len(p))) + } + binary.BigEndian.PutUint32(p, uint32(len(p))) + b.pos = len(b.buf) + 1 + b.buf = append(b.buf, byte(c), 0, 0, 0, 0) +} diff --git a/vendor/github.com/lib/pq/compose.yaml b/vendor/github.com/lib/pq/compose.yaml new file mode 100644 index 0000000..0092b7e --- /dev/null +++ b/vendor/github.com/lib/pq/compose.yaml @@ -0,0 +1,89 @@ +name: 'pqgo' + +services: + pgbouncer: + profiles: ['pgbouncer'] + image: 'cleanstart/pgbouncer:latest' + ports: ['127.0.0.1:6432:6432'] + command: ['/init/pgbouncer.ini'] + volumes: ['./testdata/pgbouncer:/init', './testdata/ssl:/ssl'] + environment: + 'PGBOUNCER_DATABASE': 'pqgo' + + pgpool: + profiles: ['pgpool'] + image: 'pgpool/pgpool:4.4.3' + ports: ['127.0.0.1:7432:7432'] + volumes: ['./testdata/pgpool:/init', './testdata/ssl:/ssl'] + entrypoint: '/init/entry.sh' + environment: + 'PGPOOL_PARAMS_PORT': '7432' + 'PGPOOL_PARAMS_BACKEND_HOSTNAME0': 'pg18' + + cockroach: + profiles: ['cockroach'] + image: 'cockroachdb/cockroach:latest-v26.1' + ports: ['127.0.0.1:26257:26257'] + volumes: ['./testdata/cockroach:/docker-entrypoint-initdb.d', './testdata/ssl:/ssl'] + command: ['start-single-node', '--accept-sql-without-tls', '--certs-dir=/ssl2'] + healthcheck: {test: ['CMD-SHELL', '/cockroach/cockroach node status --insecure --user=pqgo'], start_period: '30s', start_interval: '1s'} + + pg18: + image: 'postgres:18' + ports: ['127.0.0.1:5432:5432'] + entrypoint: '/init/entry.sh' + volumes: ['./testdata/postgres:/init', './testdata/ssl:/ssl'] + shm_size: '128mb' + healthcheck: {test: ['CMD-SHELL', 'pg_isready -U pqgo -d pqgo'], start_period: '30s', start_interval: '1s'} + environment: + 'POSTGRES_DATABASE': 'pqgo' + 'POSTGRES_USER': 'pqgo' + 'POSTGRES_PASSWORD': 'unused' + pg17: + profiles: ['pg17'] + image: 'postgres:17' + ports: ['127.0.0.1:5432:5432'] + entrypoint: '/init/entry.sh' + volumes: ['./testdata/postgres:/init', './testdata/ssl:/ssl'] + shm_size: '128mb' + healthcheck: {test: ['CMD-SHELL', 'pg_isready -U pqgo -d pqgo'], start_period: '30s', start_interval: '1s'} + environment: + 'POSTGRES_DATABASE': 'pqgo' + 'POSTGRES_USER': 'pqgo' + 'POSTGRES_PASSWORD': 'unused' + pg16: + profiles: ['pg16'] + image: 'postgres:16' + ports: ['127.0.0.1:5432:5432'] + entrypoint: '/init/entry.sh' + volumes: ['./testdata/postgres:/init', './testdata/ssl:/ssl'] + shm_size: '128mb' + healthcheck: {test: ['CMD-SHELL', 'pg_isready -U pqgo -d pqgo'], start_period: '30s', start_interval: '1s'} + environment: + 'POSTGRES_DATABASE': 'pqgo' + 'POSTGRES_USER': 'pqgo' + 'POSTGRES_PASSWORD': 'unused' + pg15: + profiles: ['pg15'] + image: 'postgres:15' + ports: ['127.0.0.1:5432:5432'] + entrypoint: '/init/entry.sh' + volumes: ['./testdata/postgres:/init', './testdata/ssl:/ssl'] + shm_size: '128mb' + healthcheck: {test: ['CMD-SHELL', 'pg_isready -U pqgo -d pqgo'], start_period: '30s', start_interval: '1s'} + environment: + 'POSTGRES_DATABASE': 'pqgo' + 'POSTGRES_USER': 'pqgo' + 'POSTGRES_PASSWORD': 'unused' + pg14: + profiles: ['pg14'] + image: 'postgres:14' + ports: ['127.0.0.1:5432:5432'] + entrypoint: '/init/entry.sh' + volumes: ['./testdata/postgres:/init', './testdata/ssl:/ssl'] + shm_size: '128mb' + healthcheck: {test: ['CMD-SHELL', 'pg_isready -U pqgo -d pqgo'], start_period: '30s', start_interval: '1s'} + environment: + 'POSTGRES_DATABASE': 'pqgo' + 'POSTGRES_USER': 'pqgo' + 'POSTGRES_PASSWORD': 'unused' diff --git a/vendor/github.com/lib/pq/conn.go b/vendor/github.com/lib/pq/conn.go new file mode 100644 index 0000000..688329c --- /dev/null +++ b/vendor/github.com/lib/pq/conn.go @@ -0,0 +1,1818 @@ +package pq + +import ( + "bufio" + "context" + "crypto/md5" + "crypto/sha256" + "database/sql" + "database/sql/driver" + "encoding/binary" + "errors" + "fmt" + "io" + "math" + "net" + "os" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/lib/pq/internal/pgpass" + "github.com/lib/pq/internal/pqsql" + "github.com/lib/pq/internal/pqutil" + "github.com/lib/pq/internal/proto" + "github.com/lib/pq/oid" + "github.com/lib/pq/scram" +) + +// Common error types +var ( + ErrNotSupported = errors.New("pq: unsupported command") + ErrInFailedTransaction = errors.New("pq: could not complete operation in a failed transaction") + ErrSSLNotSupported = errors.New("pq: SSL is not enabled on the server") + ErrCouldNotDetectUsername = errors.New("pq: could not detect default username; please provide one explicitly") + ErrSSLKeyUnknownOwnership = pqutil.ErrSSLKeyUnknownOwnership + ErrSSLKeyHasWorldPermissions = pqutil.ErrSSLKeyHasWorldPermissions + + errQueryInProgress = errors.New("pq: there is already a query being processed on this connection") + errUnexpectedReady = errors.New("unexpected ReadyForQuery") + errNoRowsAffected = errors.New("no RowsAffected available after the empty statement") + errNoLastInsertID = errors.New("no LastInsertId available after the empty statement") +) + +// Compile time validation that our types implement the expected interfaces +var ( + _ driver.Driver = Driver{} + _ driver.ConnBeginTx = (*conn)(nil) + _ driver.ConnPrepareContext = (*conn)(nil) + _ driver.Execer = (*conn)(nil) //lint:ignore SA1019 x + _ driver.ExecerContext = (*conn)(nil) + _ driver.NamedValueChecker = (*conn)(nil) + _ driver.Pinger = (*conn)(nil) + _ driver.Queryer = (*conn)(nil) //lint:ignore SA1019 x + _ driver.QueryerContext = (*conn)(nil) + _ driver.SessionResetter = (*conn)(nil) + _ driver.Validator = (*conn)(nil) + _ driver.StmtExecContext = (*stmt)(nil) + _ driver.StmtQueryContext = (*stmt)(nil) +) + +func init() { + sql.Register("postgres", &Driver{}) +} + +var debugProto = func() bool { + // Check for exactly "1" (rather than mere existence) so we can add + // options/flags in the future. I don't know if we ever want that, but it's + // nice to leave the option open. + return os.Getenv("PQGO_DEBUG") == "1" +}() + +// Driver is the Postgres database driver. +type Driver struct{} + +// Open opens a new connection to the database. name is a connection string. +// Most users should only use it through database/sql package from the standard +// library. +func (d Driver) Open(name string) (driver.Conn, error) { + return Open(name) +} + +// Parameters sent by PostgreSQL on startup. +type parameterStatus struct { + serverVersion int + currentLocation *time.Location + inHotStandby, defaultTransactionReadOnly sql.NullBool +} + +type format int + +const ( + formatText format = 0 + formatBinary format = 1 +) + +var ( + // One result-column format code with the value 1 (i.e. all binary). + colFmtDataAllBinary = []byte{0, 1, 0, 1} + + // No result-column format codes (i.e. all text). + colFmtDataAllText = []byte{0, 0} +) + +type transactionStatus byte + +const ( + txnStatusIdle transactionStatus = 'I' + txnStatusIdleInTransaction transactionStatus = 'T' + txnStatusInFailedTransaction transactionStatus = 'E' +) + +func (s transactionStatus) String() string { + switch s { + case txnStatusIdle: + return "idle" + case txnStatusIdleInTransaction: + return "idle in transaction" + case txnStatusInFailedTransaction: + return "in a failed transaction" + default: + panic(fmt.Sprintf("pq: unknown transactionStatus %d", s)) + } +} + +// Dialer is the dialer interface. It can be used to obtain more control over +// how pq creates network connections. +type Dialer interface { + Dial(network, address string) (net.Conn, error) + DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) +} + +// DialerContext is the context-aware dialer interface. +type DialerContext interface { + DialContext(ctx context.Context, network, address string) (net.Conn, error) +} + +type defaultDialer struct { + d net.Dialer +} + +func (d defaultDialer) Dial(network, address string) (net.Conn, error) { + return d.d.Dial(network, address) +} + +func (d defaultDialer) DialTimeout(network, address string, timeout time.Duration) (net.Conn, error) { + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + return d.DialContext(ctx, network, address) +} + +func (d defaultDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { + return d.d.DialContext(ctx, network, address) +} + +type conn struct { + c net.Conn + buf *bufio.Reader + namei int + scratch [512]byte + txnStatus transactionStatus + txnFinish func() + + // Save connection arguments to use during CancelRequest. + dialer Dialer + cfg Config + parameterStatus parameterStatus + + saveMessageType proto.ResponseCode + saveMessageBuffer []byte + + // If an error is set this connection is bad and all public-facing + // functions should return the appropriate error by calling get() + // (ErrBadConn) or getForNext(). + err syncErr + + secretKey []byte // Cancellation key for CancelRequest messages. + pid int // Cancellation PID. + inProgress atomic.Bool // This connection is in the middle of a processing a request. + noticeHandler func(*Error) // If not nil, notices will be synchronously sent here + notificationHandler func(*Notification) // If not nil, notifications will be synchronously sent here + gss GSS // GSSAPI context +} + +type syncErr struct { + err error + sync.Mutex +} + +// Return ErrBadConn if connection is bad. +func (e *syncErr) get() error { + e.Lock() + defer e.Unlock() + if e.err != nil { + return driver.ErrBadConn + } + return nil +} + +// Return the error set on the connection. Currently only used by rows.Next. +func (e *syncErr) getForNext() error { + e.Lock() + defer e.Unlock() + return e.err +} + +// Set error, only if it isn't set yet. +func (e *syncErr) set(err error) { + if err == nil { + panic("attempt to set nil err") + } + e.Lock() + defer e.Unlock() + if e.err == nil { + e.err = err + } +} + +func (cn *conn) writeBuf(b proto.RequestCode) *writeBuf { + cn.scratch[0] = byte(b) + return &writeBuf{ + buf: cn.scratch[:5], + pos: 1, + } +} + +// Open opens a new connection to the database. dsn is a connection string. Most +// users should only use it through database/sql package from the standard +// library. +func Open(dsn string) (_ driver.Conn, err error) { + return DialOpen(defaultDialer{}, dsn) +} + +// DialOpen opens a new connection to the database using a dialer. +func DialOpen(d Dialer, dsn string) (_ driver.Conn, err error) { + c, err := NewConnector(dsn) + if err != nil { + return nil, err + } + c.Dialer(d) + return c.open(context.Background()) +} + +func (c *Connector) open(ctx context.Context) (*conn, error) { + tsa := c.cfg.TargetSessionAttrs +restartAll: + var ( + errs []error + app = func(err error, cfg Config) bool { + if err != nil { + if debugProto { + fmt.Fprintln(os.Stderr, "CONNECT (error)", err) + } + errs = append(errs, fmt.Errorf("connecting to %s:%d: %w", cfg.Host, cfg.Port, err)) + } + return err != nil + } + ) + for _, cfg := range c.cfg.hosts() { + mode := cfg.SSLMode + restartHost: + if debugProto { + fmt.Fprintln(os.Stderr, "CONNECT ", cfg.string()) + } + + cfg.SSLMode = mode + cn := &conn{cfg: cfg, dialer: c.dialer} + cn.cfg.Password = pgpass.PasswordFromPgpass(cn.cfg.Passfile, cn.cfg.User, cn.cfg.Password, + cn.cfg.Host, strconv.Itoa(int(cn.cfg.Port)), cn.cfg.Database) + + var err error + cn.c, err = dial(ctx, c.dialer, cn.cfg) + if app(err, cfg) { + continue + } + + err = cn.ssl(cn.cfg, mode) + if err != nil && mode == SSLModePrefer { + mode = SSLModeDisable + goto restartHost + } + if app(err, cfg) { + if cn.c != nil { + _ = cn.c.Close() + } + continue + } + + cn.buf = bufio.NewReader(cn.c) + err = cn.startup(cn.cfg) + if err != nil && mode == SSLModeAllow { + mode = SSLModeRequire + goto restartHost + } + if app(err, cfg) { + _ = cn.c.Close() + continue + } + + // Reset the deadline, in case one was set (see dial) + if cn.cfg.ConnectTimeout > 0 { + err := cn.c.SetDeadline(time.Time{}) + if app(err, cfg) { + _ = cn.c.Close() + continue + } + } + + err = cn.checkTSA(tsa) + if app(err, cfg) { + _ = cn.c.Close() + continue + } + + return cn, nil + } + + // target_session_attrs=prefer-standby is treated as standby in checkTSA; we + // ran out of hosts so none are on standby. Clear the setting and try again. + if c.cfg.TargetSessionAttrs == TargetSessionAttrsPreferStandby { + tsa = TargetSessionAttrsAny + goto restartAll + } + + if len(c.cfg.Multi) == 0 { + // Remove the "connecting to [..]" when we have just one host, so the + // error is identical to what we had before. + return nil, errors.Unwrap(errs[0]) + } + return nil, fmt.Errorf("pq: could not connect to any of the hosts:\n%w", errors.Join(errs...)) +} + +func (cn *conn) getBool(query string) (bool, error) { + res, err := cn.simpleQuery(query) + if err != nil { + return false, err + } + defer res.Close() + + v := make([]driver.Value, 1) + err = res.Next(v) + if err != nil { + return false, err + } + + switch vv := v[0].(type) { + default: + return false, fmt.Errorf("parseBool: unknown type %T: %[1]v", v[0]) + case bool: + return vv, nil + case string: + vv, ok := v[0].(string) + if !ok { + return false, err + } + return vv == "on", nil + } +} + +func (cn *conn) checkTSA(tsa TargetSessionAttrs) error { + var ( + geths = func() (hs bool, err error) { + hs = cn.parameterStatus.inHotStandby.Bool + if !cn.parameterStatus.inHotStandby.Valid { + hs, err = cn.getBool("select pg_catalog.pg_is_in_recovery()") + } + return hs, err + } + getro = func() (ro bool, err error) { + ro = cn.parameterStatus.defaultTransactionReadOnly.Bool + if !cn.parameterStatus.defaultTransactionReadOnly.Valid { + ro, err = cn.getBool("show transaction_read_only") + } + return ro, err + } + ) + + switch tsa { + default: + panic("unreachable") + case "", TargetSessionAttrsAny: + return nil + case TargetSessionAttrsReadWrite, TargetSessionAttrsReadOnly: + readonly, err := getro() + if err != nil { + return err + } + if !cn.parameterStatus.defaultTransactionReadOnly.Valid { + var err error + readonly, err = cn.getBool("show transaction_read_only") + if err != nil { + return err + } + } + switch { + case tsa == TargetSessionAttrsReadOnly && !readonly: + return errors.New("session is not read-only") + case tsa == TargetSessionAttrsReadWrite: + if readonly { + return errors.New("session is read-only") + } + hs, err := geths() + if err != nil { + return err + } + if hs { + return errors.New("server is in hot standby mode") + } + return nil + default: + return nil + } + case TargetSessionAttrsPrimary, TargetSessionAttrsStandby, TargetSessionAttrsPreferStandby: + hs, err := geths() + if err != nil { + return err + } + switch { + case (tsa == TargetSessionAttrsStandby || tsa == TargetSessionAttrsPreferStandby) && !hs: + return errors.New("server is not in hot standby mode") + case tsa == TargetSessionAttrsPrimary && hs: + return errors.New("server is in hot standby mode") + default: + return nil + } + } +} + +func dial(ctx context.Context, d Dialer, cfg Config) (net.Conn, error) { + network, address := cfg.network() + + // Zero or not specified means wait indefinitely. + if cfg.ConnectTimeout > 0 { + // connect_timeout should apply to the entire connection establishment + // procedure, so we both use a timeout for the TCP connection + // establishment and set a deadline for doing the initial handshake. The + // deadline is then reset after startup() is done. + var ( + deadline = time.Now().Add(cfg.ConnectTimeout) + conn net.Conn + err error + ) + if dctx, ok := d.(DialerContext); ok { + ctx, cancel := context.WithTimeout(ctx, cfg.ConnectTimeout) + defer cancel() + conn, err = dctx.DialContext(ctx, network, address) + } else { + conn, err = d.DialTimeout(network, address, cfg.ConnectTimeout) + } + if err != nil { + return nil, err + } + err = conn.SetDeadline(deadline) + return conn, err + } + if dctx, ok := d.(DialerContext); ok { + return dctx.DialContext(ctx, network, address) + } + return d.Dial(network, address) +} + +func (cn *conn) isInTransaction() bool { + return cn.txnStatus == txnStatusIdleInTransaction || + cn.txnStatus == txnStatusInFailedTransaction +} + +func (cn *conn) checkIsInTransaction(intxn bool) error { + if cn.isInTransaction() != intxn { + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected transaction status %v", cn.txnStatus) + } + return nil +} + +func (cn *conn) Begin() (_ driver.Tx, err error) { + return cn.begin("") +} + +func (cn *conn) begin(mode string) (_ driver.Tx, err error) { + if err := cn.err.get(); err != nil { + return nil, err + } + if err := cn.checkIsInTransaction(false); err != nil { + return nil, err + } + + _, commandTag, err := cn.simpleExec("BEGIN" + mode) + if err != nil { + return nil, cn.handleError(err) + } + if commandTag != "BEGIN" { + cn.err.set(driver.ErrBadConn) + return nil, fmt.Errorf("unexpected command tag %s", commandTag) + } + if cn.txnStatus != txnStatusIdleInTransaction { + cn.err.set(driver.ErrBadConn) + return nil, fmt.Errorf("unexpected transaction status %v", cn.txnStatus) + } + return cn, nil +} + +func (cn *conn) closeTxn() { + if finish := cn.txnFinish; finish != nil { + finish() + } +} + +func (cn *conn) Commit() error { + defer cn.closeTxn() + if err := cn.err.get(); err != nil { + return err + } + if err := cn.checkIsInTransaction(true); err != nil { + return err + } + + // We don't want the client to think that everything is okay if it tries + // to commit a failed transaction. However, no matter what we return, + // database/sql will release this connection back into the free connection + // pool so we have to abort the current transaction here. Note that you + // would get the same behaviour if you issued a COMMIT in a failed + // transaction, so it's also the least surprising thing to do here. + if cn.txnStatus == txnStatusInFailedTransaction { + if err := cn.rollback(); err != nil { + return err + } + return ErrInFailedTransaction + } + + _, commandTag, err := cn.simpleExec("COMMIT") + if err != nil { + if cn.isInTransaction() { + cn.err.set(driver.ErrBadConn) + } + return cn.handleError(err) + } + if commandTag != "COMMIT" { + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("unexpected command tag %s", commandTag) + } + return cn.checkIsInTransaction(false) +} + +func (cn *conn) Rollback() error { + defer cn.closeTxn() + if err := cn.err.get(); err != nil { + return err + } + + err := cn.rollback() + if err != nil { + return cn.handleError(err) + } + return nil +} + +func (cn *conn) rollback() (err error) { + if err := cn.checkIsInTransaction(true); err != nil { + return err + } + + _, commandTag, err := cn.simpleExec("ROLLBACK") + if err != nil { + if cn.isInTransaction() { + cn.err.set(driver.ErrBadConn) + } + return err + } + if commandTag != "ROLLBACK" { + return fmt.Errorf("unexpected command tag %s", commandTag) + } + return cn.checkIsInTransaction(false) +} + +func (cn *conn) gname() string { + cn.namei++ + return strconv.FormatInt(int64(cn.namei), 10) +} + +func (cn *conn) simpleExec(q string) (res driver.Result, commandTag string, resErr error) { + if debugProto { + fmt.Fprintln(os.Stderr, " START conn.simpleExec") + defer fmt.Fprintln(os.Stderr, " END conn.simpleExec") + } + + b := cn.writeBuf(proto.Query) + b.string(q) + err := cn.send(b) + if err != nil { + return nil, "", err + } + + for { + t, r, err := cn.recv1() + if err != nil { + return nil, "", err + } + switch t { + case proto.CommandComplete: + res, commandTag, err = cn.parseComplete(r.string()) + if err != nil { + return nil, "", err + } + case proto.ReadyForQuery: + cn.processReadyForQuery(r) + if res == nil && resErr == nil { + resErr = errUnexpectedReady + } + return res, commandTag, resErr + case proto.ErrorResponse: + resErr = parseError(r, q) + case proto.EmptyQueryResponse: + res = emptyRows + case proto.RowDescription, proto.DataRow: + // ignore any results + default: + cn.err.set(driver.ErrBadConn) + return nil, "", fmt.Errorf("pq: unknown response for simple query: %q", t) + } + } +} + +func (cn *conn) simpleQuery(q string) (*rows, error) { + if debugProto { + fmt.Fprintln(os.Stderr, " START conn.simpleQuery") + defer fmt.Fprintln(os.Stderr, " END conn.simpleQuery") + } + + b := cn.writeBuf(proto.Query) + b.string(q) + err := cn.send(b) + if err != nil { + return nil, cn.handleError(err, q) + } + + var ( + res *rows + resErr error + ) + for { + t, r, err := cn.recv1() + if err != nil { + return nil, cn.handleError(err, q) + } + switch t { + case proto.CommandComplete, proto.EmptyQueryResponse: + // We allow queries which don't return any results through Query as + // well as Exec. We still have to give database/sql a rows object + // the user can close, though, to avoid connections from being + // leaked. A "rows" with done=true works fine for that purpose. + if resErr != nil { + cn.err.set(driver.ErrBadConn) + return nil, fmt.Errorf("pq: unexpected message %q in simple query execution", t) + } + if res == nil { + res = &rows{cn: cn} + } + // Set the result and tag to the last command complete if there wasn't a + // query already run. Although queries usually return from here and cede + // control to Next, a query with zero results does not. + if t == proto.CommandComplete { + res.result, res.tag, err = cn.parseComplete(r.string()) + if err != nil { + return nil, cn.handleError(err, q) + } + if res.colNames != nil { + return res, cn.handleError(resErr, q) + } + } + res.done = true + case proto.ReadyForQuery: + cn.processReadyForQuery(r) + if err == nil && res == nil { + res = &rows{done: true} + } + return res, cn.handleError(resErr, q) // done + case proto.ErrorResponse: + res = nil + resErr = parseError(r, q) + case proto.DataRow: + if res == nil { + cn.err.set(driver.ErrBadConn) + return nil, fmt.Errorf("pq: unexpected DataRow in simple query execution") + } + return res, cn.saveMessage(t, r) // The query didn't fail; kick off to Next + case proto.RowDescription: + // res might be non-nil here if we received a previous + // CommandComplete, but that's fine and just overwrite it. + res = &rows{cn: cn, rowsHeader: parsePortalRowDescribe(r)} + + // To work around a bug in QueryRow in Go 1.2 and earlier, wait + // until the first DataRow has been received. + default: + cn.err.set(driver.ErrBadConn) + return nil, fmt.Errorf("pq: unknown response for simple query: %q", t) + } + } +} + +// Decides which column formats to use for a prepared statement. The input is +// an array of type oids, one element per result column. +func decideColumnFormats(colTyps []fieldDesc, forceText bool) (colFmts []format, colFmtData []byte, _ error) { + if len(colTyps) == 0 { + return nil, colFmtDataAllText, nil + } + + colFmts = make([]format, len(colTyps)) + if forceText { + return colFmts, colFmtDataAllText, nil + } + + allBinary := true + allText := true + for i, t := range colTyps { + switch t.OID { + // This is the list of types to use binary mode for when receiving them + // through a prepared statement. If a type appears in this list, it + // must also be implemented in binaryDecode in encode.go. + case oid.T_bytea: + fallthrough + case oid.T_int8: + fallthrough + case oid.T_int4: + fallthrough + case oid.T_int2: + fallthrough + case oid.T_uuid: + colFmts[i] = formatBinary + allText = false + default: + allBinary = false + } + } + + if allBinary { + return colFmts, colFmtDataAllBinary, nil + } else if allText { + return colFmts, colFmtDataAllText, nil + } else { + colFmtData = make([]byte, 2+len(colFmts)*2) + if len(colFmts) > math.MaxUint16 { + return nil, nil, fmt.Errorf("pq: too many columns (%d > math.MaxUint16)", len(colFmts)) + } + binary.BigEndian.PutUint16(colFmtData, uint16(len(colFmts))) + for i, v := range colFmts { + binary.BigEndian.PutUint16(colFmtData[2+i*2:], uint16(v)) + } + return colFmts, colFmtData, nil + } +} + +func (cn *conn) prepareTo(q, stmtName string) (*stmt, error) { + if debugProto { + fmt.Fprintln(os.Stderr, " START conn.prepareTo") + defer fmt.Fprintln(os.Stderr, " END conn.prepareTo") + } + + st := &stmt{cn: cn, name: stmtName} + + b := cn.writeBuf(proto.Parse) + b.string(st.name) + b.string(q) + b.int16(0) + + b.next(proto.Describe) + b.byte(proto.Sync) + b.string(st.name) + + b.next(proto.Sync) + err := cn.send(b) + if err != nil { + return nil, err + } + + err = cn.readParseResponse() + if err != nil { + return nil, err + } + st.paramTyps, st.colNames, st.colTyps, err = cn.readStatementDescribeResponse() + if err != nil { + return nil, err + } + st.colFmts, st.colFmtData, err = decideColumnFormats(st.colTyps, cn.cfg.DisablePreparedBinaryResult) + if err != nil { + return nil, err + } + + err = cn.readReadyForQuery() + if err != nil { + return nil, err + } + return st, nil +} + +func (cn *conn) Prepare(q string) (driver.Stmt, error) { + if err := cn.err.get(); err != nil { + return nil, err + } + + if pqsql.StartsWithCopy(q) { + s, err := cn.prepareCopyIn(q) + if err == nil { + cn.inProgress.Store(true) + } + return s, cn.handleError(err, q) + } + s, err := cn.prepareTo(q, cn.gname()) + if err != nil { + return nil, cn.handleError(err, q) + } + return s, nil +} + +func (cn *conn) Close() error { + // Don't go through send(); ListenerConn relies on us not scribbling on the + // scratch buffer of this connection. + err := cn.sendSimpleMessage(proto.Terminate) + if err != nil { + _ = cn.c.Close() // Ensure that cn.c.Close is always run. + return cn.handleError(err) + } + return cn.c.Close() +} + +func toNamedValue(v []driver.Value) []driver.NamedValue { + v2 := make([]driver.NamedValue, len(v)) + for i := range v { + v2[i] = driver.NamedValue{Ordinal: i + 1, Value: v[i]} + } + return v2 +} + +// CheckNamedValue implements [driver.NamedValueChecker]. +func (cn *conn) CheckNamedValue(nv *driver.NamedValue) error { + if cn.cfg.BinaryParameters { + if bin, ok := nv.Value.(interface{ BinaryValue() ([]byte, error) }); ok { + var err error + nv.Value, err = bin.BinaryValue() + return err + } + } + + // Ignore Valuer, for backward compatibility with pq.Array(). + if _, ok := nv.Value.(driver.Valuer); ok { + return driver.ErrSkip + } + + v := reflect.ValueOf(nv.Value) + if !v.IsValid() { + return driver.ErrSkip + } + t := v.Type() + for t.Kind() == reflect.Pointer { + t, v = t.Elem(), v.Elem() + } + + // Ignore []byte and related types: *[]byte, json.RawMessage, etc. + if t.Kind() == reflect.Slice && t.Elem().Kind() == reflect.Uint8 { + return driver.ErrSkip + } + + switch v.Kind() { + default: + return driver.ErrSkip + case reflect.Slice: + var err error + nv.Value, err = Array(v.Interface()).Value() + return err + case reflect.Uint64: + value := v.Uint() + if value >= math.MaxInt64 { + nv.Value = strconv.FormatUint(value, 10) + } else { + nv.Value = int64(value) + } + return nil + } +} + +// Implement the "Queryer" interface +func (cn *conn) Query(query string, args []driver.Value) (driver.Rows, error) { + return cn.query(query, toNamedValue(args)) +} + +func (cn *conn) query(query string, args []driver.NamedValue) (*rows, error) { + if debugProto { + fmt.Fprintln(os.Stderr, " START conn.query") + defer fmt.Fprintln(os.Stderr, " END conn.query") + } + if err := cn.err.get(); err != nil { + return nil, err + } + if !cn.inProgress.CompareAndSwap(false, true) { + return nil, errQueryInProgress + } + + // Check to see if we can use the "simpleQuery" interface, which is + // *much* faster than going through prepare/exec + if len(args) == 0 { + return cn.simpleQuery(query) + } + + if cn.cfg.BinaryParameters { + err := cn.sendBinaryModeQuery(query, args) + if err != nil { + return nil, cn.handleError(err, query) + } + err = cn.readParseResponse() + if err != nil { + return nil, cn.handleError(err, query) + } + err = cn.readBindResponse() + if err != nil { + return nil, cn.handleError(err, query) + } + + rows := &rows{cn: cn} + rows.rowsHeader, err = cn.readPortalDescribeResponse() + if err != nil { + return nil, cn.handleError(err, query) + } + err = cn.postExecuteWorkaround() + if err != nil { + return nil, cn.handleError(err, query) + } + return rows, nil + } + + st, err := cn.prepareTo(query, "") + if err != nil { + return nil, cn.handleError(err, query) + } + err = st.exec(args) + if err != nil { + return nil, cn.handleError(err, query) + } + return &rows{ + cn: cn, + rowsHeader: st.rowsHeader, + }, nil +} + +// Implement the optional "Execer" interface for one-shot queries +func (cn *conn) Exec(query string, args []driver.Value) (driver.Result, error) { + if err := cn.err.get(); err != nil { + return nil, err + } + if !cn.inProgress.CompareAndSwap(false, true) { + return nil, errQueryInProgress + } + + // Check to see if we can use the "simpleExec" interface, which is *much* + // faster than going through prepare/exec + if len(args) == 0 { + // ignore commandTag, our caller doesn't care + r, _, err := cn.simpleExec(query) + return r, cn.handleError(err, query) + } + + if cn.cfg.BinaryParameters { + err := cn.sendBinaryModeQuery(query, toNamedValue(args)) + if err != nil { + return nil, cn.handleError(err, query) + } + err = cn.readParseResponse() + if err != nil { + return nil, cn.handleError(err, query) + } + err = cn.readBindResponse() + if err != nil { + return nil, cn.handleError(err, query) + } + + _, err = cn.readPortalDescribeResponse() + if err != nil { + return nil, cn.handleError(err, query) + } + err = cn.postExecuteWorkaround() + if err != nil { + return nil, cn.handleError(err, query) + } + res, _, err := cn.readExecuteResponse("Execute") + return res, cn.handleError(err, query) + } + + // Use the unnamed statement to defer planning until bind time, or else + // value-based selectivity estimates cannot be used. + st, err := cn.prepareTo(query, "") + if err != nil { + return nil, cn.handleError(err, query) + } + r, err := st.Exec(args) + if err != nil { + return nil, cn.handleError(err, query) + } + return r, nil +} + +type safeRetryError struct{ Err error } + +func (se *safeRetryError) Error() string { return se.Err.Error() } + +func (cn *conn) send(m *writeBuf) error { + if debugProto { + w := m.wrap() + for len(w) > 0 { // Can contain multiple messages. + c := proto.RequestCode(w[0]) + l := int(binary.BigEndian.Uint32(w[1:5])) - 4 + fmt.Fprintf(os.Stderr, "CLIENT → %-20s %5d %q\n", c, l, w[5:l+5]) + w = w[l+5:] + } + } + + n, err := cn.c.Write(m.wrap()) + if err != nil && n == 0 { + err = &safeRetryError{Err: err} + } + return err +} + +func (cn *conn) sendStartupPacket(m *writeBuf) error { + if debugProto { + w := m.wrap() + fmt.Fprintf(os.Stderr, "CLIENT → %-20s %5d %q\n", "Startup", int(binary.BigEndian.Uint32(w[1:5]))-4, w[5:]) + } + _, err := cn.c.Write((m.wrap())[1:]) + return err +} + +// Send a message of type typ to the server on the other end of cn. The message +// should have no payload. This method does not use the scratch buffer. +func (cn *conn) sendSimpleMessage(typ proto.RequestCode) error { + if debugProto { + fmt.Fprintf(os.Stderr, "CLIENT → %-20s %5d %q\n", typ, 0, []byte{}) + } + _, err := cn.c.Write([]byte{byte(typ), '\x00', '\x00', '\x00', '\x04'}) + return err +} + +// saveMessage memorizes a message and its buffer in the conn struct. +// recvMessage will then return these values on the next call to it. This +// method is useful in cases where you have to see what the next message is +// going to be (e.g. to see whether it's an error or not) but you can't handle +// the message yourself. +func (cn *conn) saveMessage(typ proto.ResponseCode, buf *readBuf) error { + if cn.saveMessageType != 0 { + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("unexpected saveMessageType %d", cn.saveMessageType) + } + cn.saveMessageType = typ + cn.saveMessageBuffer = *buf + return nil +} + +// recvMessage receives any message from the backend, or returns an error if +// a problem occurred while reading the message. +func (cn *conn) recvMessage(r *readBuf) (proto.ResponseCode, error) { + // workaround for a QueryRow bug, see exec + if cn.saveMessageType != 0 { + t := cn.saveMessageType + *r = cn.saveMessageBuffer + cn.saveMessageType = 0 + cn.saveMessageBuffer = nil + return t, nil + } + + x := cn.scratch[:5] + _, err := io.ReadFull(cn.buf, x) + if err != nil { + return 0, err + } + + // Read the type and length of the message that follows. + t := proto.ResponseCode(x[0]) + n := int(binary.BigEndian.Uint32(x[1:])) - 4 + + if proto.ResponseCode(t) == proto.ReadyForQuery { + cn.inProgress.Store(false) + } + + // When PostgreSQL cannot start a backend (e.g., an external process limit), + // it sends plain text like "Ecould not fork new process [..]", which + // doesn't use the standard encoding for the Error message. + // + // libpq checks "if ErrorResponse && (msgLength < 8 || msgLength > MAX_ERRLEN)", + // but check < 4 since n represents bytes remaining to be read after length. + if t == proto.ErrorResponse && (n < 4 || n > proto.MaxErrlen) { + msg, _ := cn.buf.ReadString('\x00') + return 0, fmt.Errorf("pq: server error: %s%s", string(x[1:]), strings.TrimSuffix(msg, "\x00")) + } + + var y []byte + if n <= len(cn.scratch) { + y = cn.scratch[:n] + } else { + y = make([]byte, n) + } + _, err = io.ReadFull(cn.buf, y) + if err != nil { + return 0, err + } + *r = y + if debugProto { + fmt.Fprintf(os.Stderr, "SERVER ← %-20s %5d %q\n", t, n, y) + } + return t, nil +} + +// recv receives a message from the backend, returning an error if an error +// happened while reading the message or the received message an ErrorResponse. +// NoticeResponses are ignored. This function should generally be used only +// during the startup sequence. +func (cn *conn) recv() (proto.ResponseCode, *readBuf, error) { + for { + r := new(readBuf) + t, err := cn.recvMessage(r) + if err != nil { + return 0, nil, err + } + switch t { + case proto.ErrorResponse: + return 0, nil, parseError(r, "") + case proto.NoticeResponse: + if n := cn.noticeHandler; n != nil { + n(parseError(r, "")) + } + case proto.NotificationResponse: + if n := cn.notificationHandler; n != nil { + n(recvNotification(r)) + } + default: + return t, r, nil + } + } +} + +// recv1Buf is exactly equivalent to recv1, except it uses a buffer supplied by +// the caller to avoid an allocation. +func (cn *conn) recv1Buf(r *readBuf) (proto.ResponseCode, error) { + for { + t, err := cn.recvMessage(r) + if err != nil { + return 0, err + } + + switch t { + case proto.NotificationResponse: + if n := cn.notificationHandler; n != nil { + n(recvNotification(r)) + } + case proto.NoticeResponse: + if n := cn.noticeHandler; n != nil { + n(parseError(r, "")) + } + case proto.ParameterStatus: + cn.processParameterStatus(r) + default: + return t, nil + } + } +} + +// recv1 receives a message from the backend, returning an error if an error +// happened while reading the message or the received message an ErrorResponse. +// All asynchronous messages are ignored, with the exception of ErrorResponse. +func (cn *conn) recv1() (proto.ResponseCode, *readBuf, error) { + r := new(readBuf) + t, err := cn.recv1Buf(r) + if err != nil { + return 0, nil, err + } + return t, r, nil +} + +// Don't refer to Config.SSLMode here, as the mode in arguments may be different +// in case of sslmode=allow or prefer. +func (cn *conn) ssl(cfg Config, mode SSLMode) error { + upgrade, err := ssl(cfg, mode) + if err != nil { + return err + } + if upgrade == nil { + return nil // Nothing to do + } + + // Only negotiate the ssl handshake if requested (which is the default). + // sslnegotiation=direct is supported by pg17 and above. + if cfg.SSLNegotiation != SSLNegotiationDirect { + w := cn.writeBuf(0) + w.int32(proto.NegotiateSSLCode) + if err = cn.sendStartupPacket(w); err != nil { + return err + } + + b := cn.scratch[:1] + _, err = io.ReadFull(cn.c, b) + if err != nil { + return err + } + + if b[0] != 'S' { + return ErrSSLNotSupported + } + } + + cn.c, err = upgrade(cn.c) + return err +} + +func (cn *conn) startup(cfg Config) error { + w := cn.writeBuf(0) + // Send maximum protocol version in startup; if the server doesn't support + // this version it responds with NegotiateProtocolVersion and the maximum + // version it supports (and will use). + w.int32(cfg.MaxProtocolVersion.proto()) + + if cfg.User != "" { + w.string("user") + w.string(cfg.User) + } + if cfg.Database != "" { + w.string("database") + w.string(cfg.Database) + } + // w.string("replication") // Sent by libpq, but we don't support that. + if cfg.Options != "" { + w.string("options") + w.string(cfg.Options) + } + if cfg.ApplicationName != "" { + w.string("application_name") + w.string(cfg.ApplicationName) + } + if cfg.ClientEncoding != "" { + w.string("client_encoding") + w.string(cfg.ClientEncoding) + } + if cfg.Datestyle != "" { + w.string("datestyle") + w.string(cfg.Datestyle) + } + for k, v := range cfg.Runtime { + w.string(k) + w.string(v) + } + + w.string("") + if err := cn.sendStartupPacket(w); err != nil { + return err + } + + for { + t, r, err := cn.recv() + if err != nil { + return err + } + switch t { + case proto.BackendKeyData: + cn.pid = r.int32() + if len(*r) > 256 { + return fmt.Errorf("pq: cancellation key longer than 256 bytes: %d bytes", len(*r)) + } + cn.secretKey = make([]byte, len(*r)) + copy(cn.secretKey, *r) + case proto.ParameterStatus: + cn.processParameterStatus(r) + case proto.AuthenticationRequest: + err := cn.auth(r, cfg) + if err != nil { + return err + } + case proto.NegotiateProtocolVersion: + newestMinor := r.int32() + serverVersion := proto.ProtocolVersion30&0xFFFF0000 | newestMinor + if serverVersion < cfg.MinProtocolVersion.proto() { + return fmt.Errorf("pq: protocol version mismatch: min_protocol_version=%s; server supports up to 3.%d", cfg.MinProtocolVersion, newestMinor) + } + case proto.ReadyForQuery: + cn.processReadyForQuery(r) + return nil + default: + return fmt.Errorf("pq: unknown response for startup: %q", t) + } + } +} + +func (cn *conn) auth(r *readBuf, cfg Config) error { + switch code := proto.AuthCode(r.int32()); code { + default: + return fmt.Errorf("pq: unknown authentication response: %s", code) + case proto.AuthReqKrb4, proto.AuthReqKrb5, proto.AuthReqCrypt, proto.AuthReqSSPI: + return fmt.Errorf("pq: unsupported authentication method: %s", code) + case proto.AuthReqOk: + return nil + + case proto.AuthReqPassword: + w := cn.writeBuf(proto.PasswordMessage) + w.string(cfg.Password) + // Don't need to check AuthOk response here; auth() is called in a loop, + // which catches the errors and AuthReqOk responses. + return cn.send(w) + + case proto.AuthReqMD5: + s := string(r.next(4)) + w := cn.writeBuf(proto.PasswordMessage) + w.string("md5" + md5s(md5s(cfg.Password+cfg.User)+s)) + // Same here. + return cn.send(w) + + case proto.AuthReqGSS: // GSSAPI, startup + if newGss == nil { + return fmt.Errorf("pq: kerberos error: no GSSAPI provider registered (import github.com/lib/pq/auth/kerberos)") + } + cli, err := newGss() + if err != nil { + return fmt.Errorf("pq: kerberos error: %w", err) + } + + var token []byte + if cfg.KrbSpn != "" { + // Use the supplied SPN if provided. + token, err = cli.GetInitTokenFromSpn(cfg.KrbSpn) + } else { + // Allow the kerberos service name to be overridden. + service := "postgres" + if cfg.KrbSrvname != "" { + service = cfg.KrbSrvname + } + token, err = cli.GetInitToken(cfg.Host, service) + } + if err != nil { + return fmt.Errorf("pq: failed to get Kerberos ticket: %w", err) + } + + w := cn.writeBuf(proto.GSSResponse) + w.bytes(token) + err = cn.send(w) + if err != nil { + return err + } + + // Store for GSSAPI continue message + cn.gss = cli + return nil + + case proto.AuthReqGSSCont: // GSSAPI continue + if cn.gss == nil { + return errors.New("pq: GSSAPI protocol error") + } + + done, tokOut, err := cn.gss.Continue([]byte(*r)) + if err == nil && !done { + w := cn.writeBuf(proto.SASLInitialResponse) + w.bytes(tokOut) + err = cn.send(w) + if err != nil { + return err + } + } + + // Errors fall through and read the more detailed message from the + // server. + return nil + + case proto.AuthReqSASL: + sc := scram.NewClient(sha256.New, cfg.User, cfg.Password) + sc.Step(nil) + if sc.Err() != nil { + return fmt.Errorf("pq: SCRAM-SHA-256 error: %w", sc.Err()) + } + scOut := sc.Out() + + w := cn.writeBuf(proto.SASLResponse) + w.string("SCRAM-SHA-256") + w.int32(len(scOut)) + w.bytes(scOut) + err := cn.send(w) + if err != nil { + return err + } + + t, r, err := cn.recv() + if err != nil { + return err + } + if t != proto.AuthenticationRequest { + return fmt.Errorf("pq: unexpected password response: %q", t) + } + + if r.int32() != int(proto.AuthReqSASLCont) { + return fmt.Errorf("pq: unexpected authentication response: %q", t) + } + + nextStep := r.next(len(*r)) + sc.Step(nextStep) + if sc.Err() != nil { + return fmt.Errorf("pq: SCRAM-SHA-256 error: %w", sc.Err()) + } + + scOut = sc.Out() + w = cn.writeBuf(proto.SASLResponse) + w.bytes(scOut) + err = cn.send(w) + if err != nil { + return err + } + + t, r, err = cn.recv() + if err != nil { + return err + } + if t != proto.AuthenticationRequest { + return fmt.Errorf("pq: unexpected password response: %q", t) + } + + if r.int32() != int(proto.AuthReqSASLFin) { + return fmt.Errorf("pq: unexpected authentication response: %q", t) + } + + nextStep = r.next(len(*r)) + sc.Step(nextStep) + if sc.Err() != nil { + return fmt.Errorf("pq: SCRAM-SHA-256 error: %w", sc.Err()) + } + + return nil + } +} + +// parseComplete parses the "command tag" from a CommandComplete message, and +// returns the number of rows affected (if applicable) and a string identifying +// only the command that was executed, e.g. "ALTER TABLE". Returns an error if +// the command can cannot be parsed. +func (cn *conn) parseComplete(commandTag string) (driver.Result, string, error) { + commandsWithAffectedRows := []string{ + "SELECT ", + // INSERT is handled below + "UPDATE ", + "DELETE ", + "FETCH ", + "MOVE ", + "COPY ", + } + + var affectedRows *string + for _, tag := range commandsWithAffectedRows { + if strings.HasPrefix(commandTag, tag) { + t := commandTag[len(tag):] + affectedRows = &t + commandTag = tag[:len(tag)-1] + break + } + } + // INSERT also includes the oid of the inserted row in its command tag. Oids + // in user tables are deprecated, and the oid is only returned when exactly + // one row is inserted, so it's unlikely to be of value to any real-world + // application and we can ignore it. + if affectedRows == nil && strings.HasPrefix(commandTag, "INSERT ") { + parts := strings.Split(commandTag, " ") + if len(parts) != 3 { + cn.err.set(driver.ErrBadConn) + return nil, "", fmt.Errorf("pq: unexpected INSERT command tag %s", commandTag) + } + affectedRows = &parts[len(parts)-1] + commandTag = "INSERT" + } + // There should be no affected rows attached to the tag, just return it + if affectedRows == nil { + return driver.RowsAffected(0), commandTag, nil + } + n, err := strconv.ParseInt(*affectedRows, 10, 64) + if err != nil { + cn.err.set(driver.ErrBadConn) + return nil, "", fmt.Errorf("pq: could not parse commandTag: %w", err) + } + return driver.RowsAffected(n), commandTag, nil +} + +func md5s(s string) string { + h := md5.New() + h.Write([]byte(s)) + return fmt.Sprintf("%x", h.Sum(nil)) +} + +func (cn *conn) sendBinaryParameters(b *writeBuf, args []driver.NamedValue) error { + // Do one pass over the parameters to see if we're going to send any of them + // over in binary. If we are, create a paramFormats array at the same time. + var paramFormats []int + for i, x := range args { + _, ok := x.Value.([]byte) + if ok { + if paramFormats == nil { + paramFormats = make([]int, len(args)) + } + paramFormats[i] = 1 + } + } + if paramFormats == nil { + b.int16(0) + } else { + b.int16(len(paramFormats)) + for _, x := range paramFormats { + b.int16(x) + } + } + + b.int16(len(args)) + for _, x := range args { + if x.Value == nil { + b.int32(-1) + } else if xx, ok := x.Value.([]byte); ok && xx == nil { + b.int32(-1) + } else { + datum, err := binaryEncode(x.Value) + if err != nil { + return err + } + b.int32(len(datum)) + b.bytes(datum) + } + } + return nil +} + +func (cn *conn) sendBinaryModeQuery(query string, args []driver.NamedValue) error { + if len(args) >= 65536 { + return fmt.Errorf("pq: got %d parameters but PostgreSQL only supports 65535 parameters", len(args)) + } + + b := cn.writeBuf(proto.Parse) + b.byte(0) // unnamed statement + b.string(query) + b.int16(0) + + b.next(proto.Bind) + b.int16(0) // unnamed portal and statement + err := cn.sendBinaryParameters(b, args) + if err != nil { + return err + } + b.bytes(colFmtDataAllText) + + b.next(proto.Describe) + b.byte(proto.Parse) + b.byte(0) // unnamed portal + + b.next(proto.Execute) + b.byte(0) + b.int32(0) + + b.next(proto.Sync) + return cn.send(b) +} + +func (cn *conn) processParameterStatus(r *readBuf) { + switch r.string() { + default: + // ignore + case "server_version": + var major1, major2 int + _, err := fmt.Sscanf(r.string(), "%d.%d", &major1, &major2) + if err == nil { + cn.parameterStatus.serverVersion = major1*10000 + major2*100 + } + case "TimeZone": + switch tz := r.string(); tz { + case "UTC", "Etc/UTC", "Etc/Universal", "Etc/Zulu", "Etc/UCT": + cn.parameterStatus.currentLocation = time.UTC + default: + var err error + cn.parameterStatus.currentLocation, err = time.LoadLocation(tz) + if err != nil { + cn.parameterStatus.currentLocation = nil + } + } + // Use sql.NullBool so we can distinguish between false and not sent. If + // it's not sent we use a query to get the value – I don't know when these + // parameters are not sent, but this is what libpq does. + case "in_hot_standby": + b, err := pqutil.ParseBool(r.string()) + if err == nil { + cn.parameterStatus.inHotStandby = sql.NullBool{Valid: true, Bool: b} + } + case "default_transaction_read_only": + b, err := pqutil.ParseBool(r.string()) + if err == nil { + cn.parameterStatus.defaultTransactionReadOnly = sql.NullBool{Valid: true, Bool: b} + } + } +} + +func (cn *conn) processReadyForQuery(r *readBuf) { + cn.txnStatus = transactionStatus(r.byte()) +} + +func (cn *conn) readReadyForQuery() error { + t, r, err := cn.recv1() + if err != nil { + return err + } + switch t { + case proto.ReadyForQuery: + cn.processReadyForQuery(r) + return nil + case proto.ErrorResponse: + err := parseError(r, "") + cn.err.set(driver.ErrBadConn) + return err + default: + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected message %q; expected ReadyForQuery", t) + } +} + +func (cn *conn) readParseResponse() error { + t, r, err := cn.recv1() + if err != nil { + return err + } + switch t { + case proto.ParseComplete: + return nil + case proto.ErrorResponse: + err := parseError(r, "") + _ = cn.readReadyForQuery() + return err + default: + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected Parse response %q", t) + } +} + +func (cn *conn) readStatementDescribeResponse() (paramTyps []oid.Oid, colNames []string, colTyps []fieldDesc, _ error) { + for { + t, r, err := cn.recv1() + if err != nil { + return nil, nil, nil, err + } + switch t { + case proto.ParameterDescription: + nparams := r.int16() + paramTyps = make([]oid.Oid, nparams) + for i := range paramTyps { + paramTyps[i] = r.oid() + } + case proto.NoData: + return paramTyps, nil, nil, nil + case proto.RowDescription: + colNames, colTyps = parseStatementRowDescribe(r) + return paramTyps, colNames, colTyps, nil + case proto.ErrorResponse: + err := parseError(r, "") + _ = cn.readReadyForQuery() + return nil, nil, nil, err + default: + cn.err.set(driver.ErrBadConn) + return nil, nil, nil, fmt.Errorf("pq: unexpected Describe statement response %q", t) + } + } +} + +func (cn *conn) readPortalDescribeResponse() (rowsHeader, error) { + t, r, err := cn.recv1() + if err != nil { + return rowsHeader{}, err + } + switch t { + case proto.RowDescription: + return parsePortalRowDescribe(r), nil + case proto.NoData: + return rowsHeader{}, nil + case proto.ErrorResponse: + err := parseError(r, "") + _ = cn.readReadyForQuery() + return rowsHeader{}, err + default: + cn.err.set(driver.ErrBadConn) + return rowsHeader{}, fmt.Errorf("pq: unexpected Describe response %q", t) + } +} + +func (cn *conn) readBindResponse() error { + t, r, err := cn.recv1() + if err != nil { + return err + } + switch t { + case proto.BindComplete: + return nil + case proto.ErrorResponse: + err := parseError(r, "") + _ = cn.readReadyForQuery() + return err + default: + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected Bind response %q", t) + } +} + +func (cn *conn) postExecuteWorkaround() error { + // Work around a bug in sql.DB.QueryRow: in Go 1.2 and earlier it ignores + // any errors from rows.Next, which masks errors that happened during the + // execution of the query. To avoid the problem in common cases, we wait + // here for one more message from the database. If it's not an error the + // query will likely succeed (or perhaps has already, if it's a + // CommandComplete), so we push the message into the conn struct; recv1 + // will return it as the next message for rows.Next or rows.Close. + // However, if it's an error, we wait until ReadyForQuery and then return + // the error to our caller. + for { + t, r, err := cn.recv1() + if err != nil { + return err + } + switch t { + case proto.ErrorResponse: + err := parseError(r, "") + _ = cn.readReadyForQuery() + return err + case proto.CommandComplete, proto.DataRow, proto.EmptyQueryResponse: + // the query didn't fail, but we can't process this message + return cn.saveMessage(t, r) + default: + cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected message during extended query execution: %q", t) + } + } +} + +// Only for Exec(), since we ignore the returned data +func (cn *conn) readExecuteResponse(protocolState string) (res driver.Result, commandTag string, resErr error) { + for { + t, r, err := cn.recv1() + if err != nil { + return nil, "", err + } + switch t { + case proto.CommandComplete: + if resErr != nil { + cn.err.set(driver.ErrBadConn) + return nil, "", fmt.Errorf("pq: unexpected CommandComplete after error %s", resErr) + } + res, commandTag, err = cn.parseComplete(r.string()) + if err != nil { + return nil, "", err + } + case proto.ReadyForQuery: + cn.processReadyForQuery(r) + if res == nil && resErr == nil { + resErr = errUnexpectedReady + } + return res, commandTag, resErr + case proto.ErrorResponse: + resErr = parseError(r, "") + case proto.RowDescription, proto.DataRow, proto.EmptyQueryResponse: + if resErr != nil { + cn.err.set(driver.ErrBadConn) + return nil, "", fmt.Errorf("pq: unexpected %q after error %s", t, resErr) + } + if t == proto.EmptyQueryResponse { + res = emptyRows + } + // ignore any results + default: + cn.err.set(driver.ErrBadConn) + return nil, "", fmt.Errorf("pq: unknown %s response: %q", protocolState, t) + } + } +} + +func parseStatementRowDescribe(r *readBuf) (colNames []string, colTyps []fieldDesc) { + n := r.int16() + colNames = make([]string, n) + colTyps = make([]fieldDesc, n) + for i := range colNames { + colNames[i] = r.string() + r.next(6) + colTyps[i].OID = r.oid() + colTyps[i].Len = r.int16() + colTyps[i].Mod = r.int32() + // format code not known when describing a statement; always 0 + r.next(2) + } + return +} + +func parsePortalRowDescribe(r *readBuf) rowsHeader { + n := r.int16() + colNames := make([]string, n) + colFmts := make([]format, n) + colTyps := make([]fieldDesc, n) + for i := range colNames { + colNames[i] = r.string() + r.next(6) + colTyps[i].OID = r.oid() + colTyps[i].Len = r.int16() + colTyps[i].Mod = r.int32() + colFmts[i] = format(r.int16()) + } + return rowsHeader{ + colNames: colNames, + colFmts: colFmts, + colTyps: colTyps, + } +} + +func (cn *conn) ResetSession(ctx context.Context) error { + // Ensure bad connections are reported: From database/sql/driver: + // If a connection is never returned to the connection pool but immediately reused, then + // ResetSession is called prior to reuse but IsValid is not called. + return cn.err.get() +} + +func (cn *conn) IsValid() bool { + return cn.err.get() == nil +} diff --git a/vendor/github.com/lib/pq/conn_go18.go b/vendor/github.com/lib/pq/conn_go18.go new file mode 100644 index 0000000..16de38e --- /dev/null +++ b/vendor/github.com/lib/pq/conn_go18.go @@ -0,0 +1,226 @@ +package pq + +import ( + "context" + "database/sql" + "database/sql/driver" + "fmt" + "io" + "time" + + "github.com/lib/pq/internal/proto" +) + +const watchCancelDialContextTimeout = 10 * time.Second + +// Implement the "QueryerContext" interface +func (cn *conn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) { + finish := cn.watchCancel(ctx) + r, err := cn.query(query, args) + if err != nil { + if finish != nil { + finish() + } + return nil, err + } + r.finish = finish + return r, nil +} + +// Implement the "ExecerContext" interface +func (cn *conn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) { + list := make([]driver.Value, len(args)) + for i, nv := range args { + list[i] = nv.Value + } + + if finish := cn.watchCancel(ctx); finish != nil { + defer finish() + } + + return cn.Exec(query, list) +} + +// Implement the "ConnPrepareContext" interface +func (cn *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { + if finish := cn.watchCancel(ctx); finish != nil { + defer finish() + } + return cn.Prepare(query) +} + +// Implement the "ConnBeginTx" interface +func (cn *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { + var mode string + switch sql.IsolationLevel(opts.Isolation) { + case sql.LevelDefault: + // Don't touch mode: use the server's default + case sql.LevelReadUncommitted: + mode = " ISOLATION LEVEL READ UNCOMMITTED" + case sql.LevelReadCommitted: + mode = " ISOLATION LEVEL READ COMMITTED" + case sql.LevelRepeatableRead: + mode = " ISOLATION LEVEL REPEATABLE READ" + case sql.LevelSerializable: + mode = " ISOLATION LEVEL SERIALIZABLE" + default: + return nil, fmt.Errorf("pq: isolation level not supported: %d", opts.Isolation) + } + if opts.ReadOnly { + mode += " READ ONLY" + } else { + mode += " READ WRITE" + } + + tx, err := cn.begin(mode) + if err != nil { + return nil, err + } + cn.txnFinish = cn.watchCancel(ctx) + return tx, nil +} + +func (cn *conn) Ping(ctx context.Context) error { + if finish := cn.watchCancel(ctx); finish != nil { + defer finish() + } + rows, err := cn.simpleQuery(";") + if err != nil { + return driver.ErrBadConn + } + _ = rows.Close() + return nil +} + +func (cn *conn) watchCancel(ctx context.Context) func() { + if done := ctx.Done(); done != nil { + finished := make(chan struct{}, 1) + go func() { + select { + case <-done: + select { + case finished <- struct{}{}: + default: + // We raced with the finish func, let the next query handle this with the + // context. + return + } + + // Set the connection state to bad so it does not get reused. + cn.err.set(ctx.Err()) + + // At this point the function level context is canceled, + // so it must not be used for the additional network + // request to cancel the query. + // Create a new context to pass into the dial. + ctxCancel, cancel := context.WithTimeout(context.Background(), watchCancelDialContextTimeout) + defer cancel() + + _ = cn.cancel(ctxCancel) + case <-finished: + } + }() + return func() { + select { + case <-finished: + cn.err.set(ctx.Err()) + _ = cn.Close() + case finished <- struct{}{}: + } + } + } + return nil +} + +func (cn *conn) cancel(ctx context.Context) error { + // Use a copy since a new connection is created here. This is necessary + // because cancel is called from a goroutine in watchCancel. + cfg := cn.cfg.Clone() + + c, err := dial(ctx, cn.dialer, cfg) + if err != nil { + return err + } + defer func() { _ = c.Close() }() + + cn2 := conn{c: c} + err = cn2.ssl(cfg, cfg.SSLMode) + if err != nil { + return err + } + + w := cn2.writeBuf(0) + w.int32(proto.CancelRequestCode) + w.int32(cn.pid) + w.bytes(cn.secretKey) + if err := cn2.sendStartupPacket(w); err != nil { + return err + } + + // Read until EOF to ensure that the server received the cancel. + _, err = io.Copy(io.Discard, c) + return err +} + +// Implement the "StmtQueryContext" interface +func (st *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { + finish := st.watchCancel(ctx) + r, err := st.query(args) + if err != nil { + if finish != nil { + finish() + } + return nil, err + } + r.finish = finish + return r, nil +} + +// Implement the "StmtExecContext" interface +func (st *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { + if finish := st.watchCancel(ctx); finish != nil { + defer finish() + } + if err := st.cn.err.get(); err != nil { + return nil, err + } + + err := st.exec(args) + if err != nil { + return nil, st.cn.handleError(err) + } + res, _, err := st.cn.readExecuteResponse("simple query") + return res, st.cn.handleError(err) +} + +// watchCancel is implemented on stmt in order to not mark the parent conn as bad +func (st *stmt) watchCancel(ctx context.Context) func() { + if done := ctx.Done(); done != nil { + finished := make(chan struct{}) + go func() { + select { + case <-done: + // At this point the function level context is canceled, so it + // must not be used for the additional network request to cancel + // the query. Create a new context to pass into the dial. + ctxCancel, cancel := context.WithTimeout(context.Background(), watchCancelDialContextTimeout) + defer cancel() + + _ = st.cancel(ctxCancel) + finished <- struct{}{} + case <-finished: + } + }() + return func() { + select { + case <-finished: + case finished <- struct{}{}: + } + } + } + return nil +} + +func (st *stmt) cancel(ctx context.Context) error { + return st.cn.cancel(ctx) +} diff --git a/vendor/github.com/lib/pq/connector.go b/vendor/github.com/lib/pq/connector.go new file mode 100644 index 0000000..a2a8fb2 --- /dev/null +++ b/vendor/github.com/lib/pq/connector.go @@ -0,0 +1,1157 @@ +package pq + +import ( + "context" + "crypto/tls" + "database/sql/driver" + "fmt" + "math/rand" + "net" + "net/netip" + neturl "net/url" + "os" + "path/filepath" + "reflect" + "slices" + "sort" + "strconv" + "strings" + "time" + "unicode" + + "github.com/lib/pq/internal/pgservice" + "github.com/lib/pq/internal/pqutil" + "github.com/lib/pq/internal/proto" +) + +type ( + // SSLMode is a sslmode setting. + SSLMode string + + // SSLNegotiation is a sslnegotiation setting. + SSLNegotiation string + + // TargetSessionAttrs is a target_session_attrs setting. + TargetSessionAttrs string + + // LoadBalanceHosts is a load_balance_hosts setting. + LoadBalanceHosts string + + // ProtocolVersion is a min_protocol_version or max_protocol_version + // setting. + ProtocolVersion string + + // SSLProtocolVersion is a ssl_min_protocol_version or + // ssl_max_protocol_version setting. + SSLProtocolVersion string +) + +// Values for [SSLMode] that pq supports. +const ( + // No SSL + SSLModeDisable = SSLMode("disable") + + // First try a non-SSL connection and if that fails try an SSL connection. + SSLModeAllow = SSLMode("allow") + + // First try an SSL connection and if that fails try a non-SSL connection. + SSLModePrefer = SSLMode("prefer") + + // Require SSL, but skip verification. This is the default. + SSLModeRequire = SSLMode("require") + + // Require SSL and verify that the certificate was signed by a trusted CA. + SSLModeVerifyCA = SSLMode("verify-ca") + + // Require SSL and verify that the certificate was signed by a trusted CA + // and the server host name matches the one in the certificate. + SSLModeVerifyFull = SSLMode("verify-full") +) + +var sslModes = []SSLMode{SSLModeDisable, SSLModeAllow, SSLModePrefer, SSLModeRequire, + SSLModeVerifyFull, SSLModeVerifyCA} + +func (s SSLMode) useSSL() bool { + switch s { + case SSLModePrefer, SSLModeRequire, SSLModeVerifyCA, SSLModeVerifyFull: + return true + } + return false +} + +// Values for [SSLNegotiation] that pq supports. +const ( + // Negotiate whether SSL should be used. This is the default. + SSLNegotiationPostgres = SSLNegotiation("postgres") + + // Always use SSL, don't try to negotiate. + SSLNegotiationDirect = SSLNegotiation("direct") +) + +var sslNegotiations = []SSLNegotiation{SSLNegotiationPostgres, SSLNegotiationDirect} + +// Values for [TargetSessionAttrs] that pq supports. +const ( + // Any successful connection is acceptable. This is the default. + TargetSessionAttrsAny = TargetSessionAttrs("any") + + // Session must accept read-write transactions by default: the server must + // not be in hot standby mode and default_transaction_read_only must be + // off. + TargetSessionAttrsReadWrite = TargetSessionAttrs("read-write") + + // Session must not accept read-write transactions by default. + TargetSessionAttrsReadOnly = TargetSessionAttrs("read-only") + + // Server must not be in hot standby mode. + TargetSessionAttrsPrimary = TargetSessionAttrs("primary") + + // Server must be in hot standby mode. + TargetSessionAttrsStandby = TargetSessionAttrs("standby") + + // First try to find a standby server, but if none of the listed hosts is a + // standby server, try again in any mode. + TargetSessionAttrsPreferStandby = TargetSessionAttrs("prefer-standby") +) + +var targetSessionAttrs = []TargetSessionAttrs{TargetSessionAttrsAny, + TargetSessionAttrsReadWrite, TargetSessionAttrsReadOnly, TargetSessionAttrsPrimary, + TargetSessionAttrsStandby, TargetSessionAttrsPreferStandby} + +// Values for [LoadBalanceHosts] that pq supports. +const ( + // Don't load balance; try hosts in the order in which they're provided. + // This is the default. + LoadBalanceHostsDisable = LoadBalanceHosts("disable") + + // Hosts are tried in random order to balance connections across multiple + // PostgreSQL servers. + // + // When using this value it's recommended to also configure a reasonable + // value for connect_timeout. Because then, if one of the nodes that are + // used for load balancing is not responding, a new node will be tried. + LoadBalanceHostsRandom = LoadBalanceHosts("random") +) + +var loadBalanceHosts = []LoadBalanceHosts{LoadBalanceHostsDisable, LoadBalanceHostsRandom} + +// Values for [ProtocolVersion] that pq supports. +const ( + // ProtocolVersion30 is the default protocol version, supported in + // PostgreSQL 3.0 and newer. + ProtocolVersion30 = ProtocolVersion("3.0") + + // ProtocolVersion32 uses a longer secret key length for query cancellation, + // supported in PostgreSQL 18 and newer. + ProtocolVersion32 = ProtocolVersion("3.2") + + // ProtocolVersionLatest is the latest protocol version that pq supports + // (which may not be supported by the server). + ProtocolVersionLatest = ProtocolVersion("latest") +) + +var protocolVersions = []ProtocolVersion{ProtocolVersion30, ProtocolVersion32, ProtocolVersionLatest} + +// Values for [SSLProtocolVersion] that pq supports. +const ( + SSLProtocolVersionTLS10 = SSLProtocolVersion("TLSv1.0") + SSLProtocolVersionTLS11 = SSLProtocolVersion("TLSv1.1") + SSLProtocolVersionTLS12 = SSLProtocolVersion("TLSv1.2") + SSLProtocolVersionTLS13 = SSLProtocolVersion("TLSv1.3") +) + +var sslProtocolVersions = []SSLProtocolVersion{SSLProtocolVersionTLS10, SSLProtocolVersionTLS11, + SSLProtocolVersionTLS12, SSLProtocolVersionTLS13} + +func (s SSLProtocolVersion) tlsconf() uint16 { + switch s { + case SSLProtocolVersionTLS10: + return tls.VersionTLS10 + case SSLProtocolVersionTLS11: + return tls.VersionTLS11 + case SSLProtocolVersionTLS12: + return tls.VersionTLS12 + case SSLProtocolVersionTLS13: + return tls.VersionTLS13 + default: + return 0 + } +} + +// Connector represents a fixed configuration for the pq driver with a given +// dsn. Connector satisfies the [database/sql/driver.Connector] interface and +// can be used to create any number of DB Conn's via [sql.OpenDB]. +type Connector struct { + cfg Config + dialer Dialer +} + +// NewConnector returns a connector for the pq driver in a fixed configuration +// with the given dsn. The returned connector can be used to create any number +// of equivalent Conn's. The returned connector is intended to be used with +// [sql.OpenDB]. +func NewConnector(dsn string) (*Connector, error) { + cfg, err := NewConfig(dsn) + if err != nil { + return nil, err + } + return NewConnectorConfig(cfg) +} + +// NewConnectorConfig returns a connector for the pq driver in a fixed +// configuration with the given [Config]. The returned connector can be used to +// create any number of equivalent Conn's. The returned connector is intended to +// be used with [sql.OpenDB]. +func NewConnectorConfig(cfg Config) (*Connector, error) { + return &Connector{cfg: cfg, dialer: defaultDialer{}}, nil +} + +// Connect returns a connection to the database using the fixed configuration of +// this Connector. Context is not used. +func (c *Connector) Connect(ctx context.Context) (driver.Conn, error) { return c.open(ctx) } + +// Dialer allows change the dialer used to open connections. +func (c *Connector) Dialer(dialer Dialer) { c.dialer = dialer } + +// Driver returns the underlying driver of this Connector. +func (c *Connector) Driver() driver.Driver { return &Driver{} } + +func (p ProtocolVersion) proto() int { + switch p { + default: + return proto.ProtocolVersion30 + case ProtocolVersion32, ProtocolVersionLatest: + return proto.ProtocolVersion32 + } +} + +// Config holds options pq supports when connecting to PostgreSQL. +// +// The postgres struct tag is used for the value from the DSN (e.g. +// "dbname=abc"), and the env struct tag is used for the environment variable +// (e.g. "PGDATABASE=abc") +type Config struct { + // The host to connect to. Absolute paths and values that start with @ are + // for unix domain sockets. Defaults to localhost. + // + // A comma-separated list of host names is also accepted, in which case each + // host name in the list is tried in order or randomly if load_balance_hosts + // is set. An empty item selects the default of localhost. The + // target_session_attrs option controls properties the host must have to be + // considered acceptable. + Host string `postgres:"host" env:"PGHOST"` + + // IPv4 or IPv6 address to connect to. Using hostaddr allows the application + // to avoid a host name lookup, which might be important in applications + // with time constraints. A hostname is required for sslmode=verify-full and + // the GSSAPI or SSPI authentication methods. + // + // The following rules are used: + // + // - If host is given without hostaddr, a host name lookup occurs. + // + // - If hostaddr is given without host, the value for hostaddr gives the + // server network address. The connection attempt will fail if the + // authentication method requires a host name. + // + // - If both host and hostaddr are given, the value for hostaddr gives the + // server network address. The value for host is ignored unless the + // authentication method requires it, in which case it will be used as the + // host name. + // + // A comma-separated list of hostaddr values is also accepted, in which case + // each host in the list is tried in order or randonly if load_balance_hosts + // is set. An empty item causes the corresponding host name to be used, or + // the default host name if that is empty as well. The target_session_attrs + // option controls properties the host must have to be considered + // acceptable. + Hostaddr netip.Addr `postgres:"hostaddr" env:"PGHOSTADDR"` + + // The port to connect to. Defaults to 5432. + // + // If multiple hosts were given in the host or hostaddr parameters, this + // parameter may specify a comma-separated list of ports of the same length + // as the host list, or it may specify a single port number to be used for + // all hosts. An empty string, or an empty item in a comma-separated list, + // specifies the default of 5432. + Port uint16 `postgres:"port" env:"PGPORT"` + + // The name of the database to connect to. + Database string `postgres:"dbname" env:"PGDATABASE"` + + // The user to sign in as. Defaults to the current user. + User string `postgres:"user" env:"PGUSER"` + + // The user's password. + Password string `postgres:"password" env:"PGPASSWORD"` + + // Path to [pgpass] file to store passwords; overrides Password. + // + // [pgpass]: http://www.postgresql.org/docs/current/static/libpq-pgpass.html + Passfile string `postgres:"passfile" env:"PGPASSFILE"` + + // Commandline options to send to the server at connection start. + Options string `postgres:"options" env:"PGOPTIONS"` + + // Application name, displayed in pg_stat_activity and log entries. + ApplicationName string `postgres:"application_name" env:"PGAPPNAME"` + + // Used if application_name is not given. Specifying a fallback name is + // useful in generic utility programs that wish to set a default application + // name but allow it to be overridden by the user. + FallbackApplicationName string `postgres:"fallback_application_name" env:"-"` + + // Whether to use SSL. Defaults to "require" (different from libpq's default + // of "prefer"). + // + // [RegisterTLSConfig] can be used to registers a custom [tls.Config], which + // can be used by setting sslmode=pqgo-«key» in the connection string. + SSLMode SSLMode `postgres:"sslmode" env:"PGSSLMODE"` + + // When set to "direct" it will use SSL without negotiation (PostgreSQL ≥17 only). + SSLNegotiation SSLNegotiation `postgres:"sslnegotiation" env:"PGSSLNEGOTIATION"` + + // Path to client SSL certificate. The file must contain PEM encoded data. + // + // Defaults to ~/.postgresql/postgresql.crt + SSLCert string `postgres:"sslcert" env:"PGSSLCERT"` + + // Path to secret key for sslcert. The file must contain PEM encoded data. + // + // Defaults to ~/.postgresql/postgresql.key + SSLKey string `postgres:"sslkey" env:"PGSSLKEY"` + + // Path to root certificate. The file must contain PEM encoded data. + // + // The special value "system" can be used to load the system's root + // certificates ([x509.SystemCertPool]). This will change the default + // sslmode to verify-full and issue an error if a lower setting is used – as + // anyone can register a valid certificate hostname verification becomes + // essential. + // + // Defaults to ~/.postgresql/root.crt. + SSLRootCert string `postgres:"sslrootcert" env:"PGSSLROOTCERT"` + + // By default SNI is on, any value which is not starting with "1" disables + // SNI. + SSLSNI bool `postgres:"sslsni" env:"PGSSLSNI"` + + // Minimum SSL/TLS protocol version to allow for the connection. + // + // The default is determined by [tls.Config.MinVersion], which is TLSv1.2 at + // the time of writing. + SSLMinProtocolVersion SSLProtocolVersion `postgres:"ssl_min_protocol_version" env:"SSLPGMINPROTOCOLVERSION"` + + // Maximum SSL/TLS protocol version to allow for the connection. If not set, + // this parameter is ignored and the connection will use the maximum bound + // defined by the backend, if set. Setting the maximum protocol version is + // mainly useful for testing or if some component has issues working with a + // newer protocol. + SSLMaxProtocolVersion SSLProtocolVersion `postgres:"ssl_max_protocol_version" env:"SSLPGMAXPROTOCOLVERSION"` + + // Interpert sslcert and sslkey as PEM encoded data, rather than a path to a + // PEM file. This is a pq extension, not supported in libpq. + SSLInline bool `postgres:"sslinline" env:"-"` + + // GSS (Kerberos) service name when constructing the SPN (default is + // postgres). This will be combined with the host to form the full SPN: + // krbsrvname/host. + KrbSrvname string `postgres:"krbsrvname" env:"PGKRBSRVNAME"` + + // GSS (Kerberos) SPN. This takes priority over krbsrvname if present. This + // is a pq extension, not supported in libpq. + KrbSpn string `postgres:"krbspn" env:"-"` + + // Maximum time to wait while connecting, in seconds. Zero, negative, or not + // specified means wait indefinitely + ConnectTimeout time.Duration `postgres:"connect_timeout" env:"PGCONNECT_TIMEOUT"` + + // Whether to always send []byte parameters over as binary. Enables single + // round-trip mode for non-prepared Query calls. This is a pq extension, not + // supported in libpq. + BinaryParameters bool `postgres:"binary_parameters" env:"-"` + + // This connection should never use the binary format when receiving query + // results from prepared statements. Only provided for debugging. This is a + // pq extension, not supported in libpq. + DisablePreparedBinaryResult bool `postgres:"disable_prepared_binary_result" env:"-"` + + // Client encoding; pq only supports UTF8 and this must be blank or "UTF8". + ClientEncoding string `postgres:"client_encoding" env:"PGCLIENTENCODING"` + + // Date/time representation to use; pq only supports "ISO, MDY" and this + // must be blank or "ISO, MDY". + Datestyle string `postgres:"datestyle" env:"PGDATESTYLE"` + + // Default time zone. + TZ string `postgres:"tz" env:"PGTZ"` + + // Default mode for the genetic query optimizer. + Geqo string `postgres:"geqo" env:"PGGEQO"` + + // Determine whether the session must have certain properties to be + // acceptable. It's typically used in combination with multiple host names + // to select the first acceptable alternative among several hosts. + TargetSessionAttrs TargetSessionAttrs `postgres:"target_session_attrs" env:"PGTARGETSESSIONATTRS"` + + // Controls the order in which the client tries to connect to the available + // hosts. Once a connection attempt is successful no other hosts will be + // tried. This parameter is typically used in combination with multiple host + // names. + // + // This parameter can be used in combination with target_session_attrs to, + // for example, load balance over standby servers only. Once successfully + // connected, subsequent queries on the returned connection will all be sent + // to the same server. + LoadBalanceHosts LoadBalanceHosts `postgres:"load_balance_hosts" env:"PGLOADBALANCEHOSTS"` + + // Minimum acceptable PostgreSQL protocol version. If the server does not + // support at least this version, the connection will fail. Defaults to + // "3.0". + MinProtocolVersion ProtocolVersion `postgres:"min_protocol_version" env:"PGMINPROTOCOLVERSION"` + + // Maximum PostgreSQL protocol version to request from the server. Defaults to "3.0". + MaxProtocolVersion ProtocolVersion `postgres:"max_protocol_version" env:"PGMAXPROTOCOLVERSION"` + + // Load connection parameters from the service file at ~/.pg_service.conf + // (which can be configured with PGSERVICEFILE). + // + // The service file is a INI-like file to configure connection parameters: + // + // [servicename] + // # Comment + // dbname=foo + // + // Unlike libpq, this does not look at the system-wide service file, as the + // location of this is a compile-time value that is not easy for pq to + // retrieve. + Service string `postgres:"service" env:"PGSERVICE"` + + // Path to connection service file. Defaults to ~/.pg_service.conf. + ServiceFile string `postgres:"-" env:"PGSERVICEFILE"` + + // Runtime parameters: any unrecognized parameter in the DSN will be added + // to this and sent to PostgreSQL during startup. + Runtime map[string]string `postgres:"-" env:"-"` + + // Multi contains additional connection details. The first value is + // available in [Config.Host], [Config.Hostaddr], and [Config.Port], and + // additional ones (if any) are available here. + Multi []ConfigMultihost + + // Record which parameters were given, so we can distinguish between an + // empty string "not given at all". + // + // The alternative is to use pointers or sql.Null[..], but that's more + // awkward to use. + set []string `env:"set"` + + multiHost []string + multiHostaddr []netip.Addr + multiPort []uint16 +} + +// ConfigMultihost specifies an additional server to try to connect to. +type ConfigMultihost struct { + Host string + Hostaddr netip.Addr + Port uint16 +} + +// NewConfig creates a new [Config] from the defaults, environment, service +// file, and DSN, in that order. That is: a service overrides any value from the +// environment, which in turn gets overridden by the same parameter in the +// connection string. +// +// Most connection parameters supported by PostgreSQL are supported; see the +// [Config] struct for supported parameters. pq also lets you specify any +// [run-time parameter] such as search_path or work_mem in the connection +// string. This is different from libpq, which uses the "options" parameter for +// this (which also works in pq). +// +// # key=value connection strings +// +// For key=value strings, use single quotes for values that contain whitespace +// or empty values. A backslash will escape the next character: +// +// "user=pqgo password='with spaces'" +// "user=''" +// "user=space\ man password='it\'s valid'" +// +// # URL connection strings +// +// pq supports URL-style postgres:// or postgresql:// connection strings in the +// form: +// +// postgres[ql]://[user[:pwd]@][net-location][:port][/dbname][?param1=value1&...] +// +// Go's [net/url.Parse] is more strict than PostgreSQL's URL parser and will +// (correctly) reject %2F in the host part. This means that unix-socket URLs: +// +// postgres://[user[:pwd]@][unix-socket][:port[/dbname]][?param1=value1&...] +// postgres://%2Ftmp%2Fpostgres/db +// +// will not work. You will need to use "host=/tmp/postgres dbname=db". +// +// Similarly, multiple ports also won't work, but ?port= will: +// +// postgres://host1,host2:5432,6543/dbname Doesn't work +// postgres://host1,host2/dbname?port=5432,6543 Works +// +// # Environment +// +// Most [PostgreSQL environment variables] are supported by pq. Environment +// variables have a lower precedence than explicitly provided connection +// parameters. pq will return an error if environment variables it does not +// support are set. Environment variables have a lower precedence than +// explicitly provided connection parameters. +// +// [PostgreSQL environment variables]: http://www.postgresql.org/docs/current/static/libpq-envars.html +// [run-time parameter]: http://www.postgresql.org/docs/current/static/runtime-config.html +func NewConfig(dsn string) (Config, error) { + return newConfig(dsn, os.Environ()) +} + +// Clone returns a copy of the [Config]. +func (cfg Config) Clone() Config { + rt := make(map[string]string) + for k, v := range cfg.Runtime { + rt[k] = v + } + c := cfg + c.Runtime = rt + c.set = append([]string{}, cfg.set...) + return c +} + +// hosts returns a slice of copies of this config, one for each host. +func (cfg Config) hosts() []Config { + cfgs := make([]Config, 1, len(cfg.Multi)+1) + cfgs[0] = cfg.Clone() + for _, m := range cfg.Multi { + c := cfg.Clone() + c.Host, c.Hostaddr, c.Port = m.Host, m.Hostaddr, m.Port + cfgs = append(cfgs, c) + } + + if cfg.LoadBalanceHosts == LoadBalanceHostsRandom { + rand.Shuffle(len(cfgs), func(i, j int) { cfgs[i], cfgs[j] = cfgs[j], cfgs[i] }) + } + + return cfgs +} + +func newConfig(dsn string, env []string) (Config, error) { + cfg := Config{ + Host: "localhost", + Port: 5432, + SSLSNI: true, + MinProtocolVersion: "3.0", + MaxProtocolVersion: "3.0", + } + if err := cfg.fromEnv(env); err != nil { + return Config{}, err + } + if err := cfg.fromDSN(dsn); err != nil { + return Config{}, err + } + if err := cfg.fromService(); err != nil { + return Config{}, err + } + + // Need to have exactly the same number of host and hostaddr, or only specify one. + if cfg.isset("host") && cfg.Host != "" && cfg.Hostaddr != (netip.Addr{}) && len(cfg.multiHost) != len(cfg.multiHostaddr) { + return Config{}, fmt.Errorf("pq: could not match %d host names to %d hostaddr values", + len(cfg.multiHost)+1, len(cfg.multiHostaddr)+1) + } + // Need one port that applies to all or exactly the same number of ports as hosts. + l, ll := max(len(cfg.multiHost), len(cfg.multiHostaddr)), len(cfg.multiPort) + if l > 0 && ll > 0 && l != ll { + return Config{}, fmt.Errorf("pq: could not match %d port numbers to %d hosts", ll+1, l+1) + } + + // Populate Multi + if len(cfg.multiHostaddr) > len(cfg.multiHost) { + cfg.multiHost = make([]string, len(cfg.multiHostaddr)) + } + for i, h := range cfg.multiHost { + p := cfg.Port + if len(cfg.multiPort) > 0 { + p = cfg.multiPort[i] + } + var addr netip.Addr + if len(cfg.multiHostaddr) > 0 { + addr = cfg.multiHostaddr[i] + } + cfg.Multi = append(cfg.Multi, ConfigMultihost{ + Host: h, + Port: p, + Hostaddr: addr, + }) + } + + // Use the "fallback" application name if necessary + if cfg.isset("fallback_application_name") && !cfg.isset("application_name") { + cfg.ApplicationName = cfg.FallbackApplicationName + } + + // We can't work with any client_encoding other than UTF-8 currently. + // However, we have historically allowed the user to set it to UTF-8 + // explicitly, and there's no reason to break such programs, so allow that. + // Note that the "options" setting could also set client_encoding, but + // parsing its value is not worth it. Instead, we always explicitly send + // client_encoding as a separate run-time parameter, which should override + // anything set in options. + if cfg.isset("client_encoding") && !isUTF8(cfg.ClientEncoding) { + return Config{}, fmt.Errorf(`pq: unsupported client_encoding %q: must be absent or "UTF8"`, cfg.ClientEncoding) + } + // DateStyle needs a similar treatment. + if cfg.isset("datestyle") && cfg.Datestyle != "ISO, MDY" { + return Config{}, fmt.Errorf(`pq: unsupported datestyle %q: must be absent or "ISO, MDY"`, cfg.Datestyle) + } + cfg.ClientEncoding, cfg.Datestyle = "UTF8", "ISO, MDY" + + // Set default user if not explicitly provided. + if !cfg.isset("user") { + u, err := pqutil.User() + if err != nil { + return Config{}, err + } + cfg.User = u + } + + // SSL is not necessary or supported over UNIX domain sockets. + if nw, _ := cfg.network(); nw == "unix" { + cfg.SSLMode = SSLModeDisable + } + + if cfg.MinProtocolVersion > cfg.MaxProtocolVersion { + return Config{}, fmt.Errorf("pq: min_protocol_version %q cannot be greater than max_protocol_version %q", + cfg.MinProtocolVersion, cfg.MaxProtocolVersion) + } + if cfg.SSLNegotiation == SSLNegotiationDirect { + switch cfg.SSLMode { + case SSLModeDisable, SSLModeAllow, SSLModePrefer: + return Config{}, fmt.Errorf( + `pq: weak sslmode %q may not be used with sslnegotiation=direct (use "require", "verify-ca", or "verify-full")`, + cfg.SSLMode) + } + } + if cfg.SSLRootCert == "system" { + if !cfg.isset("sslmode") { + cfg.SSLMode = SSLModeVerifyFull + } + if cfg.SSLMode != SSLModeVerifyFull { + return Config{}, fmt.Errorf( + `pq: weak sslmode %q may not be used with sslrootcert=system (use "verify-full")`, + cfg.SSLMode) + } + } + + return cfg, nil +} + +func (cfg Config) network() (string, string) { + if cfg.Hostaddr != (netip.Addr{}) { + return "tcp", net.JoinHostPort(cfg.Hostaddr.String(), strconv.Itoa(int(cfg.Port))) + } + // UNIX domain sockets are either represented by an (absolute) file system + // path or they live in the abstract name space (starting with an @). + if filepath.IsAbs(cfg.Host) || strings.HasPrefix(cfg.Host, "@") { + sockPath := filepath.Join(cfg.Host, ".s.PGSQL."+strconv.Itoa(int(cfg.Port))) + return "unix", sockPath + } + return "tcp", net.JoinHostPort(cfg.Host, strconv.Itoa(int(cfg.Port))) +} + +func (cfg *Config) fromEnv(env []string) error { + e := make(map[string]string) + for _, v := range env { + k, v, ok := strings.Cut(v, "=") + if !ok { + continue + } + switch k { + case "PGREQUIRESSL", "PGSSLCOMPRESSION", // Deprecated. + "PGREALM", "PGGSSENCMODE", "PGGSSDELEGATION", "PGGSSLIB", // krb stuff + "PGREQUIREAUTH", "PGCHANNELBINDING", + "PGSSLCERTMODE", "PGSSLCRL", "PGSSLCRLDIR", "PGREQUIREPEER": + return fmt.Errorf("pq: environment variable $%s is not supported", k) + case "PGKRBSRVNAME": + if newGss == nil { + return fmt.Errorf("pq: environment variable $%s is not supported as Kerberos is not enabled", k) + } + } + e[k] = v + } + return cfg.setFromTag(e, "env", false) +} + +// fromDSN parses the options from name and adds them to the values. +// +// The parsing code is based on conninfo_parse from libpq's fe-connect.c +func (cfg *Config) fromDSN(dsn string) error { + if strings.HasPrefix(dsn, "postgres://") || strings.HasPrefix(dsn, "postgresql://") { + var err error + dsn, err = convertURL(dsn) + if err != nil { + return err + } + } + + var ( + opt = make(map[string]string) + s = []rune(dsn) + i int + next = func() (rune, bool) { + if i >= len(s) { + return 0, false + } + r := s[i] + i++ + return r, true + } + skipSpaces = func() (rune, bool) { + r, ok := next() + for unicode.IsSpace(r) && ok { + r, ok = next() + } + return r, ok + } + ) + + for { + var ( + keyRunes, valRunes []rune + r rune + ok bool + ) + + if r, ok = skipSpaces(); !ok { + break + } + + // Scan the key + for !unicode.IsSpace(r) && r != '=' { + keyRunes = append(keyRunes, r) + if r, ok = next(); !ok { + break + } + } + + // Skip any whitespace if we're not at the = yet + if r != '=' { + r, ok = skipSpaces() + } + + // The current character should be = + if r != '=' || !ok { + return fmt.Errorf(`missing "=" after %q in connection info string`, string(keyRunes)) + } + + // Skip any whitespace after the = + if r, ok = skipSpaces(); !ok { + // If we reach the end here, the last value is just an empty string as per libpq. + opt[string(keyRunes)] = "" + break + } + + if r != '\'' { + for !unicode.IsSpace(r) { + if r == '\\' { + if r, ok = next(); !ok { + return fmt.Errorf(`missing character after backslash`) + } + } + valRunes = append(valRunes, r) + + if r, ok = next(); !ok { + break + } + } + } else { + quote: + for { + if r, ok = next(); !ok { + return fmt.Errorf(`unterminated quoted string literal in connection string`) + } + switch r { + case '\'': + break quote + case '\\': + r, _ = next() + fallthrough + default: + valRunes = append(valRunes, r) + } + } + } + + opt[string(keyRunes)] = string(valRunes) + } + + return cfg.setFromTag(opt, "postgres", false) +} + +func (cfg *Config) fromService() error { + if cfg.Service == "" { + return nil + } + + if !cfg.isset("PGSERVICEFILE") { + if home := pqutil.Home(false); home != "" { + cfg.ServiceFile = filepath.Join(home, ".pg_service.conf") + } + } + + opts, err := pgservice.FindService(cfg.ServiceFile, cfg.Service) + if err != nil { + return fmt.Errorf("pq: %w", err) + } + return cfg.setFromTag(opts, "postgres", true) +} + +func (cfg *Config) setFromTag(o map[string]string, tag string, service bool) error { + f := "pq: wrong value for %q: " + if tag == "env" { + f = "pq: wrong value for $%s: " + } + var ( + types = reflect.TypeOf(cfg).Elem() + values = reflect.ValueOf(cfg).Elem() + ) + for i := 0; i < types.NumField(); i++ { + var ( + rt = types.Field(i) + rv = values.Field(i) + k = rt.Tag.Get(tag) + connectTimeout = (tag == "postgres" && k == "connect_timeout") || (tag == "env" && k == "PGCONNECT_TIMEOUT") + host = (tag == "postgres" && k == "host") || (tag == "env" && k == "PGHOST") + hostaddr = (tag == "postgres" && k == "hostaddr") || (tag == "env" && k == "PGHOSTADDR") + port = (tag == "postgres" && k == "port") || (tag == "env" && k == "PGPORT") + sslmode = (tag == "postgres" && k == "sslmode") || (tag == "env" && k == "PGSSLMODE") + sslnegotiation = (tag == "postgres" && k == "sslnegotiation") || (tag == "env" && k == "PGSSLNEGOTIATION") + targetsessionattrs = (tag == "postgres" && k == "target_session_attrs") || (tag == "env" && k == "PGTARGETSESSIONATTRS") + loadbalancehosts = (tag == "postgres" && k == "load_balance_hosts") || (tag == "env" && k == "PGLOADBALANCEHOSTS") + minprotocolversion = (tag == "postgres" && k == "min_protocol_version") || (tag == "env" && k == "PGMINPROTOCOLVERSION") + maxprotocolversion = (tag == "postgres" && k == "max_protocol_version") || (tag == "env" && k == "PGMAXPROTOCOLVERSION") + sslminprotocolversion = (tag == "postgres" && k == "ssl_min_protocol_version") || (tag == "env" && k == "SSLPGMINPROTOCOLVERSION") + sslmaxprotocolversion = (tag == "postgres" && k == "ssl_max_protocol_version") || (tag == "env" && k == "SSLPGMAXPROTOCOLVERSION") + ) + if k == "" || k == "-" { + continue + } + + v, ok := o[k] + delete(o, k) + if ok { + t, ok := rt.Tag.Lookup("postgres") + if !ok || t == "" || t == "-" { // For PGSERVICEFILE, which can only be from env + t, ok = rt.Tag.Lookup("env") + } + if ok && t != "" && t != "-" { + cfg.set = append(cfg.set, t) + } + switch rt.Type.Kind() { + default: + return fmt.Errorf("don't know how to set %s: unknown type %s", rt.Name, rt.Type.Kind()) + case reflect.Struct: + if rt.Type == reflect.TypeOf(netip.Addr{}) { + if hostaddr { + vv := strings.Split(v, ",") + v = vv[0] + for _, vvv := range vv[1:] { + if vvv == "" { + cfg.multiHostaddr = append(cfg.multiHostaddr, netip.Addr{}) + } else { + ip, err := netip.ParseAddr(vvv) + if err != nil { + return fmt.Errorf(f+"%w", k, err) + } + cfg.multiHostaddr = append(cfg.multiHostaddr, ip) + } + } + } + ip, err := netip.ParseAddr(v) + if err != nil { + return fmt.Errorf(f+"%w", k, err) + } + rv.Set(reflect.ValueOf(ip)) + } else { + return fmt.Errorf("don't know how to set %s: unknown type %s", rt.Name, rt.Type) + } + case reflect.String: + if sslmode && !slices.Contains(sslModes, SSLMode(v)) && !(strings.HasPrefix(v, "pqgo-") && hasTLSConfig(v[5:])) { + return fmt.Errorf(f+`%q is not supported; supported values are %s`, k, v, pqutil.Join(sslModes)) + } + if sslnegotiation && !slices.Contains(sslNegotiations, SSLNegotiation(v)) { + return fmt.Errorf(f+`%q is not supported; supported values are %s`, k, v, pqutil.Join(sslNegotiations)) + } + if targetsessionattrs && !slices.Contains(targetSessionAttrs, TargetSessionAttrs(v)) { + return fmt.Errorf(f+`%q is not supported; supported values are %s`, k, v, pqutil.Join(targetSessionAttrs)) + } + if loadbalancehosts && !slices.Contains(loadBalanceHosts, LoadBalanceHosts(v)) { + return fmt.Errorf(f+`%q is not supported; supported values are %s`, k, v, pqutil.Join(loadBalanceHosts)) + } + if (minprotocolversion || maxprotocolversion) && !slices.Contains(protocolVersions, ProtocolVersion(v)) { + return fmt.Errorf(f+`%q is not supported; supported values are %s`, k, v, pqutil.Join(protocolVersions)) + } + if (sslminprotocolversion || sslmaxprotocolversion) && !slices.Contains(sslProtocolVersions, SSLProtocolVersion(v)) { + return fmt.Errorf(f+`%q is not supported; supported values are %s`, k, v, pqutil.Join(sslProtocolVersions)) + } + if host { + vv := strings.Split(v, ",") + v = vv[0] + for i, vvv := range vv[1:] { + if vvv == "" { + vv[i+1] = "localhost" + } + } + cfg.multiHost = append(cfg.multiHost, vv[1:]...) + } + rv.SetString(v) + case reflect.Int64: + n, err := strconv.ParseInt(v, 10, 64) + if err != nil { + return fmt.Errorf(f+"%w", k, err) + } + if connectTimeout { + n = int64(time.Duration(n) * time.Second) + } + rv.SetInt(n) + case reflect.Uint16: + if port { + vv := strings.Split(v, ",") + v = vv[0] + for _, vvv := range vv[1:] { + if vvv == "" { + vvv = "5432" + } + n, err := strconv.ParseUint(vvv, 10, 16) + if err != nil { + return fmt.Errorf(f+"%w", k, err) + } + cfg.multiPort = append(cfg.multiPort, uint16(n)) + } + } + n, err := strconv.ParseUint(v, 10, 16) + if err != nil { + return fmt.Errorf(f+"%w", k, err) + } + rv.SetUint(n) + case reflect.Bool: + b, err := pqutil.ParseBool(v) + if err != nil { + return fmt.Errorf(f+"%w", k, err) + } + rv.SetBool(b) + } + } + } + + if service && len(o) > 0 { + // TODO(go1.23): use maps.Keys once we require Go 1.23. + var key string + for k := range o { + key = k + break + } + return fmt.Errorf("pq: unknown setting %q in service file for service %q", key, cfg.Service) + } + + // Set run-time; we delete map keys as they're set in the struct. + if !service && tag == "postgres" { + // Make sure database= sets dbname=, as that previously worked (kind of + // by accident). + // TODO(v2): remove + if d, ok := o["database"]; ok { + cfg.Database = d + delete(o, "database") + } + cfg.Runtime = o + } + + return nil +} + +// Should generally only be used from newConfig(), as it will never be set if +// people go outside that. +func (cfg Config) isset(name string) bool { + return slices.Contains(cfg.set, name) +} + +// Convert to a map; used only in tests. +func (cfg Config) tomap() map[string]string { + var ( + o = make(map[string]string) + values = reflect.ValueOf(cfg) + types = reflect.TypeOf(cfg) + ) + for i := 0; i < types.NumField(); i++ { + var ( + rt = types.Field(i) + rv = values.Field(i) + k = rt.Tag.Get("postgres") + ) + if k == "" || k == "-" { + continue + } + if !rv.IsZero() || slices.Contains(cfg.set, k) { + switch rt.Type.Kind() { + default: + if s, ok := rv.Interface().(fmt.Stringer); ok { + o[k] = s.String() + } else { + o[k] = rv.String() + } + case reflect.Uint16: + n := rv.Uint() + o[k] = strconv.FormatUint(n, 10) + case reflect.Int64: + n := rv.Int() + if k == "connect_timeout" { + n = int64(time.Duration(n) / time.Second) + } + o[k] = strconv.FormatInt(n, 10) + case reflect.Bool: + if rv.Bool() { + o[k] = "yes" + } else { + o[k] = "no" + } + } + } + } + for k, v := range cfg.Runtime { + o[k] = v + } + return o +} + +// Create DSN for this config; used only in tests. +func (cfg Config) string() string { + var ( + m = cfg.tomap() + keys = make([]string, 0, len(m)) + ) + for k := range m { + switch k { + case "datestyle", "client_encoding": + continue + case "host", "port", "user", "sslsni", "min_protocol_version", "max_protocol_version": + if !cfg.isset(k) { + continue + } + } + if k == "application_name" && m[k] == "pqgo" { + continue + } + if k == "host" && len(cfg.multiHost) > 0 { + m[k] += "," + strings.Join(cfg.multiHost, ",") + } + if k == "hostaddr" && len(cfg.multiHostaddr) > 0 { + for _, ha := range cfg.multiHostaddr { + m[k] += "," + if ha != (netip.Addr{}) { + m[k] += ha.String() + } + } + } + if k == "port" && len(cfg.multiPort) > 0 { + for _, p := range cfg.multiPort { + m[k] += "," + strconv.Itoa(int(p)) + } + } + keys = append(keys, k) + } + sort.Strings(keys) + + var b strings.Builder + for i, k := range keys { + if i > 0 { + b.WriteByte(' ') + } + b.WriteString(k) + b.WriteByte('=') + var ( + v = m[k] + nv = make([]rune, 0, len(v)+2) + quote = v == "" + ) + for _, c := range v { + if c == ' ' { + quote = true + } + if c == '\'' { + nv = append(nv, '\\') + } + nv = append(nv, c) + } + if quote { + b.WriteByte('\'') + } + b.WriteString(string(nv)) + if quote { + b.WriteByte('\'') + } + } + return b.String() +} + +// Recognize all sorts of silly things as "UTF-8", like Postgres does +func isUTF8(name string) bool { + s := strings.Map(func(c rune) rune { + if 'A' <= c && c <= 'Z' { + return c + ('a' - 'A') + } + if 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { + return c + } + return -1 // discard + }, name) + return s == "utf8" || s == "unicode" +} + +func convertURL(url string) (string, error) { + u, err := neturl.Parse(url) + if err != nil { + return "", err + } + + if u.Scheme != "postgres" && u.Scheme != "postgresql" { + return "", fmt.Errorf("invalid connection protocol: %s", u.Scheme) + } + + var kvs []string + escaper := strings.NewReplacer(`'`, `\'`, `\`, `\\`) + accrue := func(k, v string) { + if v != "" { + kvs = append(kvs, k+"='"+escaper.Replace(v)+"'") + } + } + + if u.User != nil { + pw, _ := u.User.Password() + accrue("user", u.User.Username()) + accrue("password", pw) + } + + if host, port, err := net.SplitHostPort(u.Host); err != nil { + accrue("host", u.Host) + } else { + accrue("host", host) + accrue("port", port) + } + + if u.Path != "" { + accrue("dbname", u.Path[1:]) + } + + q := u.Query() + for k := range q { + accrue(k, q.Get(k)) + } + + sort.Strings(kvs) // Makes testing easier (not a performance concern) + return strings.Join(kvs, " "), nil +} diff --git a/vendor/github.com/lib/pq/copy.go b/vendor/github.com/lib/pq/copy.go new file mode 100644 index 0000000..a7c73e0 --- /dev/null +++ b/vendor/github.com/lib/pq/copy.go @@ -0,0 +1,339 @@ +package pq + +import ( + "context" + "database/sql/driver" + "encoding/binary" + "errors" + "fmt" + "os" + "sync" + + "github.com/lib/pq/internal/proto" +) + +var ( + errCopyInClosed = errors.New("pq: copyin statement has already been closed") + errBinaryCopyNotSupported = errors.New("pq: only text format supported for COPY") + errCopyToNotSupported = errors.New("pq: COPY TO is not supported") + errCopyNotSupportedOutsideTxn = errors.New("pq: COPY is only allowed inside a transaction") +) + +type copyin struct { + cn *conn + buffer []byte + rowData chan []byte + done chan bool + closed bool + mu struct { + sync.Mutex + err error + driver.Result + } +} + +const ( + ciBufferSize = 64 * 1024 + // flush buffer before the buffer is filled up and needs reallocation + ciBufferFlushSize = 63 * 1024 +) + +func (cn *conn) prepareCopyIn(q string) (_ driver.Stmt, resErr error) { + if !cn.isInTransaction() { + return nil, errCopyNotSupportedOutsideTxn + } + + ci := ©in{ + cn: cn, + buffer: make([]byte, 0, ciBufferSize), + rowData: make(chan []byte), + done: make(chan bool, 1), + } + // add CopyData identifier + 4 bytes for message length + ci.buffer = append(ci.buffer, byte(proto.CopyDataRequest), 0, 0, 0, 0) + + b := cn.writeBuf(proto.Query) + b.string(q) + err := cn.send(b) + if err != nil { + return nil, err + } + +awaitCopyInResponse: + for { + t, r, err := cn.recv1() + if err != nil { + return nil, err + } + switch t { + case proto.CopyInResponse: + if r.byte() != 0 { + resErr = errBinaryCopyNotSupported + break awaitCopyInResponse + } + go ci.resploop() + return ci, nil + case proto.CopyOutResponse: + resErr = errCopyToNotSupported + break awaitCopyInResponse + case proto.ErrorResponse: + resErr = parseError(r, q) + case proto.ReadyForQuery: + if resErr == nil { + ci.setBad(driver.ErrBadConn) + return nil, fmt.Errorf("pq: unexpected ReadyForQuery in response to COPY") + } + cn.processReadyForQuery(r) + return nil, resErr + default: + ci.setBad(driver.ErrBadConn) + return nil, fmt.Errorf("pq: unknown response for copy query: %q", t) + } + } + + // something went wrong, abort COPY before we return + b = cn.writeBuf(proto.CopyFail) + b.string(resErr.Error()) + err = cn.send(b) + if err != nil { + return nil, err + } + + for { + t, r, err := cn.recv1() + if err != nil { + return nil, err + } + + switch t { + case proto.CopyDoneResponse, proto.CommandComplete, proto.ErrorResponse: + case proto.ReadyForQuery: + // correctly aborted, we're done + cn.processReadyForQuery(r) + return nil, resErr + default: + ci.setBad(driver.ErrBadConn) + return nil, fmt.Errorf("pq: unknown response for CopyFail: %q", t) + } + } +} + +func (ci *copyin) flush(buf []byte) error { + if len(buf)-1 > proto.MaxUint32 { + return errors.New("pq: too many columns") + } + if debugProto { + fmt.Fprintf(os.Stderr, "CLIENT → %-20s %5d %q\n", proto.RequestCode(buf[0]), len(buf)-5, buf[5:]) + } + binary.BigEndian.PutUint32(buf[1:], uint32(len(buf)-1)) // Set message length (without message identifier). + _, err := ci.cn.c.Write(buf) + return err +} + +func (ci *copyin) resploop() { + for { + var r readBuf + t, err := ci.cn.recvMessage(&r) + if err != nil { + ci.setBad(driver.ErrBadConn) + ci.setError(err) + ci.done <- true + return + } + switch t { + case proto.CommandComplete: + // complete + res, _, err := ci.cn.parseComplete(r.string()) + if err != nil { + panic(err) + } + ci.setResult(res) + case proto.NoticeResponse: + if n := ci.cn.noticeHandler; n != nil { + n(parseError(&r, "")) + } + case proto.ReadyForQuery: + ci.cn.processReadyForQuery(&r) + ci.done <- true + return + case proto.ErrorResponse: + err := parseError(&r, "") + ci.setError(err) + default: + ci.setBad(driver.ErrBadConn) + ci.setError(fmt.Errorf("unknown response during CopyIn: %q", t)) + ci.done <- true + return + } + } +} + +func (ci *copyin) setBad(err error) { + ci.cn.err.set(err) +} + +func (ci *copyin) getBad() error { + return ci.cn.err.get() +} + +func (ci *copyin) err() error { + ci.mu.Lock() + err := ci.mu.err + ci.mu.Unlock() + return err +} + +// setError() sets ci.err if one has not been set already. Caller must not be +// holding ci.Mutex. +func (ci *copyin) setError(err error) { + ci.mu.Lock() + if ci.mu.err == nil { + ci.mu.err = err + } + ci.mu.Unlock() +} + +func (ci *copyin) setResult(result driver.Result) { + ci.mu.Lock() + ci.mu.Result = result + ci.mu.Unlock() +} + +func (ci *copyin) getResult() driver.Result { + ci.mu.Lock() + result := ci.mu.Result + ci.mu.Unlock() + if result == nil { + return driver.RowsAffected(0) + } + return result +} + +func (ci *copyin) NumInput() int { + return -1 +} + +func (ci *copyin) Query(v []driver.Value) (r driver.Rows, err error) { + return nil, ErrNotSupported +} + +// Exec inserts values into the COPY stream. The insert is asynchronous +// and Exec can return errors from previous Exec calls to the same +// COPY stmt. +// +// You need to call Exec(nil) to sync the COPY stream and to get any +// errors from pending data, since Stmt.Close() doesn't return errors +// to the user. +func (ci *copyin) Exec(v []driver.Value) (driver.Result, error) { + if ci.closed { + return nil, errCopyInClosed + } + if err := ci.getBad(); err != nil { + return nil, err + } + if err := ci.err(); err != nil { + return nil, err + } + + if len(v) == 0 { + if err := ci.Close(); err != nil { + return driver.RowsAffected(0), err + } + return ci.getResult(), nil + } + + var ( + numValues = len(v) + err error + ) + for i, value := range v { + ci.buffer, err = appendEncodedText(ci.buffer, value) + if err != nil { + return nil, ci.cn.handleError(err) + } + if i < numValues-1 { + ci.buffer = append(ci.buffer, '\t') + } + } + + ci.buffer = append(ci.buffer, '\n') + + if len(ci.buffer) > ciBufferFlushSize { + err := ci.flush(ci.buffer) + if err != nil { + return nil, ci.cn.handleError(err) + } + // reset buffer, keep bytes for message identifier and length + ci.buffer = ci.buffer[:5] + } + + return driver.RowsAffected(0), nil +} + +// CopyData inserts a raw string into the COPY stream. The insert is +// asynchronous and CopyData can return errors from previous CopyData calls to +// the same COPY stmt. +// +// You need to call Exec(nil) to sync the COPY stream and to get any +// errors from pending data, since Stmt.Close() doesn't return errors +// to the user. +func (ci *copyin) CopyData(ctx context.Context, line string) (driver.Result, error) { + if ci.closed { + return nil, errCopyInClosed + } + if finish := ci.cn.watchCancel(ctx); finish != nil { + defer finish() + } + if err := ci.getBad(); err != nil { + return nil, err + } + if err := ci.err(); err != nil { + return nil, err + } + + ci.buffer = append(ci.buffer, []byte(line)...) + ci.buffer = append(ci.buffer, '\n') + + if len(ci.buffer) > ciBufferFlushSize { + err := ci.flush(ci.buffer) + if err != nil { + return nil, ci.cn.handleError(err) + } + + // reset buffer, keep bytes for message identifier and length + ci.buffer = ci.buffer[:5] + } + + return driver.RowsAffected(0), nil +} + +func (ci *copyin) Close() error { + if ci.closed { // Don't do anything, we're already closed + return nil + } + ci.closed = true + + if err := ci.getBad(); err != nil { + return err + } + + if len(ci.buffer) > 0 { + err := ci.flush(ci.buffer) + if err != nil { + return ci.cn.handleError(err) + } + } + // Avoid touching the scratch buffer as resploop could be using it. + err := ci.cn.sendSimpleMessage(proto.CopyDoneRequest) + if err != nil { + return ci.cn.handleError(err) + } + + <-ci.done + ci.cn.inProgress.Store(false) + + if err := ci.err(); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/lib/pq/deprecated.go b/vendor/github.com/lib/pq/deprecated.go new file mode 100644 index 0000000..d43934a --- /dev/null +++ b/vendor/github.com/lib/pq/deprecated.go @@ -0,0 +1,133 @@ +package pq + +import ( + "bytes" + "database/sql" + + "github.com/lib/pq/pqerror" +) + +// [pq.Error.Severity] values. +// +// Deprecated: use pqerror.Severity[..] values. +// +//go:fix inline +const ( + Efatal = pqerror.SeverityFatal + Epanic = pqerror.SeverityPanic + Ewarning = pqerror.SeverityWarning + Enotice = pqerror.SeverityNotice + Edebug = pqerror.SeverityDebug + Einfo = pqerror.SeverityInfo + Elog = pqerror.SeverityLog +) + +// PGError is an interface used by previous versions of pq. +// +// Deprecated: use the Error type. This is never used. +type PGError interface { + Error() string + Fatal() bool + Get(k byte) (v string) +} + +// Get implements the legacy PGError interface. +// +// Deprecated: new code should use the fields of the Error struct directly. +func (e *Error) Get(k byte) (v string) { + switch k { + case 'S': + return e.Severity + case 'C': + return string(e.Code) + case 'M': + return e.Message + case 'D': + return e.Detail + case 'H': + return e.Hint + case 'P': + return e.Position + case 'p': + return e.InternalPosition + case 'q': + return e.InternalQuery + case 'W': + return e.Where + case 's': + return e.Schema + case 't': + return e.Table + case 'c': + return e.Column + case 'd': + return e.DataTypeName + case 'n': + return e.Constraint + case 'F': + return e.File + case 'L': + return e.Line + case 'R': + return e.Routine + } + return "" +} + +// ParseURL converts a url to a connection string for driver.Open. +// +// Deprecated: directly passing an URL to sql.Open("postgres", "postgres://...") +// now works, and calling this manually is no longer required. +func ParseURL(url string) (string, error) { return convertURL(url) } + +// NullTime represents a [time.Time] that may be null. +// +// Deprecated: this is an alias for [sql.NullTime]. +// +//go:fix inline +type NullTime = sql.NullTime + +// CopyIn creates a COPY FROM statement which can be prepared with Tx.Prepare(). +// The target table should be visible in search_path. +// +// It copies all columns if the list of columns is empty. +// +// Deprecated: there is no need to use this query builder, you can use: +// +// tx.Prepare("copy tbl (col1, col2) from stdin") +func CopyIn(table string, columns ...string) string { + b := bytes.NewBufferString("COPY ") + BufferQuoteIdentifier(table, b) + makeStmt(b, columns...) + return b.String() +} + +// CopyInSchema creates a COPY FROM statement which can be prepared with +// Tx.Prepare(). +// +// Deprecated: there is no need to use this query builder, you can use: +// +// tx.Prepare("copy schema.tbl (col1, col2) from stdin") +func CopyInSchema(schema, table string, columns ...string) string { + b := bytes.NewBufferString("COPY ") + BufferQuoteIdentifier(schema, b) + b.WriteRune('.') + BufferQuoteIdentifier(table, b) + makeStmt(b, columns...) + return b.String() +} + +func makeStmt(b *bytes.Buffer, columns ...string) { + if len(columns) == 0 { + b.WriteString(" FROM STDIN") + return + } + b.WriteString(" (") + for i, col := range columns { + if i != 0 { + b.WriteString(", ") + } + BufferQuoteIdentifier(col, b) + } + b.WriteString(") FROM STDIN") +} diff --git a/vendor/github.com/lib/pq/doc.go b/vendor/github.com/lib/pq/doc.go new file mode 100644 index 0000000..9d9d78e --- /dev/null +++ b/vendor/github.com/lib/pq/doc.go @@ -0,0 +1,137 @@ +/* +Package pq is a Go PostgreSQL driver for database/sql. + +Most clients will use the database/sql package instead of using this package +directly. For example: + + import ( + "database/sql" + + _ "github.com/lib/pq" + ) + + func main() { + dsn := "user=pqgo dbname=pqgo sslmode=verify-full" + db, err := sql.Open("postgres", dsn) + if err != nil { + log.Fatal(err) + } + + age := 21 + rows, err := db.Query("select name from users where age = $1", age) + // … + } + +You can also connect with an URL: + + dsn := "postgres://pqgo:password@localhost/pqgo?sslmode=verify-full" + db, err := sql.Open("postgres", dsn) + +# Connection String Parameters + +See [NewConfig]. + +# Queries + +database/sql does not dictate any specific format for parameter placeholders, +and pq uses the PostgreSQL-native ordinal markers ($1, $2, etc.). The same +placeholder can be used more than once: + + rows, err := db.Query( + `select * from users where name = $1 or age between $2 and $2 + 3`, + "Duck", 64) + +pq does not support [sql.Result.LastInsertId]. Use the RETURNING clause with a +Query or QueryRow call instead to return the identifier: + + row := db.QueryRow(`insert into users(name, age) values('Scrooge McDuck', 93) returning id`) + + var userid int + err := row.Scan(&userid) + +# Data Types + +Parameters pass through [driver.DefaultParameterConverter] before they are handled +by this package. When the binary_parameters connection option is enabled, []byte +values are sent directly to the backend as data in binary format. + +This package returns the following types for values from the PostgreSQL backend: + + - integer types smallint, integer, and bigint are returned as int64 + - floating-point types real and double precision are returned as float64 + - character types char, varchar, and text are returned as string + - temporal types date, time, timetz, timestamp, and timestamptz are + returned as time.Time + - the boolean type is returned as bool + - the bytea type is returned as []byte + +All other types are returned directly from the backend as []byte values in text format. + +# Errors + +pq may return errors of type [*pq.Error] which contain error details: + + pqErr := new(pq.Error) + if errors.As(err, &pqErr) { + fmt.Println("pq error:", pqErr.Code.Name()) + } + +# Bulk imports + +You can perform bulk imports by preparing a "COPY [..] FROM STDIN" statement in +a transaction ([sql.Tx]). The returned [sql.Stmt] handle can then be repeatedly +"executed" to copy data into the target table. After all data has been processed +you should call Exec() once with no arguments to flush all buffered data. Any +call to Exec() might return an error which should be handled appropriately, but +because of the internal buffering an error returned by Exec() might not be +related to the data passed in the call that failed. + +It is not possible to COPY outside of an explicit transaction in pq. + +Use nil for NULL, or explicitly add WITH NULL 'SOME STRING' (the default of \N +doesn't work). + +# Notifications + +PostgreSQL supports a simple publish/subscribe model using PostgreSQL's [NOTIFY] mechanism. + +To start listening for notifications, you first have to open a new connection to +the database by calling [NewListener]. This connection can not be used for +anything other than LISTEN / NOTIFY. Calling Listen will open a "notification +channel"; once a notification channel is open, a notification generated on that +channel will effect a send on the Listener.Notify channel. A notification +channel will remain open until Unlisten is called, though connection loss might +result in some notifications being lost. To solve this problem, Listener sends a +nil pointer over the Notify channel any time the connection is re-established +following a connection loss. The application can get information about the state +of the underlying connection by setting an event callback in the call to +NewListener. + +A single [Listener] can safely be used from concurrent goroutines, which means +that there is often no need to create more than one Listener in your +application. However, a Listener is always connected to a single database, so +you will need to create a new Listener instance for every database you want to +receive notifications in. + +The channel name in both Listen and Unlisten is case sensitive, and can contain +any characters legal in an [identifier]. Note that the channel name will be +truncated to 63 bytes by the PostgreSQL server. + +# Kerberos Support + +If you need support for Kerberos authentication, add the following to your main +package: + + import "github.com/lib/pq/auth/kerberos" + + func init() { + pq.RegisterGSSProvider(func() (pq.Gss, error) { return kerberos.NewGSS() }) + } + +This package is in a separate module so that users who don't need Kerberos don't +have to add unnecessary dependencies. + +[identifier]: http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS +[NOTIFY]: http://www.postgresql.org/docs/current/static/sql-notify.html +*/ +package pq diff --git a/vendor/github.com/lib/pq/encode.go b/vendor/github.com/lib/pq/encode.go new file mode 100644 index 0000000..f9b6505 --- /dev/null +++ b/vendor/github.com/lib/pq/encode.go @@ -0,0 +1,400 @@ +package pq + +import ( + "bytes" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/lib/pq/internal/pqtime" + "github.com/lib/pq/oid" +) + +func binaryEncode(x any) ([]byte, error) { + switch v := x.(type) { + case []byte: + return v, nil + default: + return encode(x, oid.T_unknown) + } +} + +func encode(x any, pgtypOid oid.Oid) ([]byte, error) { + switch v := x.(type) { + case int64: + return strconv.AppendInt(nil, v, 10), nil + case float64: + return strconv.AppendFloat(nil, v, 'f', -1, 64), nil + case []byte: + if v == nil { + return nil, nil + } + if pgtypOid == oid.T_bytea { + return encodeBytea(v), nil + } + return v, nil + case string: + if pgtypOid == oid.T_bytea { + return encodeBytea([]byte(v)), nil + } + return []byte(v), nil + case bool: + return strconv.AppendBool(nil, v), nil + case time.Time: + return formatTS(v), nil + default: + return nil, fmt.Errorf("pq: encode: unknown type for %T", v) + } +} + +func decode(ps *parameterStatus, s []byte, typ oid.Oid, f format) (any, error) { + switch f { + case formatBinary: + return binaryDecode(s, typ) + case formatText: + return textDecode(ps, s, typ) + default: + panic("unreachable") + } +} + +func binaryDecode(s []byte, typ oid.Oid) (any, error) { + switch typ { + case oid.T_bytea: + return s, nil + case oid.T_int8: + return int64(binary.BigEndian.Uint64(s)), nil + case oid.T_int4: + return int64(int32(binary.BigEndian.Uint32(s))), nil + case oid.T_int2: + return int64(int16(binary.BigEndian.Uint16(s))), nil + case oid.T_uuid: + return decodeUUIDBinary(s) + default: + return nil, fmt.Errorf("pq: don't know how to decode binary parameter of type %d", uint32(typ)) + } + +} + +// decodeUUIDBinary interprets the binary format of a uuid, returning it in text format. +func decodeUUIDBinary(src []byte) ([]byte, error) { + if len(src) != 16 { + return nil, fmt.Errorf("pq: unable to decode uuid; bad length: %d", len(src)) + } + + dst := make([]byte, 36) + dst[8], dst[13], dst[18], dst[23] = '-', '-', '-', '-' + hex.Encode(dst[0:], src[0:4]) + hex.Encode(dst[9:], src[4:6]) + hex.Encode(dst[14:], src[6:8]) + hex.Encode(dst[19:], src[8:10]) + hex.Encode(dst[24:], src[10:16]) + return dst, nil +} + +func textDecode(ps *parameterStatus, s []byte, typ oid.Oid) (any, error) { + switch typ { + case oid.T_char, oid.T_bpchar, oid.T_varchar, oid.T_text: + return string(s), nil + case oid.T_bytea: + b, err := parseBytea(s) + if err != nil { + err = errors.New("pq: " + err.Error()) + } + return b, err + case oid.T_timestamptz: + return parseTS(ps.currentLocation, string(s)) + case oid.T_timestamp, oid.T_date: + return parseTS(nil, string(s)) + case oid.T_time: + return parseTime(typ, s) + case oid.T_timetz: + return parseTime(typ, s) + case oid.T_bool: + return s[0] == 't', nil + case oid.T_int8, oid.T_int4, oid.T_int2: + i, err := strconv.ParseInt(string(s), 10, 64) + if err != nil { + err = errors.New("pq: " + err.Error()) + } + return i, err + case oid.T_float4, oid.T_float8: + // We always use 64 bit parsing, regardless of whether the input text is for + // a float4 or float8, because clients expect float64s for all float datatypes + // and returning a 32-bit parsed float64 produces lossy results. + f, err := strconv.ParseFloat(string(s), 64) + if err != nil { + err = errors.New("pq: " + err.Error()) + } + return f, err + } + return s, nil +} + +// appendEncodedText encodes item in text format as required by COPY +// and appends to buf +func appendEncodedText(buf []byte, x any) ([]byte, error) { + switch v := x.(type) { + case int64: + return strconv.AppendInt(buf, v, 10), nil + case float64: + return strconv.AppendFloat(buf, v, 'f', -1, 64), nil + case []byte: + encodedBytea := encodeBytea(v) + return appendEscapedText(buf, string(encodedBytea)), nil + case string: + return appendEscapedText(buf, v), nil + case bool: + return strconv.AppendBool(buf, v), nil + case time.Time: + return append(buf, formatTS(v)...), nil + case nil: + return append(buf, `\N`...), nil + default: + return nil, fmt.Errorf("pq: encode: unknown type for %T", v) + } +} + +func appendEscapedText(buf []byte, text string) []byte { + escapeNeeded := false + startPos := 0 + + // check if we need to escape + for i := 0; i < len(text); i++ { + c := text[i] + if c == '\\' || c == '\n' || c == '\r' || c == '\t' { + escapeNeeded = true + startPos = i + break + } + } + if !escapeNeeded { + return append(buf, text...) + } + + // copy till first char to escape, iterate the rest + result := append(buf, text[:startPos]...) + for i := startPos; i < len(text); i++ { + switch c := text[i]; c { + case '\\': + result = append(result, '\\', '\\') + case '\n': + result = append(result, '\\', 'n') + case '\r': + result = append(result, '\\', 'r') + case '\t': + result = append(result, '\\', 't') + default: + result = append(result, c) + } + } + return result +} + +func parseTime(typ oid.Oid, s []byte) (time.Time, error) { + str := string(s) + + f := "15:04:05" + if typ == oid.T_timetz { + f = "15:04:05-07" + // PostgreSQL just sends the hour if the minute and second is 0: + // 22:04:59+00 + // 22:04:59+08 + // 22:04:59+08:30 + // 22:04:59+08:30:40 + // 23:00:00.112321+02:12:13 + // So add those to the format string. + c := strings.Count(str, ":") + if c > 3 { + f = "15:04:05-07:00:00" + } else if c > 2 { + f = "15:04:05-07:00" + } + } + + // Go doesn't parse 24:00, so manually set that to midnight on Jan 2. 24:00 + // is never with subseconds but may have a timezone: + // 24:00:00 + // 24:00:00+08 + // 24:00:00-08:01:01 + var is2400Time bool + if strings.HasPrefix(str, "24:00:00") { + is2400Time = true + if len(str) > 8 { + str = "00:00:00" + str[8:] + } else { + str = "00:00:00" + } + } + + t, err := time.Parse(f, str) + if err != nil { + return time.Time{}, errors.New("pq: " + err.Error()) + } + if is2400Time { + t = t.Add(24 * time.Hour) + } + // TODO(v2): it uses UTC, which it shouldn't. But I'm afraid changing it now + // will break people's code. + //if typ == oid.T_time { + // // Don't use UTC but time.FixedZone("", 0) + // t = t.In(globalLocationCache.getLocation(0)) + //} + return t, nil +} + +var ( + infinityTSEnabled = false + infinityTSNegative time.Time + infinityTSPositive time.Time +) + +// EnableInfinityTs controls the handling of Postgres' "-infinity" and +// "infinity" "timestamp"s. +// +// If EnableInfinityTs is not called, "-infinity" and "infinity" will return +// []byte("-infinity") and []byte("infinity") respectively, and potentially +// cause error "sql: Scan error on column index 0: unsupported driver -> Scan +// pair: []uint8 -> *time.Time", when scanning into a time.Time value. +// +// Once EnableInfinityTs has been called, all connections created using this +// driver will decode Postgres' "-infinity" and "infinity" for "timestamp", +// "timestamp with time zone" and "date" types to the predefined minimum and +// maximum times, respectively. When encoding time.Time values, any time which +// equals or precedes the predefined minimum time will be encoded to +// "-infinity". Any values at or past the maximum time will similarly be +// encoded to "infinity". +// +// If EnableInfinityTs is called with negative >= positive, it will panic. +// Calling EnableInfinityTs after a connection has been established results in +// undefined behavior. If EnableInfinityTs is called more than once, it will +// panic. +func EnableInfinityTs(negative time.Time, positive time.Time) { + if infinityTSEnabled { + panic("pq: infinity timestamp already enabled") + } + if !negative.Before(positive) { + panic("pq: infinity timestamp: negative value must be smaller (before) than positive") + } + infinityTSEnabled = true + infinityTSNegative = negative + infinityTSPositive = positive +} + +// Testing might want to toggle infinityTSEnabled +func disableInfinityTS() { + infinityTSEnabled = false +} + +// This is a time function specific to the Postgres default DateStyle setting +// ("ISO, MDY"), the only one we currently support. This accounts for the +// discrepancies between the parsing available with time.Parse and the Postgres +// date formatting quirks. +func parseTS(currentLocation *time.Location, str string) (any, error) { + switch str { + case "-infinity": + if infinityTSEnabled { + return infinityTSNegative, nil + } + return []byte(str), nil + case "infinity": + if infinityTSEnabled { + return infinityTSPositive, nil + } + return []byte(str), nil + } + t, err := ParseTimestamp(currentLocation, str) + if err != nil { + err = errors.New("pq: " + err.Error()) + } + return t, err +} + +// ParseTimestamp parses Postgres' text format. It returns a time.Time in +// currentLocation iff that time's offset agrees with the offset sent from the +// Postgres server. Otherwise, ParseTimestamp returns a time.Time with the fixed +// offset offset provided by the Postgres server. +func ParseTimestamp(currentLocation *time.Location, str string) (time.Time, error) { + return pqtime.Parse(currentLocation, str) +} + +// formatTS formats t into a format postgres understands. +func formatTS(t time.Time) []byte { + if infinityTSEnabled { + // t <= -infinity : ! (t > -infinity) + if !t.After(infinityTSNegative) { + return []byte("-infinity") + } + // t >= infinity : ! (!t < infinity) + if !t.Before(infinityTSPositive) { + return []byte("infinity") + } + } + return FormatTimestamp(t) +} + +// FormatTimestamp formats t into Postgres' text format for timestamps. +func FormatTimestamp(t time.Time) []byte { + return pqtime.Format(t) +} + +// Parse a bytea value received from the server. Both "hex" and the legacy +// "escape" format are supported. +func parseBytea(s []byte) (result []byte, err error) { + // Hex format. + if len(s) >= 2 && bytes.Equal(s[:2], []byte("\\x")) { + s = s[2:] // trim off leading "\\x" + result = make([]byte, hex.DecodedLen(len(s))) + _, err := hex.Decode(result, s) + if err != nil { + return nil, err + } + return result, nil + } + + // Escape format. + for len(s) > 0 { + if s[0] == '\\' { + // escaped '\\' + if len(s) >= 2 && s[1] == '\\' { + result = append(result, '\\') + s = s[2:] + continue + } + + // '\\' followed by an octal number + if len(s) < 4 { + return nil, fmt.Errorf("invalid bytea sequence %v", s) + } + r, err := strconv.ParseUint(string(s[1:4]), 8, 8) + if err != nil { + return nil, fmt.Errorf("could not parse bytea value: %w", err) + } + result = append(result, byte(r)) + s = s[4:] + } else { + // We hit an unescaped, raw byte. Try to read in as many as + // possible in one go. + i := bytes.IndexByte(s, '\\') + if i == -1 { + result = append(result, s...) + break + } + result = append(result, s[:i]...) + s = s[i:] + } + } + return result, nil +} + +func encodeBytea(v []byte) (result []byte) { + result = make([]byte, 2+hex.EncodedLen(len(v))) + result[0] = '\\' + result[1] = 'x' + hex.Encode(result[2:], v) + return result +} diff --git a/vendor/github.com/lib/pq/error.go b/vendor/github.com/lib/pq/error.go new file mode 100644 index 0000000..7d06187 --- /dev/null +++ b/vendor/github.com/lib/pq/error.go @@ -0,0 +1,324 @@ +package pq + +import ( + "database/sql/driver" + "fmt" + "io" + "net" + "runtime" + "strconv" + "strings" + "unicode/utf8" + + "github.com/lib/pq/pqerror" +) + +// Error returned by the PostgreSQL server. +// +// The [Error] method returns the error message and error code: +// +// pq: invalid input syntax for type json (22P02) +// +// The [ErrorWithDetail] method also includes the error Detail, Hint, and +// location context (if any): +// +// ERROR: invalid input syntax for type json (22P02) +// DETAIL: Token "asd" is invalid. +// CONTEXT: line 5, column 8: +// +// 3 | 'def', +// 4 | 123, +// 5 | 'foo', 'asd'::jsonb +// ^ +type Error struct { + // [Efatal], [Epanic], [Ewarning], [Enotice], [Edebug], [Einfo], or [Elog]. + // Always present. + Severity string + + // SQLSTATE code. Always present. + Code pqerror.Code + + // Primary human-readable error message. This should be accurate but terse + // (typically one line). Always present. + Message string + + // Optional secondary error message carrying more detail about the problem. + // Might run to multiple lines. + Detail string + + // Optional suggestion what to do about the problem. This is intended to + // differ from Detail in that it offers advice (potentially inappropriate) + // rather than hard facts. Might run to multiple lines. + Hint string + + // error position as an index into the original query string, as decimal + // ASCII integer. The first character has index 1, and positions are + // measured in characters not bytes. + Position string + + // This is defined the same as the Position field, but it is used when the + // cursor position refers to an internally generated command rather than the + // one submitted by the client. The InternalQuery field will always appear + // when this field appears. + InternalPosition string + + // Text of a failed internally-generated command. This could be, for + // example, an SQL query issued by a PL/pgSQL function. + InternalQuery string + + // An indication of the context in which the error occurred. Presently this + // includes a call stack traceback of active procedural language functions + // and internally-generated queries. The trace is one entry per line, most + // recent first. + Where string + + // If the error was associated with a specific database object, the name of + // the schema containing that object, if any. + Schema string + + // If the error was associated with a specific table, the name of the table. + // (Refer to the schema name field for the name of the table's schema.) + Table string + + // If the error was associated with a specific table column, the name of the + // column. (Refer to the schema and table name fields to identify the + // table.) + Column string + + // If the error was associated with a specific data type, the name of the + // data type. (Refer to the schema name field for the name of the data + // type's schema.) + DataTypeName string + + // If the error was associated with a specific constraint, the name of the + // constraint. Refer to fields listed above for the associated table or + // domain. (For this purpose, indexes are treated as constraints, even if + // they weren't created with constraint syntax.) + Constraint string + + // File name of the source-code location where the error was reported. + File string + + // Line number of the source-code location where the error was reported. + Line string + + // Name of the source-code routine reporting the error. + Routine string + + query string +} + +type ( + // ErrorCode is a five-character error code. + // + // Deprecated: use pqerror.Code + // + //go:fix inline + ErrorCode = pqerror.Code + + // ErrorClass is only the class part of an error code. + // + // Deprecated: use pqerror.Class + // + //go:fix inline + ErrorClass = pqerror.Class +) + +func parseError(r *readBuf, q string) *Error { + err := &Error{query: q} + for t := r.byte(); t != 0; t = r.byte() { + msg := r.string() + switch t { + case 'S': + err.Severity = msg + case 'C': + err.Code = pqerror.Code(msg) + case 'M': + err.Message = msg + case 'D': + err.Detail = msg + case 'H': + err.Hint = msg + case 'P': + err.Position = msg + case 'p': + err.InternalPosition = msg + case 'q': + err.InternalQuery = msg + case 'W': + err.Where = msg + case 's': + err.Schema = msg + case 't': + err.Table = msg + case 'c': + err.Column = msg + case 'd': + err.DataTypeName = msg + case 'n': + err.Constraint = msg + case 'F': + err.File = msg + case 'L': + err.Line = msg + case 'R': + err.Routine = msg + } + } + return err +} + +// Fatal returns true if the Error Severity is fatal. +func (e *Error) Fatal() bool { return e.Severity == pqerror.SeverityFatal } + +// SQLState returns the SQLState of the error. +func (e *Error) SQLState() string { return string(e.Code) } + +func (e *Error) Error() string { + msg := e.Message + if e.query != "" && e.Position != "" { + pos, err := strconv.Atoi(e.Position) + if err == nil { + lines := strings.Split(e.query, "\n") + line, col := posToLine(pos, lines) + if len(lines) == 1 { + msg += " at column " + strconv.Itoa(col) + } else { + msg += " at position " + strconv.Itoa(line) + ":" + strconv.Itoa(col) + } + } + } + + if e.Code != "" { + return "pq: " + msg + " (" + string(e.Code) + ")" + } + return "pq: " + msg +} + +// ErrorWithDetail returns the error message with detailed information and +// location context (if any). +// +// See the documentation on [Error]. +func (e *Error) ErrorWithDetail() string { + b := new(strings.Builder) + b.Grow(len(e.Message) + len(e.Detail) + len(e.Hint) + 30) + b.WriteString("ERROR: ") + b.WriteString(e.Message) + if e.Code != "" { + b.WriteString(" (") + b.WriteString(string(e.Code)) + b.WriteByte(')') + } + if e.Detail != "" { + b.WriteString("\nDETAIL: ") + b.WriteString(e.Detail) + } + if e.Hint != "" { + b.WriteString("\nHINT: ") + b.WriteString(e.Hint) + } + + if e.query != "" && e.Position != "" { + b.Grow(512) + pos, err := strconv.Atoi(e.Position) + if err != nil { + return b.String() + } + lines := strings.Split(e.query, "\n") + line, col := posToLine(pos, lines) + + fmt.Fprintf(b, "\nCONTEXT: line %d, column %d:\n\n", line, col) + if line > 2 { + fmt.Fprintf(b, "% 7d | %s\n", line-2, expandTab(lines[line-3])) + } + if line > 1 { + fmt.Fprintf(b, "% 7d | %s\n", line-1, expandTab(lines[line-2])) + } + /// Expand tabs, so that the ^ is at at the correct position, but leave + /// "column 10-13" intact. Adjusting this to the visual column would be + /// better, but we don't know the tabsize of the user in their editor, + /// which can be 8, 4, 2, or something else. We can't know. So leaving + /// it as the character index is probably the "most correct". + expanded := expandTab(lines[line-1]) + diff := len(expanded) - len(lines[line-1]) + fmt.Fprintf(b, "% 7d | %s\n", line, expanded) + fmt.Fprintf(b, "% 10s%s%s\n", "", strings.Repeat(" ", col-1+diff), "^") + } + + return b.String() +} + +func posToLine(pos int, lines []string) (line, col int) { + read := 0 + for i := range lines { + line++ + ll := utf8.RuneCountInString(lines[i]) + 1 // +1 for the removed newline + if read+ll >= pos { + col = max(pos-read, 1) // Should be lower than 1, but just in case. + break + } + read += ll + } + return line, col +} + +func expandTab(s string) string { + var ( + b strings.Builder + l int + fill = func(n int) string { + b := make([]byte, n) + for i := range b { + b[i] = ' ' + } + return string(b) + } + ) + b.Grow(len(s)) + for _, r := range s { + switch r { + case '\t': + tw := 8 - l%8 + b.WriteString(fill(tw)) + l += tw + default: + b.WriteRune(r) + l += 1 + } + } + return b.String() +} + +func (cn *conn) handleError(reported error, query ...string) error { + switch err := reported.(type) { + case nil: + return nil + case runtime.Error, *net.OpError: + cn.err.set(driver.ErrBadConn) + case *safeRetryError: + cn.err.set(driver.ErrBadConn) + reported = driver.ErrBadConn + case *Error: + if len(query) > 0 && query[0] != "" { + err.query = query[0] + reported = err + } + if err.Fatal() { + reported = driver.ErrBadConn + } + case error: + if err == io.EOF || err == io.ErrUnexpectedEOF || err.Error() == "remote error: handshake failure" { + reported = driver.ErrBadConn + } + default: + cn.err.set(driver.ErrBadConn) + reported = fmt.Errorf("pq: unknown error %T: %[1]s", err) + } + + // Any time we return ErrBadConn, we need to remember it since *Tx doesn't + // mark the connection bad in database/sql. + if reported == driver.ErrBadConn { + cn.err.set(driver.ErrBadConn) + } + return reported +} diff --git a/vendor/github.com/lib/pq/internal/pgpass/pgpass.go b/vendor/github.com/lib/pq/internal/pgpass/pgpass.go new file mode 100644 index 0000000..4da3538 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pgpass/pgpass.go @@ -0,0 +1,70 @@ +package pgpass + +import ( + "bufio" + "os" + "path/filepath" + "strings" + + "github.com/lib/pq/internal/pqutil" +) + +func PasswordFromPgpass(passfile, user, password, host, port, dbname string) string { + if password != "" { // Do not process .pgpass if a password was supplied. + return password + } + + filename := pqutil.Pgpass(passfile) + if filename == "" { + return "" + } + + fp, err := os.Open(filename) + if err != nil { + return "" + } + defer fp.Close() + + scan := bufio.NewScanner(fp) + for scan.Scan() { + line := scan.Text() + if len(line) == 0 || line[0] == '#' { + continue + } + split := splitFields(line) + if len(split) != 5 { + continue + } + + socket := host == "" || filepath.IsAbs(host) || strings.HasPrefix(host, "@") + if (split[0] == "*" || split[0] == host || (split[0] == "localhost" && socket)) && + (split[1] == "*" || split[1] == port) && + (split[2] == "*" || split[2] == dbname) && + (split[3] == "*" || split[3] == user) { + return split[4] + } + } + + return "" +} + +func splitFields(s string) []string { + var ( + fs = make([]string, 0, 5) + f = make([]rune, 0, len(s)) + esc bool + ) + for _, c := range s { + switch { + case esc: + f, esc = append(f, c), false + case c == '\\': + esc = true + case c == ':': + fs, f = append(fs, string(f)), f[:0] + default: + f = append(f, c) + } + } + return append(fs, string(f)) +} diff --git a/vendor/github.com/lib/pq/internal/pgservice/pgservice.go b/vendor/github.com/lib/pq/internal/pgservice/pgservice.go new file mode 100644 index 0000000..9842648 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pgservice/pgservice.go @@ -0,0 +1,70 @@ +package pgservice + +import ( + "bufio" + "fmt" + "os" + "strings" + + "github.com/lib/pq/internal/pqutil" +) + +func FindService(path string, service string) (map[string]string, error) { + fp, err := os.Open(path) + if err != nil { + if pqutil.ErrNotExists(err) { + // libpq just returns "definition of service not found" if the + // default file doesn't exist, but IMO that's confusing. + return nil, fmt.Errorf("service file %q not found", path) + } + return nil, err + } + defer fp.Close() + + var ( + scan = bufio.NewScanner(fp) + i int + ) + for scan.Scan() { + i++ + line := strings.TrimSpace(scan.Text()) + if line == "" || line[0] == '#' { + continue + } + + // [service] header that we want. + if line[0] == '[' && line[len(line)-1] == ']' && strings.TrimSpace(line[1:len(line)-1]) == service { + opts := make(map[string]string) + for scan.Scan() { + i++ + line := strings.TrimSpace(scan.Text()) + if line == "" || line[0] == '#' { + continue + } + // Next header: our work here is done. + if line[0] == '[' && line[len(line)-1] == ']' { + return opts, nil + } + + k, v, ok := strings.Cut(line, "=") + if !ok { + return nil, fmt.Errorf("line %d: missing '=' in %q", i, line) + } + k, v = strings.TrimSpace(k), strings.TrimSpace(v) + if k == "" { + return nil, fmt.Errorf("line %d: no value before '=' in %q", i, line) + } + opts[k] = v + } + if scan.Err() != nil { + return nil, scan.Err() + } + return opts, nil + } + } + if scan.Err() != nil { + return nil, scan.Err() + } + + return nil, fmt.Errorf("definition of service %q not found", service) +} diff --git a/vendor/github.com/lib/pq/internal/pqsql/copy.go b/vendor/github.com/lib/pq/internal/pqsql/copy.go new file mode 100644 index 0000000..ccb688f --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqsql/copy.go @@ -0,0 +1,37 @@ +package pqsql + +// StartsWithCopy reports if the SQL strings start with "copy", ignoring +// whitespace, comments, and casing. +func StartsWithCopy(query string) bool { + if len(query) < 4 { + return false + } + var linecmt, blockcmt bool + for i := 0; i < len(query); i++ { + c := query[i] + if linecmt { + linecmt = c != '\n' + continue + } + if blockcmt { + blockcmt = !(c == '/' && query[i-1] == '*') + continue + } + if c == '-' && len(query) > i+1 && query[i+1] == '-' { + linecmt = true + continue + } + if c == '/' && len(query) > i+1 && query[i+1] == '*' { + blockcmt = true + continue + } + if c == ' ' || c == '\t' || c == '\r' || c == '\n' { + continue + } + + // First non-comment and non-whitespace. + return len(query) > i+3 && c|0x20 == 'c' && query[i+1]|0x20 == 'o' && + query[i+2]|0x20 == 'p' && query[i+3]|0x20 == 'y' + } + return false +} diff --git a/vendor/github.com/lib/pq/internal/pqtime/loc.go b/vendor/github.com/lib/pq/internal/pqtime/loc.go new file mode 100644 index 0000000..d23dd5b --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqtime/loc.go @@ -0,0 +1,37 @@ +package pqtime + +import ( + "sync" + "time" +) + +// The location cache caches the time zones typically used by the client. +type locationCache struct { + cache map[int]*time.Location + lock sync.Mutex +} + +// All connections share the same list of timezones. Benchmarking shows that +// about 5% speed could be gained by putting the cache in the connection and +// losing the mutex, at the cost of a small amount of memory and a somewhat +// significant increase in code complexity. +var globalLocationCache = &locationCache{cache: make(map[int]*time.Location)} + +func Reset() { + globalLocationCache = &locationCache{cache: make(map[int]*time.Location)} +} + +// Returns the cached timezone for the specified offset, creating and caching +// it if necessary. +func (c *locationCache) getLocation(offset int) *time.Location { + c.lock.Lock() + defer c.lock.Unlock() + l, ok := c.cache[offset] + if !ok { + // TODO(v2): for offset=0 it should use some descriptive text like + // "without time zone". + l = time.FixedZone("", offset) + c.cache[offset] = l + } + return l +} diff --git a/vendor/github.com/lib/pq/internal/pqtime/pqtime.go b/vendor/github.com/lib/pq/internal/pqtime/pqtime.go new file mode 100644 index 0000000..28008e8 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqtime/pqtime.go @@ -0,0 +1,190 @@ +package pqtime + +import ( + "errors" + "fmt" + "math" + "strconv" + "strings" + "time" +) + +var errInvalidTimestamp = errors.New("invalid timestamp") + +type timestampParser struct { + err error +} + +func (p *timestampParser) expect(str string, char byte, pos int) { + if p.err != nil { + return + } + if pos+1 > len(str) { + p.err = errInvalidTimestamp + return + } + if c := str[pos]; c != char && p.err == nil { + p.err = fmt.Errorf("expected '%v' at position %v; got '%v'", char, pos, c) + } +} + +func (p *timestampParser) mustAtoi(str string, begin int, end int) int { + if p.err != nil { + return 0 + } + if begin < 0 || end < 0 || begin > end || end > len(str) { + p.err = errInvalidTimestamp + return 0 + } + result, err := strconv.Atoi(str[begin:end]) + if err != nil { + if p.err == nil { + p.err = fmt.Errorf("expected number; got '%v'", str) + } + return 0 + } + return result +} + +func Parse(currentLocation *time.Location, str string) (time.Time, error) { + p := timestampParser{} + + monSep := strings.IndexRune(str, '-') + // this is Gregorian year, not ISO Year + // In Gregorian system, the year 1 BC is followed by AD 1 + year := p.mustAtoi(str, 0, monSep) + daySep := monSep + 3 + month := p.mustAtoi(str, monSep+1, daySep) + p.expect(str, '-', daySep) + timeSep := daySep + 3 + day := p.mustAtoi(str, daySep+1, timeSep) + + minLen := monSep + len("01-01") + 1 + + isBC := strings.HasSuffix(str, " BC") + if isBC { + minLen += 3 + } + + var hour, minute, second int + if len(str) > minLen { + p.expect(str, ' ', timeSep) + minSep := timeSep + 3 + p.expect(str, ':', minSep) + hour = p.mustAtoi(str, timeSep+1, minSep) + secSep := minSep + 3 + p.expect(str, ':', secSep) + minute = p.mustAtoi(str, minSep+1, secSep) + secEnd := secSep + 3 + second = p.mustAtoi(str, secSep+1, secEnd) + } + remainderIdx := monSep + len("01-01 00:00:00") + 1 + // Three optional (but ordered) sections follow: the + // fractional seconds, the time zone offset, and the BC + // designation. We set them up here and adjust the other + // offsets if the preceding sections exist. + + nanoSec := 0 + tzOff := 0 + + if remainderIdx < len(str) && str[remainderIdx] == '.' { + fracStart := remainderIdx + 1 + fracOff := strings.IndexAny(str[fracStart:], "-+Z ") + if fracOff < 0 { + fracOff = len(str) - fracStart + } + fracSec := p.mustAtoi(str, fracStart, fracStart+fracOff) + nanoSec = fracSec * (1000000000 / int(math.Pow(10, float64(fracOff)))) + + remainderIdx += fracOff + 1 + } + if tzStart := remainderIdx; tzStart < len(str) && (str[tzStart] == '-' || str[tzStart] == '+') { + // time zone separator is always '-' or '+' or 'Z' (UTC is +00) + var tzSign int + switch c := str[tzStart]; c { + case '-': + tzSign = -1 + case '+': + tzSign = +1 + default: + return time.Time{}, fmt.Errorf("expected '-' or '+' at position %v; got %v", tzStart, c) + } + tzHours := p.mustAtoi(str, tzStart+1, tzStart+3) + remainderIdx += 3 + var tzMin, tzSec int + if remainderIdx < len(str) && str[remainderIdx] == ':' { + tzMin = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) + remainderIdx += 3 + } + if remainderIdx < len(str) && str[remainderIdx] == ':' { + tzSec = p.mustAtoi(str, remainderIdx+1, remainderIdx+3) + remainderIdx += 3 + } + tzOff = tzSign * ((tzHours * 60 * 60) + (tzMin * 60) + tzSec) + } else if tzStart < len(str) && str[tzStart] == 'Z' { + // time zone Z separator indicates UTC is +00 + remainderIdx += 1 + } + + var isoYear int + + if isBC { + isoYear = 1 - year + remainderIdx += 3 + } else { + isoYear = year + } + if remainderIdx < len(str) { + return time.Time{}, fmt.Errorf("expected end of input, got %v", str[remainderIdx:]) + } + t := time.Date(isoYear, time.Month(month), day, + hour, minute, second, nanoSec, + globalLocationCache.getLocation(tzOff)) + + if currentLocation != nil { + // Set the location of the returned Time based on the session's + // TimeZone value, but only if the local time zone database agrees with + // the remote database on the offset. + lt := t.In(currentLocation) + _, newOff := lt.Zone() + if newOff == tzOff { + t = lt + } + } + + return t, p.err +} + +// Format into Postgres' text format for timestamps. +func Format(t time.Time) []byte { + // Need to send dates before 0001 A.D. with " BC" suffix, instead of the + // minus sign preferred by Go. + // Beware, "0000" in ISO is "1 BC", "-0001" is "2 BC" and so on + bc := false + if t.Year() <= 0 { + // flip year sign, and add 1, e.g: "0" will be "1", and "-10" will be "11" + t = t.AddDate((-t.Year())*2+1, 0, 0) + bc = true + } + b := []byte(t.Format("2006-01-02 15:04:05.999999999Z07:00")) + + _, offset := t.Zone() + offset %= 60 + if offset != 0 { + // RFC3339Nano already printed the minus sign + if offset < 0 { + offset = -offset + } + + b = append(b, ':') + if offset < 10 { + b = append(b, '0') + } + b = strconv.AppendInt(b, int64(offset), 10) + } + + if bc { + b = append(b, " BC"...) + } + return b +} diff --git a/vendor/github.com/lib/pq/internal/pqutil/path.go b/vendor/github.com/lib/pq/internal/pqutil/path.go new file mode 100644 index 0000000..dd0d5af --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/path.go @@ -0,0 +1,91 @@ +package pqutil + +import ( + "errors" + "fmt" + "io" + "os" + "os/user" + "path/filepath" + "runtime" + "syscall" +) + +// Home gets the PostgreSQL configuration dir in the user's home directory: +// %APPDATA%/postgresql on Windows, and $HOME/.postgresql/postgresql.crt +// everywhere else. +// +// Returns an empy string if no home directory was found. +// +// Matches pqGetHomeDirectory() from PostgreSQL. +// https://github.com/postgres/postgres/blob/2b117bb/src/interfaces/libpq/fe-connect.c#L8214 +func Home(subdir bool) string { + if runtime.GOOS == "windows" { + // pq uses SHGetFolderPath(), which is deprecated but x/sys/windows has + // KnownFolderPath(). We don't really want to pull that in though, so + // use APPDATA env. This is also what PostgreSQL uses in some other + // codepaths (get_home_path() for example). + ad := os.Getenv("APPDATA") + if ad == "" { + return "" + } + return filepath.Join(ad, "postgresql") + } + + home, _ := os.UserHomeDir() + if home == "" { + u, err := user.Current() + if err != nil { + return "" + } + home = u.HomeDir + } + // libpq reads some files from ~/ and some from ~/.postgresql – on Windows + // it always uses %APPDATA%/postgresql. + if subdir { + home = filepath.Join(home, ".postgresql") + } + return home +} + +// ErrNotExists reports if err is a "path doesn't exist" type error. +// +// fs.ErrNotExist is not enough, as "/dev/null/somefile" will return ENOTDIR +// instead of ENOENT. +func ErrNotExists(err error) bool { + perr := new(os.PathError) + if errors.As(err, &perr) && (perr.Err == syscall.ENOENT || perr.Err == syscall.ENOTDIR) { + return true + } + return false +} + +var WarnFD io.Writer = os.Stderr + +// Pgpass gets the filepath to the pgpass file to use, returning "" if a pgpass +// file shouldn't be used. +func Pgpass(passfile string) string { + // Get passfile from the options. + if passfile == "" { + home := Home(false) + if home == "" { + return "" + } + passfile = filepath.Join(home, ".pgpass") + } + + // On Win32, the directory is protected, so we don't have to check the file. + if runtime.GOOS != "windows" { + fi, err := os.Stat(passfile) + if err != nil { + return "" + } + if fi.Mode().Perm()&(0x77) != 0 { + fmt.Fprintf(WarnFD, + "WARNING: password file %q has group or world access; permissions should be u=rw (0600) or less\n", + passfile) + return "" + } + } + return passfile +} diff --git a/vendor/github.com/lib/pq/internal/pqutil/perm.go b/vendor/github.com/lib/pq/internal/pqutil/perm.go new file mode 100644 index 0000000..05fb9a6 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/perm.go @@ -0,0 +1,64 @@ +//go:build !windows && !plan9 + +package pqutil + +import ( + "errors" + "os" + "syscall" +) + +var ( + ErrSSLKeyUnknownOwnership = errors.New("pq: could not get owner information for private key, may not be properly protected") + ErrSSLKeyHasWorldPermissions = errors.New("pq: private key has world access; permissions should be u=rw,g=r (0640) if owned by root, or u=rw (0600), or less") +) + +// SSLKeyPermissions checks the permissions on user-supplied SSL key files, +// which should have very little access. libpq does not check key file +// permissions on Windows. +// +// If the file is owned by the same user the process is running as, the file +// should only have 0600. If the file is owned by root, and the group matches +// the group that the process is running in, the permissions cannot be more than +// 0640. The file should never have world permissions. +// +// Returns an error when the permission check fails. +func SSLKeyPermissions(sslkey string) error { + fi, err := os.Stat(sslkey) + if err != nil { + return err + } + + return CheckPermissions(fi) +} + +func CheckPermissions(fi os.FileInfo) error { + // The maximum permissions that a private key file owned by a regular user + // is allowed to have. This translates to u=rw. Regardless of if we're + // running as root or not, 0600 is acceptable, so we return if no bits + // beyond the regular user permission mask are set. + if fi.Mode().Perm()&^os.FileMode(0o600) == 0 { + return nil + } + + // We need to pull the Unix file information to get the file's owner. + // If we can't access it, there's some sort of operating system level error + // and we should fail rather than attempting to use faulty information. + sys, ok := fi.Sys().(*syscall.Stat_t) + if !ok { + return ErrSSLKeyUnknownOwnership + } + + // if the file is owned by root, we allow 0640 (u=rw,g=r) to match what + // Postgres does. + if sys.Uid == 0 { + // The maximum permissions that a private key file owned by root is + // allowed to have. This translates to u=rw,g=r. + if fi.Mode().Perm()&^os.FileMode(0o640) != 0 { + return ErrSSLKeyHasWorldPermissions + } + return nil + } + + return ErrSSLKeyHasWorldPermissions +} diff --git a/vendor/github.com/lib/pq/internal/pqutil/perm_unsupported.go b/vendor/github.com/lib/pq/internal/pqutil/perm_unsupported.go new file mode 100644 index 0000000..3ce7595 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/perm_unsupported.go @@ -0,0 +1,12 @@ +//go:build windows || plan9 + +package pqutil + +import "errors" + +var ( + ErrSSLKeyUnknownOwnership = errors.New("unused") + ErrSSLKeyHasWorldPermissions = errors.New("unused") +) + +func SSLKeyPermissions(sslkey string) error { return nil } diff --git a/vendor/github.com/lib/pq/internal/pqutil/pqutil.go b/vendor/github.com/lib/pq/internal/pqutil/pqutil.go new file mode 100644 index 0000000..ca869e9 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/pqutil.go @@ -0,0 +1,32 @@ +package pqutil + +import ( + "strconv" + "strings" +) + +// ParseBool is like strconv.ParseBool, but also accepts "yes"/"no" and +// "on"/"off". +func ParseBool(str string) (bool, error) { + switch str { + case "1", "t", "T", "true", "TRUE", "True", "yes", "on": + return true, nil + case "0", "f", "F", "false", "FALSE", "False", "no", "off": + return false, nil + } + return false, &strconv.NumError{Func: "ParseBool", Num: str, Err: strconv.ErrSyntax} +} + +func Join[S ~[]E, E ~string](s S) string { + var b strings.Builder + for i := range s { + if i > 0 { + b.WriteString(", ") + } + if i == len(s)-1 { + b.WriteString("or ") + } + b.WriteString(string(s[i])) + } + return b.String() +} diff --git a/vendor/github.com/lib/pq/internal/pqutil/user_other.go b/vendor/github.com/lib/pq/internal/pqutil/user_other.go new file mode 100644 index 0000000..09e4f8d --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/user_other.go @@ -0,0 +1,9 @@ +//go:build js || android || hurd || zos || wasip1 || appengine + +package pqutil + +import "errors" + +func User() (string, error) { + return "", errors.New("pqutil.User: not supported on current platform") +} diff --git a/vendor/github.com/lib/pq/internal/pqutil/user_posix.go b/vendor/github.com/lib/pq/internal/pqutil/user_posix.go new file mode 100644 index 0000000..bd0ece6 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/user_posix.go @@ -0,0 +1,25 @@ +//go:build !windows && !js && !android && !hurd && !zos && !wasip1 && !appengine + +package pqutil + +import ( + "os" + "os/user" + "runtime" +) + +func User() (string, error) { + env := "USER" + if runtime.GOOS == "plan9" { + env = "user" + } + if n := os.Getenv(env); n != "" { + return n, nil + } + + u, err := user.Current() + if err != nil { + return "", err + } + return u.Username, nil +} diff --git a/vendor/github.com/lib/pq/internal/pqutil/user_windows.go b/vendor/github.com/lib/pq/internal/pqutil/user_windows.go new file mode 100644 index 0000000..960cb80 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/pqutil/user_windows.go @@ -0,0 +1,28 @@ +//go:build windows && !appengine + +package pqutil + +import ( + "path/filepath" + "syscall" +) + +func User() (string, error) { + // Perform Windows user name lookup identically to libpq. + // + // The PostgreSQL code makes use of the legacy Win32 function GetUserName, + // and that function has not been imported into stock Go. GetUserNameEx is + // available though, the difference being that a wider range of names are + // available. To get the output to be the same as GetUserName, only the + // base (or last) component of the result is returned. + var ( + name = make([]uint16, 128) + pwnameSz = uint32(len(name)) - 1 + ) + err := syscall.GetUserNameEx(syscall.NameSamCompatible, &name[0], &pwnameSz) + if err != nil { + return "", err + } + s := syscall.UTF16ToString(name) + return filepath.Base(s), nil +} diff --git a/vendor/github.com/lib/pq/internal/proto/proto.go b/vendor/github.com/lib/pq/internal/proto/proto.go new file mode 100644 index 0000000..e8b4bc5 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/proto/proto.go @@ -0,0 +1,186 @@ +// From src/include/libpq/protocol.h and src/include/libpq/pqcomm.h – PostgreSQL 18.1 + +package proto + +import ( + "fmt" + "strconv" +) + +// Constants from pqcomm.h +const ( + ProtocolVersion30 = (3 << 16) | 0 //lint:ignore SA4016 x + ProtocolVersion32 = (3 << 16) | 2 // PostgreSQL ≥18. + CancelRequestCode = (1234 << 16) | 5678 + NegotiateSSLCode = (1234 << 16) | 5679 + NegotiateGSSCode = (1234 << 16) | 5680 +) + +// Constants from fe-connect.c +const ( + MaxErrlen = 30_000 // https://github.com/postgres/postgres/blob/c6a10a89f/src/interfaces/libpq/fe-connect.c#L4067 +) + +// RequestCode is a request codes sent by the frontend. +type RequestCode byte + +// These are the request codes sent by the frontend. +const ( + Bind = RequestCode('B') + Close = RequestCode('C') + Describe = RequestCode('D') + Execute = RequestCode('E') + FunctionCall = RequestCode('F') + Flush = RequestCode('H') + Parse = RequestCode('P') + Query = RequestCode('Q') + Sync = RequestCode('S') + Terminate = RequestCode('X') + CopyFail = RequestCode('f') + GSSResponse = RequestCode('p') + PasswordMessage = RequestCode('p') + SASLInitialResponse = RequestCode('p') + SASLResponse = RequestCode('p') + CopyDoneRequest = RequestCode('c') + CopyDataRequest = RequestCode('d') +) + +func (r RequestCode) String() string { + s, ok := map[RequestCode]string{ + Bind: "Bind", + Close: "Close", + Describe: "Describe", + Execute: "Execute", + FunctionCall: "FunctionCall", + Flush: "Flush", + Parse: "Parse", + Query: "Query", + Sync: "Sync", + Terminate: "Terminate", + CopyFail: "CopyFail", + // These are all the same :-/ + //GSSResponse: "GSSResponse", + PasswordMessage: "PasswordMessage", + //SASLInitialResponse: "SASLInitialResponse", + //SASLResponse: "SASLResponse", + CopyDoneRequest: "CopyDone", + CopyDataRequest: "CopyData", + }[r] + if !ok { + s = "" + } + c := string(r) + if r <= 0x1f || r == 0x7f { + c = fmt.Sprintf("0x%x", string(r)) + } + return "(" + c + ") " + s +} + +// ResponseCode is a response codes sent by the backend. +type ResponseCode byte + +// These are the response codes sent by the backend. +const ( + ParseComplete = ResponseCode('1') + BindComplete = ResponseCode('2') + CloseComplete = ResponseCode('3') + NotificationResponse = ResponseCode('A') + CommandComplete = ResponseCode('C') + DataRow = ResponseCode('D') + ErrorResponse = ResponseCode('E') + CopyInResponse = ResponseCode('G') + CopyOutResponse = ResponseCode('H') + EmptyQueryResponse = ResponseCode('I') + BackendKeyData = ResponseCode('K') + NoticeResponse = ResponseCode('N') + AuthenticationRequest = ResponseCode('R') + ParameterStatus = ResponseCode('S') + RowDescription = ResponseCode('T') + FunctionCallResponse = ResponseCode('V') + CopyBothResponse = ResponseCode('W') + ReadyForQuery = ResponseCode('Z') + NoData = ResponseCode('n') + PortalSuspended = ResponseCode('s') + ParameterDescription = ResponseCode('t') + NegotiateProtocolVersion = ResponseCode('v') + CopyDoneResponse = ResponseCode('c') + CopyDataResponse = ResponseCode('d') +) + +func (r ResponseCode) String() string { + s, ok := map[ResponseCode]string{ + ParseComplete: "ParseComplete", + BindComplete: "BindComplete", + CloseComplete: "CloseComplete", + NotificationResponse: "NotificationResponse", + CommandComplete: "CommandComplete", + DataRow: "DataRow", + ErrorResponse: "ErrorResponse", + CopyInResponse: "CopyInResponse", + CopyOutResponse: "CopyOutResponse", + EmptyQueryResponse: "EmptyQueryResponse", + BackendKeyData: "BackendKeyData", + NoticeResponse: "NoticeResponse", + AuthenticationRequest: "AuthRequest", + ParameterStatus: "ParamStatus", + RowDescription: "RowDescription", + FunctionCallResponse: "FunctionCallResponse", + CopyBothResponse: "CopyBothResponse", + ReadyForQuery: "ReadyForQuery", + NoData: "NoData", + PortalSuspended: "PortalSuspended", + ParameterDescription: "ParamDescription", + NegotiateProtocolVersion: "NegotiateProtocolVersion", + CopyDoneResponse: "CopyDone", + CopyDataResponse: "CopyData", + }[r] + if !ok { + s = "" + } + c := string(r) + if r <= 0x1f || r == 0x7f { + c = fmt.Sprintf("0x%x", string(r)) + } + return "(" + c + ") " + s +} + +// AuthCode are authentication request codes sent by the backend. +type AuthCode int32 + +// These are the authentication request codes sent by the backend. +const ( + AuthReqOk = AuthCode(0) // User is authenticated + AuthReqKrb4 = AuthCode(1) // Kerberos V4. Not supported any more. + AuthReqKrb5 = AuthCode(2) // Kerberos V5. Not supported any more. + AuthReqPassword = AuthCode(3) // Password + AuthReqCrypt = AuthCode(4) // crypt password. Not supported any more. + AuthReqMD5 = AuthCode(5) // md5 password + _ = AuthCode(6) // 6 is available. It was used for SCM creds, not supported any more. + AuthReqGSS = AuthCode(7) // GSSAPI without wrap() + AuthReqGSSCont = AuthCode(8) // Continue GSS exchanges + AuthReqSSPI = AuthCode(9) // SSPI negotiate without wrap() + AuthReqSASL = AuthCode(10) // Begin SASL authentication + AuthReqSASLCont = AuthCode(11) // Continue SASL authentication + AuthReqSASLFin = AuthCode(12) // Final SASL message +) + +func (a AuthCode) String() string { + s, ok := map[AuthCode]string{ + AuthReqOk: "ok", + AuthReqKrb4: "krb4", + AuthReqKrb5: "krb5", + AuthReqPassword: "password", + AuthReqCrypt: "crypt", + AuthReqMD5: "md5", + AuthReqGSS: "GDD", + AuthReqGSSCont: "GSSCont", + AuthReqSSPI: "SSPI", + AuthReqSASL: "SASL", + AuthReqSASLCont: "SASLCont", + AuthReqSASLFin: "SASLFin", + }[a] + if !ok { + s = "" + } + return s + " (" + strconv.Itoa(int(a)) + ")" +} diff --git a/vendor/github.com/lib/pq/internal/proto/sz_32.go b/vendor/github.com/lib/pq/internal/proto/sz_32.go new file mode 100644 index 0000000..6806559 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/proto/sz_32.go @@ -0,0 +1,7 @@ +//go:build 386 || arm || mips || mipsle + +package proto + +import "math" + +const MaxUint32 = math.MaxInt diff --git a/vendor/github.com/lib/pq/internal/proto/sz_64.go b/vendor/github.com/lib/pq/internal/proto/sz_64.go new file mode 100644 index 0000000..2b8ad89 --- /dev/null +++ b/vendor/github.com/lib/pq/internal/proto/sz_64.go @@ -0,0 +1,7 @@ +//go:build !386 && !arm && !mips && !mipsle + +package proto + +import "math" + +const MaxUint32 = math.MaxUint32 diff --git a/vendor/github.com/lib/pq/krb.go b/vendor/github.com/lib/pq/krb.go new file mode 100644 index 0000000..408ec01 --- /dev/null +++ b/vendor/github.com/lib/pq/krb.go @@ -0,0 +1,27 @@ +package pq + +// NewGSSFunc creates a GSS authentication provider, for use with +// RegisterGSSProvider. +type NewGSSFunc func() (GSS, error) + +var newGss NewGSSFunc + +// RegisterGSSProvider registers a GSS authentication provider. For example, if +// you need to use Kerberos to authenticate with your server, add this to your +// main package: +// +// import "github.com/lib/pq/auth/kerberos" +// +// func init() { +// pq.RegisterGSSProvider(func() (pq.GSS, error) { return kerberos.NewGSS() }) +// } +func RegisterGSSProvider(newGssArg NewGSSFunc) { + newGss = newGssArg +} + +// GSS provides GSSAPI authentication (e.g., Kerberos). +type GSS interface { + GetInitToken(host string, service string) ([]byte, error) + GetInitTokenFromSpn(spn string) ([]byte, error) + Continue(inToken []byte) (done bool, outToken []byte, err error) +} diff --git a/vendor/github.com/lib/pq/notice.go b/vendor/github.com/lib/pq/notice.go new file mode 100644 index 0000000..7b9ff39 --- /dev/null +++ b/vendor/github.com/lib/pq/notice.go @@ -0,0 +1,69 @@ +package pq + +import ( + "context" + "database/sql/driver" +) + +// NoticeHandler returns the notice handler on the given connection, if any. A +// runtime panic occurs if c is not a pq connection. This is rarely used +// directly, use [ConnectorNoticeHandler] and [ConnectorWithNoticeHandler] instead. +func NoticeHandler(c driver.Conn) func(*Error) { + return c.(*conn).noticeHandler +} + +// SetNoticeHandler sets the given notice handler on the given connection. A +// runtime panic occurs if c is not a pq connection. A nil handler may be used +// to unset it. This is rarely used directly, use ConnectorNoticeHandler and +// [ConnectorWithNoticeHandler] instead. +// +// Note: Notice handlers are executed synchronously by pq meaning commands +// won't continue to be processed until the handler returns. +func SetNoticeHandler(c driver.Conn, handler func(*Error)) { + c.(*conn).noticeHandler = handler +} + +// NoticeHandlerConnector wraps a regular connector and sets a notice handler +// on it. +type NoticeHandlerConnector struct { + driver.Connector + noticeHandler func(*Error) +} + +// Connect calls the underlying connector's connect method and then sets the +// notice handler. +func (n *NoticeHandlerConnector) Connect(ctx context.Context) (driver.Conn, error) { + c, err := n.Connector.Connect(ctx) + if err == nil { + SetNoticeHandler(c, n.noticeHandler) + } + return c, err +} + +// ConnectorNoticeHandler returns the currently set notice handler, if any. If +// the given connector is not a result of [ConnectorWithNoticeHandler], nil is +// returned. +func ConnectorNoticeHandler(c driver.Connector) func(*Error) { + if c, ok := c.(*NoticeHandlerConnector); ok { + return c.noticeHandler + } + return nil +} + +// ConnectorWithNoticeHandler creates or sets the given handler for the given +// connector. If the given connector is a result of calling this function +// previously, it is simply set on the given connector and returned. Otherwise, +// this returns a new connector wrapping the given one and setting the notice +// handler. A nil notice handler may be used to unset it. +// +// The returned connector is intended to be used with database/sql.OpenDB. +// +// Note: Notice handlers are executed synchronously by pq meaning commands +// won't continue to be processed until the handler returns. +func ConnectorWithNoticeHandler(c driver.Connector, handler func(*Error)) *NoticeHandlerConnector { + if c, ok := c.(*NoticeHandlerConnector); ok { + c.noticeHandler = handler + return c + } + return &NoticeHandlerConnector{Connector: c, noticeHandler: handler} +} diff --git a/vendor/github.com/lib/pq/notify.go b/vendor/github.com/lib/pq/notify.go new file mode 100644 index 0000000..4f4c422 --- /dev/null +++ b/vendor/github.com/lib/pq/notify.go @@ -0,0 +1,834 @@ +package pq + +import ( + "context" + "database/sql/driver" + "errors" + "fmt" + "net" + "sync" + "sync/atomic" + "time" + + "github.com/lib/pq/internal/proto" +) + +// Notification represents a single notification from the database. +type Notification struct { + BePid int // Process ID (PID) of the notifying postgres backend. + Channel string // Name of the channel the notification was sent on. + Extra string // Payload, or the empty string if unspecified. +} + +func recvNotification(r *readBuf) *Notification { + bePid := r.int32() + channel := r.string() + extra := r.string() + return &Notification{bePid, channel, extra} +} + +// SetNotificationHandler sets the given notification handler on the given +// connection. A runtime panic occurs if c is not a pq connection. A nil handler +// may be used to unset it. +// +// Note: Notification handlers are executed synchronously by pq meaning commands +// won't continue to be processed until the handler returns. +func SetNotificationHandler(c driver.Conn, handler func(*Notification)) { + c.(*conn).notificationHandler = handler +} + +// NotificationHandlerConnector wraps a regular connector and sets a +// notification handler on it. +type NotificationHandlerConnector struct { + driver.Connector + notificationHandler func(*Notification) +} + +// Connect calls the underlying connector's connect method and then sets the +// notification handler. +func (n *NotificationHandlerConnector) Connect(ctx context.Context) (driver.Conn, error) { + c, err := n.Connector.Connect(ctx) + if err == nil { + SetNotificationHandler(c, n.notificationHandler) + } + return c, err +} + +// ConnectorNotificationHandler returns the currently set notification handler, +// if any. If the given connector is not a result of +// [ConnectorWithNotificationHandler], nil is returned. +func ConnectorNotificationHandler(c driver.Connector) func(*Notification) { + if c, ok := c.(*NotificationHandlerConnector); ok { + return c.notificationHandler + } + return nil +} + +// ConnectorWithNotificationHandler creates or sets the given handler for the +// given connector. If the given connector is a result of calling this function +// previously, it is simply set on the given connector and returned. Otherwise, +// this returns a new connector wrapping the given one and setting the +// notification handler. A nil notification handler may be used to unset it. +// +// The returned connector is intended to be used with database/sql.OpenDB. +// +// Note: Notification handlers are executed synchronously by pq meaning commands +// won't continue to be processed until the handler returns. +func ConnectorWithNotificationHandler(c driver.Connector, handler func(*Notification)) *NotificationHandlerConnector { + if c, ok := c.(*NotificationHandlerConnector); ok { + c.notificationHandler = handler + return c + } + return &NotificationHandlerConnector{Connector: c, notificationHandler: handler} +} + +const ( + connStateIdle int32 = iota + connStateExpectResponse + connStateExpectReadyForQuery +) + +type message struct { + typ proto.ResponseCode + err error +} + +var errListenerConnClosed = errors.New("pq: ListenerConn has been closed") + +// ListenerConn is a low-level interface for waiting for notifications. You +// should use [Listener] instead. +type ListenerConn struct { + connectionLock sync.Mutex // guards cn and err + senderLock sync.Mutex // the sending goroutine will be holding this lock + cn *conn + err error + connState int32 + notificationChan chan<- *Notification + replyChan chan message +} + +// NewListenerConn creates a new ListenerConn. Use NewListener instead. +func NewListenerConn(name string, notificationChan chan<- *Notification) (*ListenerConn, error) { + return newDialListenerConn(defaultDialer{}, name, notificationChan) +} + +func newDialListenerConn(d Dialer, name string, c chan<- *Notification) (*ListenerConn, error) { + cn, err := DialOpen(d, name) + if err != nil { + return nil, err + } + + l := &ListenerConn{ + cn: cn.(*conn), + notificationChan: c, + connState: connStateIdle, + replyChan: make(chan message, 2), + } + + go l.listenerConnMain() + return l, nil +} + +// We can only allow one goroutine at a time to be running a query on the +// connection for various reasons, so the goroutine sending on the connection +// must be holding senderLock. +// +// Returns an error if an unrecoverable error has occurred and the ListenerConn +// should be abandoned. +func (l *ListenerConn) acquireSenderLock() error { + // we must acquire senderLock first to avoid deadlocks; see ExecSimpleQuery + l.senderLock.Lock() + + l.connectionLock.Lock() + err := l.err + l.connectionLock.Unlock() + if err != nil { + l.senderLock.Unlock() + return err + } + return nil +} + +func (l *ListenerConn) releaseSenderLock() { + l.senderLock.Unlock() +} + +// setState advances the protocol state to newState. Returns false if moving +// to that state from the current state is not allowed. +func (l *ListenerConn) setState(newState int32) bool { + var expectedState int32 + + switch newState { + case connStateIdle: + expectedState = connStateExpectReadyForQuery + case connStateExpectResponse: + expectedState = connStateIdle + case connStateExpectReadyForQuery: + expectedState = connStateExpectResponse + default: + panic(fmt.Sprintf("unexpected listenerConnState %d", newState)) + } + + return atomic.CompareAndSwapInt32(&l.connState, expectedState, newState) +} + +// Main logic is here: receive messages from the postgres backend, forward +// notifications and query replies and keep the internal state in sync with the +// protocol state. Returns when the connection has been lost, is about to go +// away or should be discarded because we couldn't agree on the state with the +// server backend. +func (l *ListenerConn) listenerConnLoop() (err error) { + r := &readBuf{} + for { + t, err := l.cn.recvMessage(r) + if err != nil { + return err + } + + switch t { + case proto.NotificationResponse: + // recvNotification copies all the data so we don't need to worry + // about the scratch buffer being overwritten. + l.notificationChan <- recvNotification(r) + + case proto.RowDescription, proto.DataRow: + // only used by tests; ignore + + case proto.ErrorResponse: + // We might receive an ErrorResponse even when not in a query; it + // is expected that the server will close the connection after + // that, but we should make sure that the error we display is the + // one from the stray ErrorResponse, not io.ErrUnexpectedEOF. + if !l.setState(connStateExpectReadyForQuery) { + return parseError(r, "") + } + l.replyChan <- message{t, parseError(r, "")} + + case proto.CommandComplete, proto.EmptyQueryResponse: + if !l.setState(connStateExpectReadyForQuery) { + // protocol out of sync + return fmt.Errorf("unexpected CommandComplete") + } + // ExecSimpleQuery doesn't need to know about this message + + case proto.ReadyForQuery: + if !l.setState(connStateIdle) { + // protocol out of sync + return fmt.Errorf("unexpected ReadyForQuery") + } + l.replyChan <- message{t, nil} + + case proto.ParameterStatus: + // ignore + case proto.NoticeResponse: + if n := l.cn.noticeHandler; n != nil { + n(parseError(r, "")) + } + default: + return fmt.Errorf("unexpected message %q from server in listenerConnLoop", t) + } + } +} + +// This is the main routine for the goroutine receiving on the database +// connection. Most of the main logic is in listenerConnLoop. +func (l *ListenerConn) listenerConnMain() { + err := l.listenerConnLoop() + + // listenerConnLoop terminated; we're done, but we still have to clean up. + // Make sure nobody tries to start any new queries by making sure the err + // pointer is set. It is important that we do not overwrite its value; a + // connection could be closed by either this goroutine or one sending on the + // connection – whoever closes the connection is assumed to have the more + // meaningful error message (as the other one will probably get + // net.errClosed), so that goroutine sets the error we expose while the + // other error is discarded. If the connection is lost while two goroutines + // are operating on the socket, it probably doesn't matter which error we + // expose so we don't try to do anything more complex. + l.connectionLock.Lock() + if l.err == nil { + l.err = err + } + _ = l.cn.Close() + l.connectionLock.Unlock() + + // There might be a query in-flight; make sure nobody's waiting for a + // response to it, since there's not going to be one. + close(l.replyChan) + + // let the listener know we're done + close(l.notificationChan) + + // this ListenerConn is done +} + +// Listen sends a LISTEN query to the server. See ExecSimpleQuery. +func (l *ListenerConn) Listen(channel string) (bool, error) { + return l.ExecSimpleQuery("LISTEN " + QuoteIdentifier(channel)) +} + +// Unlisten sends an UNLISTEN query to the server. See ExecSimpleQuery. +func (l *ListenerConn) Unlisten(channel string) (bool, error) { + return l.ExecSimpleQuery("UNLISTEN " + QuoteIdentifier(channel)) +} + +// UnlistenAll sends an `UNLISTEN *` query to the server. See ExecSimpleQuery. +func (l *ListenerConn) UnlistenAll() (bool, error) { + return l.ExecSimpleQuery("UNLISTEN *") +} + +// Ping the remote server to make sure it's alive. Non-nil error means the +// connection has failed and should be abandoned. +func (l *ListenerConn) Ping() error { + sent, err := l.ExecSimpleQuery("") + if !sent { + return err + } + if err != nil { // shouldn't happen + panic(err) + } + return nil +} + +// Attempt to send a query on the connection. Returns an error if sending the +// query failed, and the caller should initiate closure of this connection. The +// caller must be holding senderLock (see acquireSenderLock and +// releaseSenderLock). +func (l *ListenerConn) sendSimpleQuery(q string) (err error) { + // Must set connection state before sending the query + if !l.setState(connStateExpectResponse) { + return errors.New("pq: two queries running at the same time") + } + + // Can't use l.cn.writeBuf here because it uses the scratch buffer which + // might get overwritten by listenerConnLoop. + b := &writeBuf{ + buf: []byte("Q\x00\x00\x00\x00"), + pos: 1, + } + b.string(q) + return l.cn.send(b) +} + +// ExecSimpleQuery executes a "simple query" (i.e. one with no bindable +// parameters) on the connection. The possible return values are: +// 1. "executed" is true; the query was executed to completion on the database +// server. If the query failed, err will be set to the error returned by the +// database, otherwise err will be nil. +// 2. If "executed" is false, the query could not be executed on the remote +// server. err will be non-nil. +// +// After a call to ExecSimpleQuery has returned an executed=false value, the +// connection has either been closed or will be closed shortly thereafter, and +// all subsequently executed queries will return an error. +func (l *ListenerConn) ExecSimpleQuery(q string) (executed bool, err error) { + if err = l.acquireSenderLock(); err != nil { + return false, err + } + defer l.releaseSenderLock() + + err = l.sendSimpleQuery(q) + if err != nil { + // We can't know what state the protocol is in, so we need to abandon + // this connection. + l.connectionLock.Lock() + // Set the error pointer if it hasn't been set already; see + // listenerConnMain. + if l.err == nil { + l.err = err + } + l.connectionLock.Unlock() + _ = l.cn.c.Close() + return false, err + } + + // now we just wait for a reply.. + for { + m, ok := <-l.replyChan + if !ok { + // We lost the connection to server, don't bother waiting for a + // a response. err should have been set already. + l.connectionLock.Lock() + err := l.err + l.connectionLock.Unlock() + return false, err + } + switch m.typ { + case proto.ReadyForQuery: + // sanity check + if m.err != nil { + panic("m.err != nil") + } + // done; err might or might not be set + return true, err + + case proto.ErrorResponse: + // sanity check + if m.err == nil { + panic("m.err == nil") + } + // server responded with an error; ReadyForQuery to follow + err = m.err + + default: + return false, fmt.Errorf("unknown response for simple query: %q", m.typ) + } + } +} + +// Close closes the connection. +func (l *ListenerConn) Close() error { + l.connectionLock.Lock() + if l.err != nil { + l.connectionLock.Unlock() + return errListenerConnClosed + } + l.err = errListenerConnClosed + l.connectionLock.Unlock() + // We can't send anything on the connection without holding senderLock. + // Simply close the net.Conn to wake up everyone operating on it. + return l.cn.c.Close() +} + +// Err returns the reason the connection was closed. It is not safe to call +// this function until l.Notify has been closed. +func (l *ListenerConn) Err() error { + return l.err +} + +// ErrChannelAlreadyOpen is returned from Listen when a channel is already +// open. +var ErrChannelAlreadyOpen = errors.New("pq: channel is already open") + +// ErrChannelNotOpen is returned from Unlisten when a channel is not open. +var ErrChannelNotOpen = errors.New("pq: channel is not open") + +// ListenerEventType is an enumeration of listener event types. +type ListenerEventType int + +const ( + // ListenerEventConnected is emitted only when the database connection has + // been initially initialized. The err argument of the callback will always + // be nil. + ListenerEventConnected ListenerEventType = iota + + // ListenerEventDisconnected is emitted after a database connection has been + // lost, either because of an error or because Close has been called. The + // err argument will be set to the reason the database connection was lost. + ListenerEventDisconnected + + // ListenerEventReconnected is emitted after a database connection has been + // re-established after connection loss. The err argument of the callback + // will always be nil. After this event has been emitted, a nil + // pq.Notification is sent on the Listener.Notify channel. + ListenerEventReconnected + + // ListenerEventConnectionAttemptFailed is emitted after a connection to the + // database was attempted, but failed. The err argument will be set to an + // error describing why the connection attempt did not succeed. + ListenerEventConnectionAttemptFailed +) + +// EventCallbackType is the event callback type. See also ListenerEventType +// constants' documentation. +type EventCallbackType func(event ListenerEventType, err error) + +func (l ListenerEventType) String() string { + return map[ListenerEventType]string{ + ListenerEventConnected: "connected", + ListenerEventDisconnected: "disconnected", + ListenerEventReconnected: "reconnected", + ListenerEventConnectionAttemptFailed: "connectionAttemptFailed", + }[l] +} + +// Listener provides an interface for listening to notifications from a +// PostgreSQL database. For general usage information, see section +// "Notifications". +// +// Listener can safely be used from concurrently running goroutines. +type Listener struct { + // Channel for receiving notifications from the database. In some cases a + // nil value will be sent. See section "Notifications" above. + Notify chan *Notification + + dsn string + minReconnectInterval time.Duration + maxReconnectInterval time.Duration + dialer Dialer + eventCallback EventCallbackType + + lock sync.Mutex + isClosed bool + reconnectCond *sync.Cond + cn *ListenerConn + connNotificationChan <-chan *Notification + channels map[string]struct{} +} + +// NewListener creates a new database connection dedicated to LISTEN / NOTIFY. +// +// name should be set to a connection string to be used to establish the +// database connection (see section "Connection String Parameters" above). +// +// minReconnect controls the duration to wait before trying to re-establish the +// database connection after connection loss. After each consecutive failure +// this interval is doubled, until maxReconnect is reached. Successfully +// completing the connection establishment procedure resets the interval back to +// minReconnect. +// +// The last parameter cb can be set to a function which will be called by the +// Listener when the state of the underlying database connection changes. This +// callback will be called by the goroutine which dispatches the notifications +// over the Notify channel, so you should try to avoid doing potentially +// time-consuming operations from the callback. +func NewListener(dsn string, minReconnect, maxReconnect time.Duration, cb EventCallbackType) *Listener { + return NewDialListener(defaultDialer{}, dsn, minReconnect, maxReconnect, cb) +} + +// NewDialListener is like NewListener but it takes a Dialer. +func NewDialListener(d Dialer, dsn string, minReconnect, maxReconnect time.Duration, cb EventCallbackType) *Listener { + l := &Listener{ + dsn: dsn, + minReconnectInterval: minReconnect, + maxReconnectInterval: maxReconnect, + dialer: d, + eventCallback: cb, + channels: make(map[string]struct{}), + Notify: make(chan *Notification, 32), + } + l.reconnectCond = sync.NewCond(&l.lock) + go l.listenerMain() + return l +} + +// NotificationChannel returns the notification channel for this listener. This +// is the same channel as Notify, and will not be recreated during the life time +// of the Listener. +func (l *Listener) NotificationChannel() <-chan *Notification { + return l.Notify +} + +// Listen starts listening for notifications on a channel. Calls to this +// function will block until an acknowledgement has been received from the +// server. Note that Listener automatically re-establishes the connection after +// connection loss, so this function may block indefinitely if the connection +// can not be re-established. +// +// Listen will only fail in three conditions: +// 1. The channel is already open. The returned error will be +// [ErrChannelAlreadyOpen]. +// 2. The query was executed on the remote server, but PostgreSQL returned an +// error message in response to the query. The returned error will be a +// [pq.Error] containing the information the server supplied. +// 3. Close is called on the Listener before the request could be completed. +// +// The channel name is case-sensitive. +func (l *Listener) Listen(channel string) error { + l.lock.Lock() + defer l.lock.Unlock() + if l.isClosed { + return net.ErrClosed + } + + // The server allows you to issue a LISTEN on a channel which is already + // open, but it seems useful to be able to detect this case to spot for + // mistakes in application logic. If the application genuinely does't care, + // it can check the exported error and ignore it. + _, exists := l.channels[channel] + if exists { + return ErrChannelAlreadyOpen + } + + if l.cn != nil { + // If resp is true but error is set then the query was executed on the + // remote server but resulted in an error. This should be relatively + // rare, so it's fine if we just pass the error to our caller. + // If resp is false then we could not complete the query on the remote + // server and our underlying connection is about to go away, so we only + // add relname to l.channels, and wait for resync() to take care of the + // rest. + resp, err := l.cn.Listen(channel) + if resp && err != nil { + return err + } + } + + l.channels[channel] = struct{}{} + for l.cn == nil { + l.reconnectCond.Wait() + // we let go of the mutex for a while + if l.isClosed { + return net.ErrClosed + } + } + + return nil +} + +// Unlisten removes a channel from the Listener's channel list. Returns +// ErrChannelNotOpen if the Listener is not listening on the specified channel. +// Returns immediately with no error if there is no connection. Note that you +// might still get notifications for this channel even after Unlisten has +// returned. +// +// The channel name is case-sensitive. +func (l *Listener) Unlisten(channel string) error { + l.lock.Lock() + defer l.lock.Unlock() + + if l.isClosed { + return net.ErrClosed + } + + // Similarly to LISTEN, this is not an error in Postgres, but it seems + // useful to distinguish from the normal conditions. + _, exists := l.channels[channel] + if !exists { + return ErrChannelNotOpen + } + + if l.cn != nil { + // Similarly to Listen (see comment there), the caller should only be + // bothered with an error if it came from the backend as a response to + // our query. + resp, err := l.cn.Unlisten(channel) + if resp && err != nil { + return err + } + } + + // Don't bother waiting for resync if there's no connection. + delete(l.channels, channel) + return nil +} + +// UnlistenAll removes all channels from the Listener's channel list. Returns +// immediately with no error if there is no connection. Note that you might +// still get notifications for any of the deleted channels even after +// UnlistenAll has returned. +func (l *Listener) UnlistenAll() error { + l.lock.Lock() + defer l.lock.Unlock() + + if l.isClosed { + return net.ErrClosed + } + + if l.cn != nil { + // Similarly to Listen (see comment in that function), the caller + // should only be bothered with an error if it came from the backend as + // a response to our query. + gotResponse, err := l.cn.UnlistenAll() + if gotResponse && err != nil { + return err + } + } + + // Don't bother waiting for resync if there's no connection. + l.channels = make(map[string]struct{}) + return nil +} + +// Ping the remote server to make sure it's alive. Non-nil return value means +// that there is no active connection. +func (l *Listener) Ping() error { + l.lock.Lock() + defer l.lock.Unlock() + + if l.isClosed { + return net.ErrClosed + } + if l.cn == nil { + return errors.New("no connection") + } + + return l.cn.Ping() +} + +// Clean up after losing the server connection. Returns l.cn.Err(), which should +// have the reason the connection was lost. +func (l *Listener) disconnectCleanup() error { + l.lock.Lock() + defer l.lock.Unlock() + + // sanity check; can't look at Err() until the channel has been closed + select { + case _, ok := <-l.connNotificationChan: + if ok { + panic("connNotificationChan not closed") + } + default: + panic("connNotificationChan not closed") + } + + err := l.cn.Err() + _ = l.cn.Close() + l.cn = nil + return err +} + +// Synchronize the list of channels we want to be listening on with the server +// after the connection has been established. +func (l *Listener) resync(cn *ListenerConn, notificationChan <-chan *Notification) error { + doneChan := make(chan error) + go func(notificationChan <-chan *Notification) { + for channel := range l.channels { + // If we got a response, return that error to our caller as it's + // going to be more descriptive than cn.Err(). + gotResponse, err := cn.Listen(channel) + if gotResponse && err != nil { + doneChan <- err + return + } + + // If we couldn't reach the server, wait for notificationChan to + // close and then return the error message from the connection, as + // per ListenerConn's interface. + if err != nil { + for range notificationChan { + } + doneChan <- cn.Err() + return + } + } + doneChan <- nil + }(notificationChan) + + // Ignore notifications while synchronization is going on to avoid + // deadlocks. We have to send a nil notification over Notify anyway as we + // can't possibly know which notifications (if any) were lost while the + // connection was down, so there's no reason to try and process these + // messages at all. + for { + select { + case _, ok := <-notificationChan: + if !ok { + notificationChan = nil + } + + case err := <-doneChan: + return err + } + } +} + +// caller should NOT be holding l.lock +func (l *Listener) closed() bool { + l.lock.Lock() + defer l.lock.Unlock() + + return l.isClosed +} + +func (l *Listener) connect() error { + l.lock.Lock() + defer l.lock.Unlock() + if l.isClosed { + return net.ErrClosed + } + + notificationChan := make(chan *Notification, 32) + + var err error + l.cn, err = newDialListenerConn(l.dialer, l.dsn, notificationChan) + if err != nil { + return err + } + + err = l.resync(l.cn, notificationChan) + if err != nil { + _ = l.cn.Close() + return err + } + + l.connNotificationChan = notificationChan + l.reconnectCond.Broadcast() + return nil +} + +// Close disconnects the Listener from the database and shuts it down. +// Subsequent calls to its methods will return an error. Close returns an error +// if the connection has already been closed. +func (l *Listener) Close() error { + l.lock.Lock() + defer l.lock.Unlock() + + if l.isClosed { + return net.ErrClosed + } + + if l.cn != nil { + _ = l.cn.Close() + } + l.isClosed = true + + // Unblock calls to Listen() + l.reconnectCond.Broadcast() + + return nil +} + +func (l *Listener) emitEvent(event ListenerEventType, err error) { + if l.eventCallback != nil { + l.eventCallback(event, err) + } +} + +// Main logic here: maintain a connection to the server when possible, wait +// for notifications and emit events. +func (l *Listener) listenerConnLoop() { + var ( + nextReconnect time.Time + reconnectInterval = l.minReconnectInterval + ) + for { + for { + err := l.connect() + if err == nil { + break + } + if l.closed() { + return + } + + l.emitEvent(ListenerEventConnectionAttemptFailed, err) + time.Sleep(reconnectInterval) + reconnectInterval *= 2 + if reconnectInterval > l.maxReconnectInterval { + reconnectInterval = l.maxReconnectInterval + } + } + + if nextReconnect.IsZero() { + l.emitEvent(ListenerEventConnected, nil) + } else { + l.emitEvent(ListenerEventReconnected, nil) + l.Notify <- nil + } + + reconnectInterval = l.minReconnectInterval + nextReconnect = time.Now().Add(reconnectInterval) + + for { + notification, ok := <-l.connNotificationChan + if !ok { // lost connection, loop again + break + } + l.Notify <- notification + } + + err := l.disconnectCleanup() + if l.closed() { + return + } + l.emitEvent(ListenerEventDisconnected, err) + + time.Sleep(time.Until(nextReconnect)) + } +} + +func (l *Listener) listenerMain() { + l.listenerConnLoop() + close(l.Notify) +} diff --git a/vendor/github.com/lib/pq/oid/doc.go b/vendor/github.com/lib/pq/oid/doc.go new file mode 100644 index 0000000..a486506 --- /dev/null +++ b/vendor/github.com/lib/pq/oid/doc.go @@ -0,0 +1,7 @@ +//go:generate go run ./gen.go + +// Package oid contains OID constants as defined by the Postgres server. +package oid + +// Oid is a Postgres Object ID. +type Oid uint32 diff --git a/vendor/github.com/lib/pq/oid/types.go b/vendor/github.com/lib/pq/oid/types.go new file mode 100644 index 0000000..ecc84c2 --- /dev/null +++ b/vendor/github.com/lib/pq/oid/types.go @@ -0,0 +1,343 @@ +// Code generated by gen.go. DO NOT EDIT. + +package oid + +const ( + T_bool Oid = 16 + T_bytea Oid = 17 + T_char Oid = 18 + T_name Oid = 19 + T_int8 Oid = 20 + T_int2 Oid = 21 + T_int2vector Oid = 22 + T_int4 Oid = 23 + T_regproc Oid = 24 + T_text Oid = 25 + T_oid Oid = 26 + T_tid Oid = 27 + T_xid Oid = 28 + T_cid Oid = 29 + T_oidvector Oid = 30 + T_pg_ddl_command Oid = 32 + T_pg_type Oid = 71 + T_pg_attribute Oid = 75 + T_pg_proc Oid = 81 + T_pg_class Oid = 83 + T_json Oid = 114 + T_xml Oid = 142 + T__xml Oid = 143 + T_pg_node_tree Oid = 194 + T__json Oid = 199 + T_smgr Oid = 210 + T_index_am_handler Oid = 325 + T_point Oid = 600 + T_lseg Oid = 601 + T_path Oid = 602 + T_box Oid = 603 + T_polygon Oid = 604 + T_line Oid = 628 + T__line Oid = 629 + T_cidr Oid = 650 + T__cidr Oid = 651 + T_float4 Oid = 700 + T_float8 Oid = 701 + T_abstime Oid = 702 + T_reltime Oid = 703 + T_tinterval Oid = 704 + T_unknown Oid = 705 + T_circle Oid = 718 + T__circle Oid = 719 + T_money Oid = 790 + T__money Oid = 791 + T_macaddr Oid = 829 + T_inet Oid = 869 + T__bool Oid = 1000 + T__bytea Oid = 1001 + T__char Oid = 1002 + T__name Oid = 1003 + T__int2 Oid = 1005 + T__int2vector Oid = 1006 + T__int4 Oid = 1007 + T__regproc Oid = 1008 + T__text Oid = 1009 + T__tid Oid = 1010 + T__xid Oid = 1011 + T__cid Oid = 1012 + T__oidvector Oid = 1013 + T__bpchar Oid = 1014 + T__varchar Oid = 1015 + T__int8 Oid = 1016 + T__point Oid = 1017 + T__lseg Oid = 1018 + T__path Oid = 1019 + T__box Oid = 1020 + T__float4 Oid = 1021 + T__float8 Oid = 1022 + T__abstime Oid = 1023 + T__reltime Oid = 1024 + T__tinterval Oid = 1025 + T__polygon Oid = 1027 + T__oid Oid = 1028 + T_aclitem Oid = 1033 + T__aclitem Oid = 1034 + T__macaddr Oid = 1040 + T__inet Oid = 1041 + T_bpchar Oid = 1042 + T_varchar Oid = 1043 + T_date Oid = 1082 + T_time Oid = 1083 + T_timestamp Oid = 1114 + T__timestamp Oid = 1115 + T__date Oid = 1182 + T__time Oid = 1183 + T_timestamptz Oid = 1184 + T__timestamptz Oid = 1185 + T_interval Oid = 1186 + T__interval Oid = 1187 + T__numeric Oid = 1231 + T_pg_database Oid = 1248 + T__cstring Oid = 1263 + T_timetz Oid = 1266 + T__timetz Oid = 1270 + T_bit Oid = 1560 + T__bit Oid = 1561 + T_varbit Oid = 1562 + T__varbit Oid = 1563 + T_numeric Oid = 1700 + T_refcursor Oid = 1790 + T__refcursor Oid = 2201 + T_regprocedure Oid = 2202 + T_regoper Oid = 2203 + T_regoperator Oid = 2204 + T_regclass Oid = 2205 + T_regtype Oid = 2206 + T__regprocedure Oid = 2207 + T__regoper Oid = 2208 + T__regoperator Oid = 2209 + T__regclass Oid = 2210 + T__regtype Oid = 2211 + T_record Oid = 2249 + T_cstring Oid = 2275 + T_any Oid = 2276 + T_anyarray Oid = 2277 + T_void Oid = 2278 + T_trigger Oid = 2279 + T_language_handler Oid = 2280 + T_internal Oid = 2281 + T_opaque Oid = 2282 + T_anyelement Oid = 2283 + T__record Oid = 2287 + T_anynonarray Oid = 2776 + T_pg_authid Oid = 2842 + T_pg_auth_members Oid = 2843 + T__txid_snapshot Oid = 2949 + T_uuid Oid = 2950 + T__uuid Oid = 2951 + T_txid_snapshot Oid = 2970 + T_fdw_handler Oid = 3115 + T_pg_lsn Oid = 3220 + T__pg_lsn Oid = 3221 + T_tsm_handler Oid = 3310 + T_anyenum Oid = 3500 + T_tsvector Oid = 3614 + T_tsquery Oid = 3615 + T_gtsvector Oid = 3642 + T__tsvector Oid = 3643 + T__gtsvector Oid = 3644 + T__tsquery Oid = 3645 + T_regconfig Oid = 3734 + T__regconfig Oid = 3735 + T_regdictionary Oid = 3769 + T__regdictionary Oid = 3770 + T_jsonb Oid = 3802 + T__jsonb Oid = 3807 + T_anyrange Oid = 3831 + T_event_trigger Oid = 3838 + T_int4range Oid = 3904 + T__int4range Oid = 3905 + T_numrange Oid = 3906 + T__numrange Oid = 3907 + T_tsrange Oid = 3908 + T__tsrange Oid = 3909 + T_tstzrange Oid = 3910 + T__tstzrange Oid = 3911 + T_daterange Oid = 3912 + T__daterange Oid = 3913 + T_int8range Oid = 3926 + T__int8range Oid = 3927 + T_pg_shseclabel Oid = 4066 + T_regnamespace Oid = 4089 + T__regnamespace Oid = 4090 + T_regrole Oid = 4096 + T__regrole Oid = 4097 +) + +var TypeName = map[Oid]string{ + T_bool: "BOOL", + T_bytea: "BYTEA", + T_char: "CHAR", + T_name: "NAME", + T_int8: "INT8", + T_int2: "INT2", + T_int2vector: "INT2VECTOR", + T_int4: "INT4", + T_regproc: "REGPROC", + T_text: "TEXT", + T_oid: "OID", + T_tid: "TID", + T_xid: "XID", + T_cid: "CID", + T_oidvector: "OIDVECTOR", + T_pg_ddl_command: "PG_DDL_COMMAND", + T_pg_type: "PG_TYPE", + T_pg_attribute: "PG_ATTRIBUTE", + T_pg_proc: "PG_PROC", + T_pg_class: "PG_CLASS", + T_json: "JSON", + T_xml: "XML", + T__xml: "_XML", + T_pg_node_tree: "PG_NODE_TREE", + T__json: "_JSON", + T_smgr: "SMGR", + T_index_am_handler: "INDEX_AM_HANDLER", + T_point: "POINT", + T_lseg: "LSEG", + T_path: "PATH", + T_box: "BOX", + T_polygon: "POLYGON", + T_line: "LINE", + T__line: "_LINE", + T_cidr: "CIDR", + T__cidr: "_CIDR", + T_float4: "FLOAT4", + T_float8: "FLOAT8", + T_abstime: "ABSTIME", + T_reltime: "RELTIME", + T_tinterval: "TINTERVAL", + T_unknown: "UNKNOWN", + T_circle: "CIRCLE", + T__circle: "_CIRCLE", + T_money: "MONEY", + T__money: "_MONEY", + T_macaddr: "MACADDR", + T_inet: "INET", + T__bool: "_BOOL", + T__bytea: "_BYTEA", + T__char: "_CHAR", + T__name: "_NAME", + T__int2: "_INT2", + T__int2vector: "_INT2VECTOR", + T__int4: "_INT4", + T__regproc: "_REGPROC", + T__text: "_TEXT", + T__tid: "_TID", + T__xid: "_XID", + T__cid: "_CID", + T__oidvector: "_OIDVECTOR", + T__bpchar: "_BPCHAR", + T__varchar: "_VARCHAR", + T__int8: "_INT8", + T__point: "_POINT", + T__lseg: "_LSEG", + T__path: "_PATH", + T__box: "_BOX", + T__float4: "_FLOAT4", + T__float8: "_FLOAT8", + T__abstime: "_ABSTIME", + T__reltime: "_RELTIME", + T__tinterval: "_TINTERVAL", + T__polygon: "_POLYGON", + T__oid: "_OID", + T_aclitem: "ACLITEM", + T__aclitem: "_ACLITEM", + T__macaddr: "_MACADDR", + T__inet: "_INET", + T_bpchar: "BPCHAR", + T_varchar: "VARCHAR", + T_date: "DATE", + T_time: "TIME", + T_timestamp: "TIMESTAMP", + T__timestamp: "_TIMESTAMP", + T__date: "_DATE", + T__time: "_TIME", + T_timestamptz: "TIMESTAMPTZ", + T__timestamptz: "_TIMESTAMPTZ", + T_interval: "INTERVAL", + T__interval: "_INTERVAL", + T__numeric: "_NUMERIC", + T_pg_database: "PG_DATABASE", + T__cstring: "_CSTRING", + T_timetz: "TIMETZ", + T__timetz: "_TIMETZ", + T_bit: "BIT", + T__bit: "_BIT", + T_varbit: "VARBIT", + T__varbit: "_VARBIT", + T_numeric: "NUMERIC", + T_refcursor: "REFCURSOR", + T__refcursor: "_REFCURSOR", + T_regprocedure: "REGPROCEDURE", + T_regoper: "REGOPER", + T_regoperator: "REGOPERATOR", + T_regclass: "REGCLASS", + T_regtype: "REGTYPE", + T__regprocedure: "_REGPROCEDURE", + T__regoper: "_REGOPER", + T__regoperator: "_REGOPERATOR", + T__regclass: "_REGCLASS", + T__regtype: "_REGTYPE", + T_record: "RECORD", + T_cstring: "CSTRING", + T_any: "ANY", + T_anyarray: "ANYARRAY", + T_void: "VOID", + T_trigger: "TRIGGER", + T_language_handler: "LANGUAGE_HANDLER", + T_internal: "INTERNAL", + T_opaque: "OPAQUE", + T_anyelement: "ANYELEMENT", + T__record: "_RECORD", + T_anynonarray: "ANYNONARRAY", + T_pg_authid: "PG_AUTHID", + T_pg_auth_members: "PG_AUTH_MEMBERS", + T__txid_snapshot: "_TXID_SNAPSHOT", + T_uuid: "UUID", + T__uuid: "_UUID", + T_txid_snapshot: "TXID_SNAPSHOT", + T_fdw_handler: "FDW_HANDLER", + T_pg_lsn: "PG_LSN", + T__pg_lsn: "_PG_LSN", + T_tsm_handler: "TSM_HANDLER", + T_anyenum: "ANYENUM", + T_tsvector: "TSVECTOR", + T_tsquery: "TSQUERY", + T_gtsvector: "GTSVECTOR", + T__tsvector: "_TSVECTOR", + T__gtsvector: "_GTSVECTOR", + T__tsquery: "_TSQUERY", + T_regconfig: "REGCONFIG", + T__regconfig: "_REGCONFIG", + T_regdictionary: "REGDICTIONARY", + T__regdictionary: "_REGDICTIONARY", + T_jsonb: "JSONB", + T__jsonb: "_JSONB", + T_anyrange: "ANYRANGE", + T_event_trigger: "EVENT_TRIGGER", + T_int4range: "INT4RANGE", + T__int4range: "_INT4RANGE", + T_numrange: "NUMRANGE", + T__numrange: "_NUMRANGE", + T_tsrange: "TSRANGE", + T__tsrange: "_TSRANGE", + T_tstzrange: "TSTZRANGE", + T__tstzrange: "_TSTZRANGE", + T_daterange: "DATERANGE", + T__daterange: "_DATERANGE", + T_int8range: "INT8RANGE", + T__int8range: "_INT8RANGE", + T_pg_shseclabel: "PG_SHSECLABEL", + T_regnamespace: "REGNAMESPACE", + T__regnamespace: "_REGNAMESPACE", + T_regrole: "REGROLE", + T__regrole: "_REGROLE", +} diff --git a/vendor/github.com/lib/pq/pqerror/codes.go b/vendor/github.com/lib/pq/pqerror/codes.go new file mode 100644 index 0000000..f557664 --- /dev/null +++ b/vendor/github.com/lib/pq/pqerror/codes.go @@ -0,0 +1,581 @@ +// Code generated by gen.go. DO NOT EDIT. + +// Last updated for PostgreSQL 18.3 + +package pqerror + +var ( + ClassSuccessfulCompletion = Class("00") // Successful Completion + ClassWarning = Class("01") // Warning + ClassNoData = Class("02") // No Data (this is also a warning class per the SQL standard) + ClassSQLStatementNotYetComplete = Class("03") // SQL Statement Not Yet Complete + ClassConnectionException = Class("08") // Connection Exception + ClassTriggeredActionException = Class("09") // Triggered Action Exception + ClassFeatureNotSupported = Class("0A") // Feature Not Supported + ClassInvalidTransactionInitiation = Class("0B") // Invalid Transaction Initiation + ClassLocatorException = Class("0F") // Locator Exception + ClassInvalidGrantor = Class("0L") // Invalid Grantor + ClassInvalidRoleSpecification = Class("0P") // Invalid Role Specification + ClassDiagnosticsException = Class("0Z") // Diagnostics Exception + ClassCaseNotFound = Class("20") // Case Not Found + ClassCardinalityViolation = Class("21") // Cardinality Violation + ClassDataException = Class("22") // Data Exception + ClassIntegrityConstraintViolation = Class("23") // Integrity Constraint Violation + ClassInvalidCursorState = Class("24") // Invalid Cursor State + ClassInvalidTransactionState = Class("25") // Invalid Transaction State + ClassInvalidSQLStatementName = Class("26") // Invalid SQL Statement Name + ClassTriggeredDataChangeViolation = Class("27") // Triggered Data Change Violation + ClassInvalidAuthorizationSpecification = Class("28") // Invalid Authorization Specification + ClassDependentPrivilegeDescriptorsStillExist = Class("2B") // Dependent Privilege Descriptors Still Exist + ClassInvalidTransactionTermination = Class("2D") // Invalid Transaction Termination + ClassSQLRoutineException = Class("2F") // SQL Routine Exception + ClassInvalidCursorName = Class("34") // Invalid Cursor Name + ClassExternalRoutineException = Class("38") // External Routine Exception + ClassExternalRoutineInvocationException = Class("39") // External Routine Invocation Exception + ClassSavepointException = Class("3B") // Savepoint Exception + ClassInvalidCatalogName = Class("3D") // Invalid Catalog Name + ClassInvalidSchemaName = Class("3F") // Invalid Schema Name + ClassTransactionRollback = Class("40") // Transaction Rollback + ClassSyntaxErrorOrAccessRuleViolation = Class("42") // Syntax Error or Access Rule Violation + ClassWithCheckOptionViolation = Class("44") // WITH CHECK OPTION Violation + ClassInsufficientResources = Class("53") // Insufficient Resources + ClassProgramLimitExceeded = Class("54") // Program Limit Exceeded + ClassObjectNotInPrerequisiteState = Class("55") // Object Not In Prerequisite State + ClassOperatorIntervention = Class("57") // Operator Intervention + ClassSystemError = Class("58") // System Error (errors external to PostgreSQL itself) + ClassConfigFileError = Class("F0") // Configuration File Error + ClassFDWError = Class("HV") // Foreign Data Wrapper Error (SQL/MED) + ClassPLpgSQLError = Class("P0") // PL/pgSQL Error + ClassInternalError = Class("XX") // Internal Error +) + +// A list of all error codes used in PostgreSQL. +var ( + SuccessfulCompletion = Code("00000") // Class 00 - Successful Completion + Warning = Code("01000") // Class 01 - Warning + WarningDynamicResultSetsReturned = Code("0100C") + WarningImplicitZeroBitPadding = Code("01008") + WarningNullValueEliminatedInSetFunction = Code("01003") + WarningPrivilegeNotGranted = Code("01007") + WarningPrivilegeNotRevoked = Code("01006") + WarningStringDataRightTruncation = Code("01004") + WarningDeprecatedFeature = Code("01P01") + NoData = Code("02000") // Class 02 - No Data (this is also a warning class per the SQL standard) + NoAdditionalDynamicResultSetsReturned = Code("02001") + SQLStatementNotYetComplete = Code("03000") // Class 03 - SQL Statement Not Yet Complete + ConnectionException = Code("08000") // Class 08 - Connection Exception + ConnectionDoesNotExist = Code("08003") + ConnectionFailure = Code("08006") + SQLClientUnableToEstablishSQLConnection = Code("08001") + SQLServerRejectedEstablishmentOfSQLConnection = Code("08004") + TransactionResolutionUnknown = Code("08007") + ProtocolViolation = Code("08P01") + TriggeredActionException = Code("09000") // Class 09 - Triggered Action Exception + FeatureNotSupported = Code("0A000") // Class 0A - Feature Not Supported + InvalidTransactionInitiation = Code("0B000") // Class 0B - Invalid Transaction Initiation + LocatorException = Code("0F000") // Class 0F - Locator Exception + LEInvalidSpecification = Code("0F001") + InvalidGrantor = Code("0L000") // Class 0L - Invalid Grantor + InvalidGrantOperation = Code("0LP01") + InvalidRoleSpecification = Code("0P000") // Class 0P - Invalid Role Specification + DiagnosticsException = Code("0Z000") // Class 0Z - Diagnostics Exception + StackedDiagnosticsAccessedWithoutActiveHandler = Code("0Z002") + InvalidArgumentForXquery = Code("10608") + CaseNotFound = Code("20000") // Class 20 - Case Not Found + CardinalityViolation = Code("21000") // Class 21 - Cardinality Violation + DataException = Code("22000") // Class 22 - Data Exception + ArraySubscriptError = Code("2202E") + CharacterNotInRepertoire = Code("22021") + DatetimeFieldOverflow = Code("22008") + DivisionByZero = Code("22012") + ErrorInAssignment = Code("22005") + EscapeCharacterConflict = Code("2200B") + IndicatorOverflow = Code("22022") + IntervalFieldOverflow = Code("22015") + InvalidArgumentForLog = Code("2201E") + InvalidArgumentForNtile = Code("22014") + InvalidArgumentForNthValue = Code("22016") + InvalidArgumentForPowerFunction = Code("2201F") + InvalidArgumentForWidthBucketFunction = Code("2201G") + InvalidCharacterValueForCast = Code("22018") + InvalidDatetimeFormat = Code("22007") + InvalidEscapeCharacter = Code("22019") + InvalidEscapeOctet = Code("2200D") + InvalidEscapeSequence = Code("22025") + NonstandardUseOfEscapeCharacter = Code("22P06") + InvalidIndicatorParameterValue = Code("22010") + InvalidParameterValue = Code("22023") + InvalidPrecedingOrFollowingSize = Code("22013") + InvalidRegularExpression = Code("2201B") + InvalidRowCountInLimitClause = Code("2201W") + InvalidRowCountInResultOffsetClause = Code("2201X") + InvalidTablesampleArgument = Code("2202H") + InvalidTablesampleRepeat = Code("2202G") + InvalidTimeZoneDisplacementValue = Code("22009") + InvalidUseOfEscapeCharacter = Code("2200C") + MostSpecificTypeMismatch = Code("2200G") + NullValueNotAllowed = Code("22004") + NullValueNoIndicatorParameter = Code("22002") + NumericValueOutOfRange = Code("22003") + SequenceGeneratorLimitExceeded = Code("2200H") + StringDataLengthMismatch = Code("22026") + StringDataRightTruncation = Code("22001") + SubstringError = Code("22011") + TrimError = Code("22027") + UnterminatedCString = Code("22024") + ZeroLengthCharacterString = Code("2200F") + FloatingPointException = Code("22P01") + InvalidTextRepresentation = Code("22P02") + InvalidBinaryRepresentation = Code("22P03") + BadCopyFileFormat = Code("22P04") + UntranslatableCharacter = Code("22P05") + NotAnXMLDocument = Code("2200L") + InvalidXMLDocument = Code("2200M") + InvalidXMLContent = Code("2200N") + InvalidXMLComment = Code("2200S") + InvalidXMLProcessingInstruction = Code("2200T") + DuplicateJSONObjectKeyValue = Code("22030") + InvalidArgumentForSQLJSONDatetimeFunction = Code("22031") + InvalidJSONText = Code("22032") + InvalidSQLJSONSubscript = Code("22033") + MoreThanOneSQLJSONItem = Code("22034") + NoSQLJSONItem = Code("22035") + NonNumericSQLJSONItem = Code("22036") + NonUniqueKeysInAJSONObject = Code("22037") + SingletonSQLJSONItemRequired = Code("22038") + SQLJSONArrayNotFound = Code("22039") + SQLJSONMemberNotFound = Code("2203A") + SQLJSONNumberNotFound = Code("2203B") + SQLJSONObjectNotFound = Code("2203C") + TooManyJSONArrayElements = Code("2203D") + TooManyJSONObjectMembers = Code("2203E") + SQLJSONScalarRequired = Code("2203F") + SQLJSONItemCannotBeCastToTargetType = Code("2203G") + IntegrityConstraintViolation = Code("23000") // Class 23 - Integrity Constraint Violation + RestrictViolation = Code("23001") + NotNullViolation = Code("23502") + ForeignKeyViolation = Code("23503") + UniqueViolation = Code("23505") + CheckViolation = Code("23514") + ExclusionViolation = Code("23P01") + InvalidCursorState = Code("24000") // Class 24 - Invalid Cursor State + InvalidTransactionState = Code("25000") // Class 25 - Invalid Transaction State + ActiveSQLTransaction = Code("25001") + BranchTransactionAlreadyActive = Code("25002") + HeldCursorRequiresSameIsolationLevel = Code("25008") + InappropriateAccessModeForBranchTransaction = Code("25003") + InappropriateIsolationLevelForBranchTransaction = Code("25004") + NoActiveSQLTransactionForBranchTransaction = Code("25005") + ReadOnlySQLTransaction = Code("25006") + SchemaAndDataStatementMixingNotSupported = Code("25007") + NoActiveSQLTransaction = Code("25P01") + InFailedSQLTransaction = Code("25P02") + IdleInTransactionSessionTimeout = Code("25P03") + TransactionTimeout = Code("25P04") + InvalidSQLStatementName = Code("26000") // Class 26 - Invalid SQL Statement Name + TriggeredDataChangeViolation = Code("27000") // Class 27 - Triggered Data Change Violation + InvalidAuthorizationSpecification = Code("28000") // Class 28 - Invalid Authorization Specification + InvalidPassword = Code("28P01") + DependentPrivilegeDescriptorsStillExist = Code("2B000") // Class 2B - Dependent Privilege Descriptors Still Exist + DependentObjectsStillExist = Code("2BP01") + InvalidTransactionTermination = Code("2D000") // Class 2D - Invalid Transaction Termination + SQLRoutineException = Code("2F000") // Class 2F - SQL Routine Exception + SREFunctionExecutedNoReturnStatement = Code("2F005") + SREModifyingSQLDataNotPermitted = Code("2F002") + SREProhibitedSQLStatementAttempted = Code("2F003") + SREReadingSQLDataNotPermitted = Code("2F004") + InvalidCursorName = Code("34000") // Class 34 - Invalid Cursor Name + ExternalRoutineException = Code("38000") // Class 38 - External Routine Exception + EREContainingSQLNotPermitted = Code("38001") + EREModifyingSQLDataNotPermitted = Code("38002") + EREProhibitedSQLStatementAttempted = Code("38003") + EREReadingSQLDataNotPermitted = Code("38004") + ExternalRoutineInvocationException = Code("39000") // Class 39 - External Routine Invocation Exception + ERIEInvalidSQLSTATEReturned = Code("39001") + ERIENullValueNotAllowed = Code("39004") + ERIETriggerProtocolViolated = Code("39P01") + ERIESrfProtocolViolated = Code("39P02") + ERIEEventTriggerProtocolViolated = Code("39P03") + SavepointException = Code("3B000") // Class 3B - Savepoint Exception + SEInvalidSpecification = Code("3B001") + InvalidCatalogName = Code("3D000") // Class 3D - Invalid Catalog Name + InvalidSchemaName = Code("3F000") // Class 3F - Invalid Schema Name + TransactionRollback = Code("40000") // Class 40 - Transaction Rollback + TRIntegrityConstraintViolation = Code("40002") + TRSerializationFailure = Code("40001") + TRStatementCompletionUnknown = Code("40003") + TRDeadlockDetected = Code("40P01") + SyntaxErrorOrAccessRuleViolation = Code("42000") // Class 42 - Syntax Error or Access Rule Violation + SyntaxError = Code("42601") + InsufficientPrivilege = Code("42501") + CannotCoerce = Code("42846") + GroupingError = Code("42803") + WindowingError = Code("42P20") + InvalidRecursion = Code("42P19") + InvalidForeignKey = Code("42830") + InvalidName = Code("42602") + NameTooLong = Code("42622") + ReservedName = Code("42939") + DatatypeMismatch = Code("42804") + IndeterminateDatatype = Code("42P18") + CollationMismatch = Code("42P21") + IndeterminateCollation = Code("42P22") + WrongObjectType = Code("42809") + GeneratedAlways = Code("428C9") + UndefinedColumn = Code("42703") + UndefinedFunction = Code("42883") + UndefinedTable = Code("42P01") + UndefinedParameter = Code("42P02") + UndefinedObject = Code("42704") + DuplicateColumn = Code("42701") + DuplicateCursor = Code("42P03") + DuplicateDatabase = Code("42P04") + DuplicateFunction = Code("42723") + DuplicatePstatement = Code("42P05") + DuplicateSchema = Code("42P06") + DuplicateTable = Code("42P07") + DuplicateAlias = Code("42712") + DuplicateObject = Code("42710") + AmbiguousColumn = Code("42702") + AmbiguousFunction = Code("42725") + AmbiguousParameter = Code("42P08") + AmbiguousAlias = Code("42P09") + InvalidColumnReference = Code("42P10") + InvalidColumnDefinition = Code("42611") + InvalidCursorDefinition = Code("42P11") + InvalidDatabaseDefinition = Code("42P12") + InvalidFunctionDefinition = Code("42P13") + InvalidPstatementDefinition = Code("42P14") + InvalidSchemaDefinition = Code("42P15") + InvalidTableDefinition = Code("42P16") + InvalidObjectDefinition = Code("42P17") + WithCheckOptionViolation = Code("44000") // Class 44 - WITH CHECK OPTION Violation + InsufficientResources = Code("53000") // Class 53 - Insufficient Resources + DiskFull = Code("53100") + OutOfMemory = Code("53200") + TooManyConnections = Code("53300") + ConfigurationLimitExceeded = Code("53400") + ProgramLimitExceeded = Code("54000") // Class 54 - Program Limit Exceeded + StatementTooComplex = Code("54001") + TooManyColumns = Code("54011") + TooManyArguments = Code("54023") + ObjectNotInPrerequisiteState = Code("55000") // Class 55 - Object Not In Prerequisite State + ObjectInUse = Code("55006") + CantChangeRuntimeParam = Code("55P02") + LockNotAvailable = Code("55P03") + UnsafeNewEnumValueUsage = Code("55P04") + OperatorIntervention = Code("57000") // Class 57 - Operator Intervention + QueryCanceled = Code("57014") + AdminShutdown = Code("57P01") + CrashShutdown = Code("57P02") + CannotConnectNow = Code("57P03") + DatabaseDropped = Code("57P04") + IdleSessionTimeout = Code("57P05") + SystemError = Code("58000") // Class 58 - System Error (errors external to PostgreSQL itself) + IOError = Code("58030") + UndefinedFile = Code("58P01") + DuplicateFile = Code("58P02") + FileNameTooLong = Code("58P03") + ConfigFileError = Code("F0000") // Class F0 - Configuration File Error + LockFileExists = Code("F0001") + FDWError = Code("HV000") // Class HV - Foreign Data Wrapper Error (SQL/MED) + FDWColumnNameNotFound = Code("HV005") + FDWDynamicParameterValueNeeded = Code("HV002") + FDWFunctionSequenceError = Code("HV010") + FDWInconsistentDescriptorInformation = Code("HV021") + FDWInvalidAttributeValue = Code("HV024") + FDWInvalidColumnName = Code("HV007") + FDWInvalidColumnNumber = Code("HV008") + FDWInvalidDataType = Code("HV004") + FDWInvalidDataTypeDescriptors = Code("HV006") + FDWInvalidDescriptorFieldIdentifier = Code("HV091") + FDWInvalidHandle = Code("HV00B") + FDWInvalidOptionIndex = Code("HV00C") + FDWInvalidOptionName = Code("HV00D") + FDWInvalidStringLengthOrBufferLength = Code("HV090") + FDWInvalidStringFormat = Code("HV00A") + FDWInvalidUseOfNullPointer = Code("HV009") + FDWTooManyHandles = Code("HV014") + FDWOutOfMemory = Code("HV001") + FDWNoSchemas = Code("HV00P") + FDWOptionNameNotFound = Code("HV00J") + FDWReplyHandle = Code("HV00K") + FDWSchemaNotFound = Code("HV00Q") + FDWTableNotFound = Code("HV00R") + FDWUnableToCreateExecution = Code("HV00L") + FDWUnableToCreateReply = Code("HV00M") + FDWUnableToEstablishConnection = Code("HV00N") + PLpgSQLError = Code("P0000") // Class P0 - PL/pgSQL Error + RaiseException = Code("P0001") + NoDataFound = Code("P0002") + TooManyRows = Code("P0003") + AssertFailure = Code("P0004") + InternalError = Code("XX000") // Class XX - Internal Error + DataCorrupted = Code("XX001") + IndexCorrupted = Code("XX002") +) + +var errorCodeNames = map[Code]string{ + "00000": "successful_completion", + "01000": "warning", + "0100C": "dynamic_result_sets_returned", + "01008": "implicit_zero_bit_padding", + "01003": "null_value_eliminated_in_set_function", + "01007": "privilege_not_granted", + "01006": "privilege_not_revoked", + "01004": "string_data_right_truncation", + "01P01": "deprecated_feature", + "02000": "no_data", + "02001": "no_additional_dynamic_result_sets_returned", + "03000": "sql_statement_not_yet_complete", + "08000": "connection_exception", + "08003": "connection_does_not_exist", + "08006": "connection_failure", + "08001": "sqlclient_unable_to_establish_sqlconnection", + "08004": "sqlserver_rejected_establishment_of_sqlconnection", + "08007": "transaction_resolution_unknown", + "08P01": "protocol_violation", + "09000": "triggered_action_exception", + "0A000": "feature_not_supported", + "0B000": "invalid_transaction_initiation", + "0F000": "locator_exception", + "0F001": "invalid_locator_specification", + "0L000": "invalid_grantor", + "0LP01": "invalid_grant_operation", + "0P000": "invalid_role_specification", + "0Z000": "diagnostics_exception", + "0Z002": "stacked_diagnostics_accessed_without_active_handler", + "10608": "invalid_argument_for_xquery", + "20000": "case_not_found", + "21000": "cardinality_violation", + "22000": "data_exception", + "2202E": "array_subscript_error", + "22021": "character_not_in_repertoire", + "22008": "datetime_field_overflow", + "22012": "division_by_zero", + "22005": "error_in_assignment", + "2200B": "escape_character_conflict", + "22022": "indicator_overflow", + "22015": "interval_field_overflow", + "2201E": "invalid_argument_for_logarithm", + "22014": "invalid_argument_for_ntile_function", + "22016": "invalid_argument_for_nth_value_function", + "2201F": "invalid_argument_for_power_function", + "2201G": "invalid_argument_for_width_bucket_function", + "22018": "invalid_character_value_for_cast", + "22007": "invalid_datetime_format", + "22019": "invalid_escape_character", + "2200D": "invalid_escape_octet", + "22025": "invalid_escape_sequence", + "22P06": "nonstandard_use_of_escape_character", + "22010": "invalid_indicator_parameter_value", + "22023": "invalid_parameter_value", + "22013": "invalid_preceding_or_following_size", + "2201B": "invalid_regular_expression", + "2201W": "invalid_row_count_in_limit_clause", + "2201X": "invalid_row_count_in_result_offset_clause", + "2202H": "invalid_tablesample_argument", + "2202G": "invalid_tablesample_repeat", + "22009": "invalid_time_zone_displacement_value", + "2200C": "invalid_use_of_escape_character", + "2200G": "most_specific_type_mismatch", + "22004": "null_value_not_allowed", + "22002": "null_value_no_indicator_parameter", + "22003": "numeric_value_out_of_range", + "2200H": "sequence_generator_limit_exceeded", + "22026": "string_data_length_mismatch", + "22001": "string_data_right_truncation", + "22011": "substring_error", + "22027": "trim_error", + "22024": "unterminated_c_string", + "2200F": "zero_length_character_string", + "22P01": "floating_point_exception", + "22P02": "invalid_text_representation", + "22P03": "invalid_binary_representation", + "22P04": "bad_copy_file_format", + "22P05": "untranslatable_character", + "2200L": "not_an_xml_document", + "2200M": "invalid_xml_document", + "2200N": "invalid_xml_content", + "2200S": "invalid_xml_comment", + "2200T": "invalid_xml_processing_instruction", + "22030": "duplicate_json_object_key_value", + "22031": "invalid_argument_for_sql_json_datetime_function", + "22032": "invalid_json_text", + "22033": "invalid_sql_json_subscript", + "22034": "more_than_one_sql_json_item", + "22035": "no_sql_json_item", + "22036": "non_numeric_sql_json_item", + "22037": "non_unique_keys_in_a_json_object", + "22038": "singleton_sql_json_item_required", + "22039": "sql_json_array_not_found", + "2203A": "sql_json_member_not_found", + "2203B": "sql_json_number_not_found", + "2203C": "sql_json_object_not_found", + "2203D": "too_many_json_array_elements", + "2203E": "too_many_json_object_members", + "2203F": "sql_json_scalar_required", + "2203G": "sql_json_item_cannot_be_cast_to_target_type", + "23000": "integrity_constraint_violation", + "23001": "restrict_violation", + "23502": "not_null_violation", + "23503": "foreign_key_violation", + "23505": "unique_violation", + "23514": "check_violation", + "23P01": "exclusion_violation", + "24000": "invalid_cursor_state", + "25000": "invalid_transaction_state", + "25001": "active_sql_transaction", + "25002": "branch_transaction_already_active", + "25008": "held_cursor_requires_same_isolation_level", + "25003": "inappropriate_access_mode_for_branch_transaction", + "25004": "inappropriate_isolation_level_for_branch_transaction", + "25005": "no_active_sql_transaction_for_branch_transaction", + "25006": "read_only_sql_transaction", + "25007": "schema_and_data_statement_mixing_not_supported", + "25P01": "no_active_sql_transaction", + "25P02": "in_failed_sql_transaction", + "25P03": "idle_in_transaction_session_timeout", + "25P04": "transaction_timeout", + "26000": "invalid_sql_statement_name", + "27000": "triggered_data_change_violation", + "28000": "invalid_authorization_specification", + "28P01": "invalid_password", + "2B000": "dependent_privilege_descriptors_still_exist", + "2BP01": "dependent_objects_still_exist", + "2D000": "invalid_transaction_termination", + "2F000": "sql_routine_exception", + "2F005": "function_executed_no_return_statement", + "2F002": "modifying_sql_data_not_permitted", + "2F003": "prohibited_sql_statement_attempted", + "2F004": "reading_sql_data_not_permitted", + "34000": "invalid_cursor_name", + "38000": "external_routine_exception", + "38001": "containing_sql_not_permitted", + "38002": "modifying_sql_data_not_permitted", + "38003": "prohibited_sql_statement_attempted", + "38004": "reading_sql_data_not_permitted", + "39000": "external_routine_invocation_exception", + "39001": "invalid_sqlstate_returned", + "39004": "null_value_not_allowed", + "39P01": "trigger_protocol_violated", + "39P02": "srf_protocol_violated", + "39P03": "event_trigger_protocol_violated", + "3B000": "savepoint_exception", + "3B001": "invalid_savepoint_specification", + "3D000": "invalid_catalog_name", + "3F000": "invalid_schema_name", + "40000": "transaction_rollback", + "40002": "transaction_integrity_constraint_violation", + "40001": "serialization_failure", + "40003": "statement_completion_unknown", + "40P01": "deadlock_detected", + "42000": "syntax_error_or_access_rule_violation", + "42601": "syntax_error", + "42501": "insufficient_privilege", + "42846": "cannot_coerce", + "42803": "grouping_error", + "42P20": "windowing_error", + "42P19": "invalid_recursion", + "42830": "invalid_foreign_key", + "42602": "invalid_name", + "42622": "name_too_long", + "42939": "reserved_name", + "42804": "datatype_mismatch", + "42P18": "indeterminate_datatype", + "42P21": "collation_mismatch", + "42P22": "indeterminate_collation", + "42809": "wrong_object_type", + "428C9": "generated_always", + "42703": "undefined_column", + "42883": "undefined_function", + "42P01": "undefined_table", + "42P02": "undefined_parameter", + "42704": "undefined_object", + "42701": "duplicate_column", + "42P03": "duplicate_cursor", + "42P04": "duplicate_database", + "42723": "duplicate_function", + "42P05": "duplicate_prepared_statement", + "42P06": "duplicate_schema", + "42P07": "duplicate_table", + "42712": "duplicate_alias", + "42710": "duplicate_object", + "42702": "ambiguous_column", + "42725": "ambiguous_function", + "42P08": "ambiguous_parameter", + "42P09": "ambiguous_alias", + "42P10": "invalid_column_reference", + "42611": "invalid_column_definition", + "42P11": "invalid_cursor_definition", + "42P12": "invalid_database_definition", + "42P13": "invalid_function_definition", + "42P14": "invalid_prepared_statement_definition", + "42P15": "invalid_schema_definition", + "42P16": "invalid_table_definition", + "42P17": "invalid_object_definition", + "44000": "with_check_option_violation", + "53000": "insufficient_resources", + "53100": "disk_full", + "53200": "out_of_memory", + "53300": "too_many_connections", + "53400": "configuration_limit_exceeded", + "54000": "program_limit_exceeded", + "54001": "statement_too_complex", + "54011": "too_many_columns", + "54023": "too_many_arguments", + "55000": "object_not_in_prerequisite_state", + "55006": "object_in_use", + "55P02": "cant_change_runtime_param", + "55P03": "lock_not_available", + "55P04": "unsafe_new_enum_value_usage", + "57000": "operator_intervention", + "57014": "query_canceled", + "57P01": "admin_shutdown", + "57P02": "crash_shutdown", + "57P03": "cannot_connect_now", + "57P04": "database_dropped", + "57P05": "idle_session_timeout", + "58000": "system_error", + "58030": "io_error", + "58P01": "undefined_file", + "58P02": "duplicate_file", + "58P03": "file_name_too_long", + "F0000": "config_file_error", + "F0001": "lock_file_exists", + "HV000": "fdw_error", + "HV005": "fdw_column_name_not_found", + "HV002": "fdw_dynamic_parameter_value_needed", + "HV010": "fdw_function_sequence_error", + "HV021": "fdw_inconsistent_descriptor_information", + "HV024": "fdw_invalid_attribute_value", + "HV007": "fdw_invalid_column_name", + "HV008": "fdw_invalid_column_number", + "HV004": "fdw_invalid_data_type", + "HV006": "fdw_invalid_data_type_descriptors", + "HV091": "fdw_invalid_descriptor_field_identifier", + "HV00B": "fdw_invalid_handle", + "HV00C": "fdw_invalid_option_index", + "HV00D": "fdw_invalid_option_name", + "HV090": "fdw_invalid_string_length_or_buffer_length", + "HV00A": "fdw_invalid_string_format", + "HV009": "fdw_invalid_use_of_null_pointer", + "HV014": "fdw_too_many_handles", + "HV001": "fdw_out_of_memory", + "HV00P": "fdw_no_schemas", + "HV00J": "fdw_option_name_not_found", + "HV00K": "fdw_reply_handle", + "HV00Q": "fdw_schema_not_found", + "HV00R": "fdw_table_not_found", + "HV00L": "fdw_unable_to_create_execution", + "HV00M": "fdw_unable_to_create_reply", + "HV00N": "fdw_unable_to_establish_connection", + "P0000": "plpgsql_error", + "P0001": "raise_exception", + "P0002": "no_data_found", + "P0003": "too_many_rows", + "P0004": "assert_failure", + "XX000": "internal_error", + "XX001": "data_corrupted", + "XX002": "index_corrupted", +} diff --git a/vendor/github.com/lib/pq/pqerror/pqerror.go b/vendor/github.com/lib/pq/pqerror/pqerror.go new file mode 100644 index 0000000..29e49e9 --- /dev/null +++ b/vendor/github.com/lib/pq/pqerror/pqerror.go @@ -0,0 +1,35 @@ +//go:generate go run gen.go + +// Package pqerror contains PostgreSQL error codes for use with pq.Error. +package pqerror + +// Code is a five-character error code. +type Code string + +// Name returns a more human friendly rendering of the error code, namely the +// "condition name". +func (ec Code) Name() string { return errorCodeNames[ec] } + +// Class returns the error class, e.g. "28". +func (ec Code) Class() Class { return Class(ec[:2]) } + +// Class is only the class part of an error code. +type Class string + +// Name returns the condition name of an error class. It is equivalent to the +// condition name of the "standard" error code (i.e. the one having the last +// three characters "000"). +func (ec Class) Name() string { return errorCodeNames[Code(ec+"000")] } + +// TODO(v2): use "type Severity string" for the below. + +// Error severity values. +const ( + SeverityFatal = "FATAL" + SeverityPanic = "PANIC" + SeverityWarning = "WARNING" + SeverityNotice = "NOTICE" + SeverityDebug = "DEBUG" + SeverityInfo = "INFO" + SeverityLog = "LOG" +) diff --git a/vendor/github.com/lib/pq/quote.go b/vendor/github.com/lib/pq/quote.go new file mode 100644 index 0000000..909e41e --- /dev/null +++ b/vendor/github.com/lib/pq/quote.go @@ -0,0 +1,71 @@ +package pq + +import ( + "bytes" + "strings" +) + +// QuoteIdentifier quotes an "identifier" (e.g. a table or a column name) to be +// used as part of an SQL statement. For example: +// +// tblname := "my_table" +// data := "my_data" +// quoted := pq.QuoteIdentifier(tblname) +// err := db.Exec(fmt.Sprintf("INSERT INTO %s VALUES ($1)", quoted), data) +// +// Any double quotes in name will be escaped. The quoted identifier will be case +// sensitive when used in a query. If the input string contains a zero byte, the +// result will be truncated immediately before it. +func QuoteIdentifier(name string) string { + end := strings.IndexRune(name, 0) + if end > -1 { + name = name[:end] + } + return `"` + strings.Replace(name, `"`, `""`, -1) + `"` +} + +// BufferQuoteIdentifier satisfies the same purpose as QuoteIdentifier, but backed by a +// byte buffer. +func BufferQuoteIdentifier(name string, buffer *bytes.Buffer) { + // TODO(v2): this should have accepted an io.Writer, not *bytes.Buffer. + end := strings.IndexRune(name, 0) + if end > -1 { + name = name[:end] + } + buffer.WriteRune('"') + buffer.WriteString(strings.Replace(name, `"`, `""`, -1)) + buffer.WriteRune('"') +} + +// QuoteLiteral quotes a 'literal' (e.g. a parameter, often used to pass literal +// to DDL and other statements that do not accept parameters) to be used as part +// of an SQL statement. For example: +// +// exp_date := pq.QuoteLiteral("2023-01-05 15:00:00Z") +// err := db.Exec(fmt.Sprintf("CREATE ROLE my_user VALID UNTIL %s", exp_date)) +// +// Any single quotes in name will be escaped. Any backslashes (i.e. "\") will be +// replaced by two backslashes (i.e. "\\") and the C-style escape identifier +// that PostgreSQL provides ('E') will be prepended to the string. +func QuoteLiteral(literal string) string { + // This follows the PostgreSQL internal algorithm for handling quoted literals + // from libpq, which can be found in the "PQEscapeStringInternal" function, + // which is found in the libpq/fe-exec.c source file: + // https://git.postgresql.org/gitweb/?p=postgresql.git;a=blob;f=src/interfaces/libpq/fe-exec.c + // + // substitute any single-quotes (') with two single-quotes ('') + literal = strings.Replace(literal, `'`, `''`, -1) + // determine if the string has any backslashes (\) in it. + // if it does, replace any backslashes (\) with two backslashes (\\) + // then, we need to wrap the entire string with a PostgreSQL + // C-style escape. Per how "PQEscapeStringInternal" handles this case, we + // also add a space before the "E" + if strings.Contains(literal, `\`) { + literal = strings.Replace(literal, `\`, `\\`, -1) + literal = ` E'` + literal + `'` + } else { + // otherwise, we can just wrap the literal with a pair of single quotes + literal = `'` + literal + `'` + } + return literal +} diff --git a/vendor/github.com/lib/pq/rows.go b/vendor/github.com/lib/pq/rows.go new file mode 100644 index 0000000..2029bfe --- /dev/null +++ b/vendor/github.com/lib/pq/rows.go @@ -0,0 +1,245 @@ +package pq + +import ( + "database/sql/driver" + "fmt" + "io" + "math" + "reflect" + "time" + + "github.com/lib/pq/internal/proto" + "github.com/lib/pq/oid" +) + +type noRows struct{} + +var emptyRows noRows + +var _ driver.Result = noRows{} + +func (noRows) LastInsertId() (int64, error) { return 0, errNoLastInsertID } +func (noRows) RowsAffected() (int64, error) { return 0, errNoRowsAffected } + +type ( + rowsHeader struct { + colNames []string + colTyps []fieldDesc + colFmts []format + } + rows struct { + cn *conn + finish func() + rowsHeader + done bool + rb readBuf + result driver.Result + tag string + + next *rowsHeader + } +) + +func (rs *rows) Close() error { + if finish := rs.finish; finish != nil { + defer finish() + } + // no need to look at cn.bad as Next() will + for { + err := rs.Next(nil) + switch err { + case nil: + case io.EOF: + // rs.Next can return io.EOF on both ReadyForQuery and + // RowDescription (used with HasNextResultSet). We need to fetch + // messages until we hit a ReadyForQuery, which is done by waiting + // for done to be set. + if rs.done { + return nil + } + default: + return err + } + } +} + +func (rs *rows) Columns() []string { + return rs.colNames +} + +func (rs *rows) Result() driver.Result { + if rs.result == nil { + return emptyRows + } + return rs.result +} + +func (rs *rows) Tag() string { + return rs.tag +} + +func (rs *rows) Next(dest []driver.Value) (resErr error) { + if rs.done { + return io.EOF + } + if err := rs.cn.err.getForNext(); err != nil { + return err + } + + for { + t, err := rs.cn.recv1Buf(&rs.rb) + if err != nil { + return rs.cn.handleError(err) + } + switch t { + case proto.ErrorResponse: + resErr = parseError(&rs.rb, "") + case proto.CommandComplete, proto.EmptyQueryResponse: + if t == proto.CommandComplete { + rs.result, rs.tag, err = rs.cn.parseComplete(rs.rb.string()) + if err != nil { + return rs.cn.handleError(err) + } + } + continue + case proto.ReadyForQuery: + rs.cn.processReadyForQuery(&rs.rb) + rs.done = true + if resErr != nil { + return rs.cn.handleError(resErr) + } + return io.EOF + case proto.DataRow: + n := rs.rb.int16() + if resErr != nil { + rs.cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected DataRow after error %s", resErr) + } + if n < len(dest) { + dest = dest[:n] + } + for i := range dest { + l := rs.rb.int32() + if l == -1 { + dest[i] = nil + continue + } + dest[i], err = decode(&rs.cn.parameterStatus, rs.rb.next(l), rs.colTyps[i].OID, rs.colFmts[i]) + if err != nil { + return rs.cn.handleError(err) + } + } + return rs.cn.handleError(resErr) + case proto.RowDescription: + next := parsePortalRowDescribe(&rs.rb) + rs.next = &next + return io.EOF + default: + return fmt.Errorf("pq: unexpected message after execute: %q", t) + } + } +} + +func (rs *rows) HasNextResultSet() bool { + hasNext := rs.next != nil && !rs.done + return hasNext +} + +func (rs *rows) NextResultSet() error { + if rs.next == nil { + return io.EOF + } + rs.rowsHeader = *rs.next + rs.next = nil + return nil +} + +// ColumnTypeScanType returns the value type that can be used to scan types into. +func (rs *rows) ColumnTypeScanType(index int) reflect.Type { + return rs.colTyps[index].Type() +} + +// ColumnTypeDatabaseTypeName return the database system type name. +func (rs *rows) ColumnTypeDatabaseTypeName(index int) string { + return rs.colTyps[index].Name() +} + +// ColumnTypeLength returns the length of the column type if the column is a +// variable length type. If the column is not a variable length type ok +// should return false. +func (rs *rows) ColumnTypeLength(index int) (length int64, ok bool) { + return rs.colTyps[index].Length() +} + +// ColumnTypePrecisionScale should return the precision and scale for decimal +// types. If not applicable, ok should be false. +func (rs *rows) ColumnTypePrecisionScale(index int) (precision, scale int64, ok bool) { + return rs.colTyps[index].PrecisionScale() +} + +const headerSize = 4 + +type fieldDesc struct { + // The object ID of the data type. + OID oid.Oid + // The data type size (see pg_type.typlen). + // Note that negative values denote variable-width types. + Len int + // The type modifier (see pg_attribute.atttypmod). + // The meaning of the modifier is type-specific. + Mod int +} + +func (fd fieldDesc) Type() reflect.Type { + switch fd.OID { + case oid.T_int8: + return reflect.TypeOf(int64(0)) + case oid.T_int4: + return reflect.TypeOf(int32(0)) + case oid.T_int2: + return reflect.TypeOf(int16(0)) + case oid.T_float8: + return reflect.TypeOf(float64(0)) + case oid.T_float4: + return reflect.TypeOf(float32(0)) + case oid.T_varchar, oid.T_text, oid.T_varbit, oid.T_bit: + return reflect.TypeOf("") + case oid.T_bool: + return reflect.TypeOf(false) + case oid.T_date, oid.T_time, oid.T_timetz, oid.T_timestamp, oid.T_timestamptz: + return reflect.TypeOf(time.Time{}) + case oid.T_bytea: + return reflect.TypeOf([]byte(nil)) + default: + return reflect.TypeOf(new(any)).Elem() + } +} + +func (fd fieldDesc) Name() string { + return oid.TypeName[fd.OID] +} + +func (fd fieldDesc) Length() (length int64, ok bool) { + switch fd.OID { + case oid.T_text, oid.T_bytea: + return math.MaxInt64, true + case oid.T_varchar, oid.T_bpchar: + return int64(fd.Mod - headerSize), true + case oid.T_varbit, oid.T_bit: + return int64(fd.Mod), true + default: + return 0, false + } +} + +func (fd fieldDesc) PrecisionScale() (precision, scale int64, ok bool) { + switch fd.OID { + case oid.T_numeric, oid.T__numeric: + mod := fd.Mod - headerSize + precision = int64((mod >> 16) & 0xffff) + scale = int64(mod & 0xffff) + return precision, scale, true + default: + return 0, 0, false + } +} diff --git a/vendor/github.com/lib/pq/scram/scram.go b/vendor/github.com/lib/pq/scram/scram.go new file mode 100644 index 0000000..7ed7a99 --- /dev/null +++ b/vendor/github.com/lib/pq/scram/scram.go @@ -0,0 +1,261 @@ +// Copyright (c) 2014 - Gustavo Niemeyer +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Package scram implements a SCRAM-{SHA-1,etc} client per RFC5802. +// +// http://tools.ietf.org/html/rfc5802 +package scram + +import ( + "bytes" + "crypto/hmac" + "crypto/rand" + "encoding/base64" + "fmt" + "hash" + "strconv" + "strings" +) + +// Client implements a SCRAM-* client (SCRAM-SHA-1, SCRAM-SHA-256, etc). +// +// A Client may be used within a SASL conversation with logic resembling: +// +// var in []byte +// var client = scram.NewClient(sha1.New, user, pass) +// for client.Step(in) { +// out := client.Out() +// // send out to server +// in := serverOut +// } +// if client.Err() != nil { +// // auth failed +// } +type Client struct { + newHash func() hash.Hash + + user string + pass string + step int + out bytes.Buffer + err error + + clientNonce []byte + serverNonce []byte + saltedPass []byte + authMsg bytes.Buffer +} + +// NewClient returns a new SCRAM-* client with the provided hash algorithm. +// +// For SCRAM-SHA-256, for example, use: +// +// client := scram.NewClient(sha256.New, user, pass) +func NewClient(newHash func() hash.Hash, user, pass string) *Client { + c := &Client{ + newHash: newHash, + user: user, + pass: pass, + } + c.out.Grow(256) + c.authMsg.Grow(256) + return c +} + +// Out returns the data to be sent to the server in the current step. +func (c *Client) Out() []byte { + if c.out.Len() == 0 { + return nil + } + return c.out.Bytes() +} + +// Err returns the error that occurred, or nil if there were no errors. +func (c *Client) Err() error { + return c.err +} + +// SetNonce sets the client nonce to the provided value. +// If not set, the nonce is generated automatically out of crypto/rand on the first step. +func (c *Client) SetNonce(nonce []byte) { + c.clientNonce = nonce +} + +var escaper = strings.NewReplacer("=", "=3D", ",", "=2C") + +// Step processes the incoming data from the server and makes the +// next round of data for the server available via Client.Out. +// Step returns false if there are no errors and more data is +// still expected. +func (c *Client) Step(in []byte) bool { + c.out.Reset() + if c.step > 2 || c.err != nil { + return false + } + c.step++ + switch c.step { + case 1: + c.err = c.step1(in) + case 2: + c.err = c.step2(in) + case 3: + c.err = c.step3(in) + } + return c.step > 2 || c.err != nil +} + +func (c *Client) step1(in []byte) error { + if len(c.clientNonce) == 0 { + const nonceLen = 16 + buf := make([]byte, nonceLen+b64.EncodedLen(nonceLen)) + if _, err := rand.Read(buf[:nonceLen]); err != nil { + return fmt.Errorf("cannot read random SCRAM-SHA-256 nonce from operating system: %w", err) + } + c.clientNonce = buf[nonceLen:] + b64.Encode(c.clientNonce, buf[:nonceLen]) + } + c.authMsg.WriteString("n=") + escaper.WriteString(&c.authMsg, c.user) + c.authMsg.WriteString(",r=") + c.authMsg.Write(c.clientNonce) + + c.out.WriteString("n,,") + c.out.Write(c.authMsg.Bytes()) + return nil +} + +var b64 = base64.StdEncoding + +func (c *Client) step2(in []byte) error { + c.authMsg.WriteByte(',') + c.authMsg.Write(in) + + fields := bytes.Split(in, []byte(",")) + if len(fields) != 3 { + return fmt.Errorf("expected 3 fields in first SCRAM-SHA-256 server message, got %d: %q", len(fields), in) + } + if !bytes.HasPrefix(fields[0], []byte("r=")) || len(fields[0]) < 2 { + return fmt.Errorf("server sent an invalid SCRAM-SHA-256 nonce: %q", fields[0]) + } + if !bytes.HasPrefix(fields[1], []byte("s=")) || len(fields[1]) < 6 { + return fmt.Errorf("server sent an invalid SCRAM-SHA-256 salt: %q", fields[1]) + } + if !bytes.HasPrefix(fields[2], []byte("i=")) || len(fields[2]) < 6 { + return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2]) + } + + c.serverNonce = fields[0][2:] + if !bytes.HasPrefix(c.serverNonce, c.clientNonce) { + return fmt.Errorf("server SCRAM-SHA-256 nonce is not prefixed by client nonce: got %q, want %q+\"...\"", c.serverNonce, c.clientNonce) + } + + salt := make([]byte, b64.DecodedLen(len(fields[1][2:]))) + n, err := b64.Decode(salt, fields[1][2:]) + if err != nil { + return fmt.Errorf("cannot decode SCRAM-SHA-256 salt sent by server: %q", fields[1]) + } + salt = salt[:n] + iterCount, err := strconv.Atoi(string(fields[2][2:])) + if err != nil { + return fmt.Errorf("server sent an invalid SCRAM-SHA-256 iteration count: %q", fields[2]) + } + c.saltPassword(salt, iterCount) + + c.authMsg.WriteString(",c=biws,r=") + c.authMsg.Write(c.serverNonce) + + c.out.WriteString("c=biws,r=") + c.out.Write(c.serverNonce) + c.out.WriteString(",p=") + c.out.Write(c.clientProof()) + return nil +} + +func (c *Client) step3(in []byte) error { + var isv, ise bool + var fields = bytes.Split(in, []byte(",")) + if len(fields) == 1 { + isv = bytes.HasPrefix(fields[0], []byte("v=")) + ise = bytes.HasPrefix(fields[0], []byte("e=")) + } + if ise { + return fmt.Errorf("SCRAM-SHA-256 authentication error: %s", fields[0][2:]) + } else if !isv { + return fmt.Errorf("unsupported SCRAM-SHA-256 final message from server: %q", in) + } + if !bytes.Equal(c.serverSignature(), fields[0][2:]) { + return fmt.Errorf("cannot authenticate SCRAM-SHA-256 server signature: %q", fields[0][2:]) + } + return nil +} + +func (c *Client) saltPassword(salt []byte, iterCount int) { + mac := hmac.New(c.newHash, []byte(c.pass)) + mac.Write(salt) + mac.Write([]byte{0, 0, 0, 1}) + ui := mac.Sum(nil) + hi := make([]byte, len(ui)) + copy(hi, ui) + for i := 1; i < iterCount; i++ { + mac.Reset() + mac.Write(ui) + mac.Sum(ui[:0]) + for j, b := range ui { + hi[j] ^= b + } + } + c.saltedPass = hi +} + +func (c *Client) clientProof() []byte { + mac := hmac.New(c.newHash, c.saltedPass) + mac.Write([]byte("Client Key")) + clientKey := mac.Sum(nil) + hash := c.newHash() + hash.Write(clientKey) + storedKey := hash.Sum(nil) + mac = hmac.New(c.newHash, storedKey) + mac.Write(c.authMsg.Bytes()) + clientProof := mac.Sum(nil) + for i, b := range clientKey { + clientProof[i] ^= b + } + clientProof64 := make([]byte, b64.EncodedLen(len(clientProof))) + b64.Encode(clientProof64, clientProof) + return clientProof64 +} + +func (c *Client) serverSignature() []byte { + mac := hmac.New(c.newHash, c.saltedPass) + mac.Write([]byte("Server Key")) + serverKey := mac.Sum(nil) + + mac = hmac.New(c.newHash, serverKey) + mac.Write(c.authMsg.Bytes()) + serverSignature := mac.Sum(nil) + + encoded := make([]byte, b64.EncodedLen(len(serverSignature))) + b64.Encode(encoded, serverSignature) + return encoded +} diff --git a/vendor/github.com/lib/pq/ssl.go b/vendor/github.com/lib/pq/ssl.go new file mode 100644 index 0000000..b935785 --- /dev/null +++ b/vendor/github.com/lib/pq/ssl.go @@ -0,0 +1,312 @@ +package pq + +import ( + "bytes" + "crypto/tls" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "net" + "os" + "path/filepath" + "slices" + "strings" + "sync" + + "github.com/lib/pq/internal/pqutil" +) + +// Registry for custom tls.Configs +var ( + tlsConfs = make(map[string]*tls.Config) + tlsConfsMu sync.RWMutex +) + +// RegisterTLSConfig registers a custom [tls.Config]. They are used by using +// sslmode=pqgo-«key» in the connection string. +// +// Set the config to nil to remove a configuration. +func RegisterTLSConfig(key string, config *tls.Config) error { + key = strings.TrimPrefix(key, "pqgo-") + if config == nil { + tlsConfsMu.Lock() + delete(tlsConfs, key) + tlsConfsMu.Unlock() + return nil + } + + tlsConfsMu.Lock() + tlsConfs[key] = config + tlsConfsMu.Unlock() + return nil +} + +func hasTLSConfig(key string) bool { + tlsConfsMu.RLock() + defer tlsConfsMu.RUnlock() + _, ok := tlsConfs[key] + return ok +} + +func getTLSConfigClone(key string) *tls.Config { + tlsConfsMu.RLock() + defer tlsConfsMu.RUnlock() + if v, ok := tlsConfs[key]; ok { + return v.Clone() + } + return nil +} + +// ssl generates a function to upgrade a net.Conn based on the "sslmode" and +// related settings. The function is nil when no upgrade should take place. +// +// Don't refer to Config.SSLMode here, as the mode in arguments may be different +// in case of sslmode=allow or prefer. +func ssl(cfg Config, mode SSLMode) (func(net.Conn) (net.Conn, error), error) { + var ( + home = pqutil.Home(true) + // Don't set defaults here, because tlsConf may be overwritten if a + // custom one was registered. Set it after the sslmode switch. + tlsConf = &tls.Config{} + // Only verify the CA signing but not the hostname. + verifyCaOnly = false + ) + if mode.useSSL() && !cfg.SSLInline && cfg.SSLRootCert == "" && home != "" { + f := filepath.Join(home, "root.crt") + if _, err := os.Stat(f); err == nil { + cfg.SSLRootCert = f + } + } + switch { + case mode == SSLModeDisable || mode == SSLModeAllow: + return nil, nil + + case mode == "" || mode == SSLModeRequire || mode == SSLModePrefer: + // Skip TLS's own verification since it requires full verification. + tlsConf.InsecureSkipVerify = true + + // From http://www.postgresql.org/docs/current/static/libpq-ssl.html: + // + // For backwards compatibility with earlier versions of PostgreSQL, if a + // root CA file exists, the behavior of sslmode=require will be the same + // as that of verify-ca, meaning the server certificate is validated + // against the CA. Relying on this behavior is discouraged, and + // applications that need certificate validation should always use + // verify-ca or verify-full. + if cfg.SSLRootCert != "" { + if cfg.SSLInline { + verifyCaOnly = true + } else if _, err := os.Stat(cfg.SSLRootCert); err == nil { + verifyCaOnly = true + } else if cfg.SSLRootCert != "system" { + cfg.SSLRootCert = "" + } + } + case mode == SSLModeVerifyCA: + // Skip TLS's own verification since it requires full verification. + tlsConf.InsecureSkipVerify = true + verifyCaOnly = true + case mode == SSLModeVerifyFull: + tlsConf.ServerName = cfg.Host + case strings.HasPrefix(string(mode), "pqgo-"): + tlsConf = getTLSConfigClone(string(mode[5:])) + if tlsConf == nil { + return nil, fmt.Errorf(`pq: unknown custom sslmode %q`, mode) + } + default: + panic("unreachable") + } + + tlsConf.MinVersion = cfg.SSLMinProtocolVersion.tlsconf() + tlsConf.MaxVersion = cfg.SSLMaxProtocolVersion.tlsconf() + + // RFC 6066 asks to not set SNI if the host is a literal IP address (IPv4 or + // IPv6). This check is coded already crypto.tls.hostnameInSNI, so just + // always set ServerName here and let crypto/tls do the filtering. + if cfg.SSLSNI { + tlsConf.ServerName = cfg.Host + } + + err := sslClientCertificates(tlsConf, cfg, home) + if err != nil { + return nil, err + } + rootPem, err := sslCertificateAuthority(tlsConf, cfg) + if err != nil { + return nil, err + } + sslAppendIntermediates(tlsConf, cfg, rootPem) + + // Accept renegotiation requests initiated by the backend. + // + // Renegotiation was deprecated then removed from PostgreSQL 9.5, but the + // default configuration of older versions has it enabled. Redshift also + // initiates renegotiations and cannot be reconfigured. + // + // TODO: I think this can be removed? + tlsConf.Renegotiation = tls.RenegotiateFreelyAsClient + + return func(conn net.Conn) (net.Conn, error) { + client := tls.Client(conn, tlsConf) + if verifyCaOnly { + err := client.Handshake() + if err != nil { + return client, err + } + var ( + certs = client.ConnectionState().PeerCertificates + opts = x509.VerifyOptions{Intermediates: x509.NewCertPool(), Roots: tlsConf.RootCAs} + ) + for _, cert := range certs[1:] { + opts.Intermediates.AddCert(cert) + } + _, err = certs[0].Verify(opts) + return client, err + } + return client, nil + }, nil +} + +// sslClientCertificates adds the certificate specified in the "sslcert" and +// +// "sslkey" settings, or if they aren't set, from the .postgresql directory +// in the user's home directory. The configured files must exist and have +// the correct permissions. +func sslClientCertificates(tlsConf *tls.Config, cfg Config, home string) error { + if cfg.SSLInline { + cert, err := tls.X509KeyPair([]byte(cfg.SSLCert), []byte(cfg.SSLKey)) + if err != nil { + return err + } + // Use GetClientCertificate instead of the Certificates field. When + // Certificates is set, Go's TLS client only sends the cert if the + // server's CertificateRequest includes a CA that issued it. When the + // client cert was signed by an intermediate CA but the server only + // advertises the root CA, Go skips sending the cert entirely. + // GetClientCertificate bypasses this filtering. + tlsConf.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + return &cert, nil + } + return nil + } + + // Only load client certificate and key if the setting is not blank, like libpq. + if cfg.SSLCert == "" && home != "" { + cfg.SSLCert = filepath.Join(home, "postgresql.crt") + } + if cfg.SSLCert == "" { + return nil + } + _, err := os.Stat(cfg.SSLCert) + if err != nil { + if pqutil.ErrNotExists(err) { + return nil + } + return err + } + + // In libpq, the ssl key is only loaded if the setting is not blank. + if cfg.SSLKey == "" && home != "" { + cfg.SSLKey = filepath.Join(home, "postgresql.key") + } + if cfg.SSLKey != "" { + err := pqutil.SSLKeyPermissions(cfg.SSLKey) + if err != nil { + return err + } + } + + cert, err := tls.LoadX509KeyPair(cfg.SSLCert, cfg.SSLKey) + if err != nil { + return err + } + + // Using GetClientCertificate instead of Certificates per comment above. + tlsConf.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { + return &cert, nil + } + return nil +} + +var testSystemRoots *x509.CertPool + +// sslCertificateAuthority adds the RootCA specified in the "sslrootcert" setting. +func sslCertificateAuthority(tlsConf *tls.Config, cfg Config) ([]byte, error) { + // Only load root certificate if not blank, like libpq. + if cfg.SSLRootCert == "" { + return nil, nil + } + + if cfg.SSLRootCert == "system" { + // No work to do as system CAs are used by default if RootCAs is nil. + tlsConf.RootCAs = testSystemRoots + return nil, nil + } + + tlsConf.RootCAs = x509.NewCertPool() + + var cert []byte + if cfg.SSLInline { + cert = []byte(cfg.SSLRootCert) + } else { + var err error + cert, err = os.ReadFile(cfg.SSLRootCert) + if err != nil { + return nil, err + } + } + + if !tlsConf.RootCAs.AppendCertsFromPEM(cert) { + return nil, errors.New("pq: couldn't parse pem from sslrootcert") + } + return cert, nil +} + +// sslAppendIntermediates appends intermediate CA certificates from sslrootcert +// to the client certificate chain. This is needed so the server can verify the +// client cert when it was signed by an intermediate CA — without this, the TLS +// handshake only sends the leaf client cert. +func sslAppendIntermediates(tlsConf *tls.Config, cfg Config, rootPem []byte) { + if cfg.SSLRootCert == "" || tlsConf.GetClientCertificate == nil || len(rootPem) == 0 { + return + } + + var ( + pemData = slices.Clone(rootPem) + intermediates [][]byte + ) + for { + var block *pem.Block + block, pemData = pem.Decode(pemData) + if block == nil { + break + } + if block.Type != "CERTIFICATE" { + continue + } + cert, err := x509.ParseCertificate(block.Bytes) + if err != nil { + continue + } + // Skip self-signed root CAs; only append intermediates. + if cert.IsCA && !bytes.Equal(cert.RawIssuer, cert.RawSubject) { + intermediates = append(intermediates, block.Bytes) + } + } + if len(intermediates) == 0 { + return + } + + // Wrap the existing GetClientCertificate to append intermediate certs to + // the certificate chain returned during the TLS handshake. + origGetCert := tlsConf.GetClientCertificate + tlsConf.GetClientCertificate = func(info *tls.CertificateRequestInfo) (*tls.Certificate, error) { + cert, err := origGetCert(info) + if err != nil { + return cert, err + } + cert.Certificate = append(cert.Certificate, intermediates...) + return cert, nil + } +} diff --git a/vendor/github.com/lib/pq/staticcheck.conf b/vendor/github.com/lib/pq/staticcheck.conf new file mode 100644 index 0000000..83abe48 --- /dev/null +++ b/vendor/github.com/lib/pq/staticcheck.conf @@ -0,0 +1,5 @@ +checks = [ + 'all', + '-ST1000', # "Must have at least one package comment" + '-ST1003', # "func EnableInfinityTs should be EnableInfinityTS" +] diff --git a/vendor/github.com/lib/pq/stmt.go b/vendor/github.com/lib/pq/stmt.go new file mode 100644 index 0000000..ca6ecc8 --- /dev/null +++ b/vendor/github.com/lib/pq/stmt.go @@ -0,0 +1,150 @@ +package pq + +import ( + "context" + "database/sql/driver" + "fmt" + "os" + + "github.com/lib/pq/internal/proto" + "github.com/lib/pq/oid" +) + +type stmt struct { + cn *conn + name string + rowsHeader + colFmtData []byte + paramTyps []oid.Oid + closed bool +} + +func (st *stmt) Close() error { + if st.closed { + return nil + } + if err := st.cn.err.get(); err != nil { + return err + } + + w := st.cn.writeBuf(proto.Close) + w.byte(proto.Sync) + w.string(st.name) + err := st.cn.send(w) + if err != nil { + return st.cn.handleError(err) + } + err = st.cn.send(st.cn.writeBuf(proto.Sync)) + if err != nil { + return st.cn.handleError(err) + } + + t, _, err := st.cn.recv1() + if err != nil { + return st.cn.handleError(err) + } + if t != proto.CloseComplete { + st.cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: unexpected close response: %q", t) + } + st.closed = true + + t, r, err := st.cn.recv1() + if err != nil { + return st.cn.handleError(err) + } + if t != proto.ReadyForQuery { + st.cn.err.set(driver.ErrBadConn) + return fmt.Errorf("pq: expected ready for query, but got: %q", t) + } + st.cn.processReadyForQuery(r) + + return nil +} + +func (st *stmt) Query(v []driver.Value) (r driver.Rows, err error) { + return st.query(toNamedValue(v)) +} + +func (st *stmt) query(v []driver.NamedValue) (*rows, error) { + if err := st.cn.err.get(); err != nil { + return nil, err + } + + err := st.exec(v) + if err != nil { + return nil, st.cn.handleError(err) + } + return &rows{ + cn: st.cn, + rowsHeader: st.rowsHeader, + }, nil +} + +func (st *stmt) Exec(v []driver.Value) (driver.Result, error) { + return st.ExecContext(context.Background(), toNamedValue(v)) +} + +func (st *stmt) exec(v []driver.NamedValue) error { + if debugProto { + fmt.Fprintf(os.Stderr, " START stmt.exec\n") + defer fmt.Fprintf(os.Stderr, " END stmt.exec\n") + } + if len(v) >= 65536 { + return fmt.Errorf("pq: got %d parameters but PostgreSQL only supports 65535 parameters", len(v)) + } + if len(v) != len(st.paramTyps) { + return fmt.Errorf("pq: got %d parameters but the statement requires %d", len(v), len(st.paramTyps)) + } + + cn := st.cn + w := cn.writeBuf(proto.Bind) + w.byte(0) // unnamed portal + w.string(st.name) + + if cn.cfg.BinaryParameters { + err := cn.sendBinaryParameters(w, v) + if err != nil { + return err + } + } else { + w.int16(0) + w.int16(len(v)) + for i, x := range v { + if x.Value == nil { + w.int32(-1) + } else { + b, err := encode(x.Value, st.paramTyps[i]) + if err != nil { + return err + } + if b == nil { + w.int32(-1) + } else { + w.int32(len(b)) + w.bytes(b) + } + } + } + } + w.bytes(st.colFmtData) + + w.next(proto.Execute) + w.byte(0) + w.int32(0) + + w.next(proto.Sync) + err := cn.send(w) + if err != nil { + return err + } + err = cn.readBindResponse() + if err != nil { + return err + } + return cn.postExecuteWorkaround() +} + +func (st *stmt) NumInput() int { + return len(st.paramTyps) +} diff --git a/vendor/github.com/spf13/cobra/.gitignore b/vendor/github.com/spf13/cobra/.gitignore new file mode 100644 index 0000000..c7b459e --- /dev/null +++ b/vendor/github.com/spf13/cobra/.gitignore @@ -0,0 +1,39 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore +# swap +[._]*.s[a-w][a-z] +[._]s[a-w][a-z] +# session +Session.vim +# temporary +.netrwhist +*~ +# auto-generated tag files +tags + +*.exe +cobra.test +bin + +.idea/ +*.iml diff --git a/vendor/github.com/spf13/cobra/.golangci.yml b/vendor/github.com/spf13/cobra/.golangci.yml new file mode 100644 index 0000000..104dc24 --- /dev/null +++ b/vendor/github.com/spf13/cobra/.golangci.yml @@ -0,0 +1,66 @@ +# Copyright 2013-2023 The Cobra Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +version: "2" + +run: + timeout: 5m + +formatters: + enable: + - gofmt + - goimports + +linters: + default: none + enable: + #- bodyclose + #- depguard + #- dogsled + #- dupl + - errcheck + #- exhaustive + #- funlen + #- gochecknoinits + - goconst + - gocritic + #- gocyclo + #- goprintffuncname + - gosec + - govet + - ineffassign + #- lll + - misspell + #- mnd + #- nakedret + #- noctx + - nolintlint + #- rowserrcheck + - staticcheck + - unconvert + #- unparam + - unused + #- whitespace + exclusions: + presets: + - common-false-positives + - legacy + - std-error-handling + settings: + govet: + # Disable buildtag check to allow dual build tag syntax (both //go:build and // +build). + # This is necessary for Go 1.15 compatibility since //go:build was introduced in Go 1.17. + # This can be removed once Cobra requires Go 1.17 or higher. + disable: + - buildtag diff --git a/vendor/github.com/spf13/cobra/.mailmap b/vendor/github.com/spf13/cobra/.mailmap new file mode 100644 index 0000000..94ec530 --- /dev/null +++ b/vendor/github.com/spf13/cobra/.mailmap @@ -0,0 +1,3 @@ +Steve Francia +Bjørn Erik Pedersen +Fabiano Franz diff --git a/vendor/github.com/spf13/cobra/CONDUCT.md b/vendor/github.com/spf13/cobra/CONDUCT.md new file mode 100644 index 0000000..9d16f88 --- /dev/null +++ b/vendor/github.com/spf13/cobra/CONDUCT.md @@ -0,0 +1,37 @@ +## Cobra User Contract + +### Versioning +Cobra will follow a steady release cadence. Non breaking changes will be released as minor versions quarterly. Patch bug releases are at the discretion of the maintainers. Users can expect security patch fixes to be released within relatively short order of a CVE becoming known. For more information on security patch fixes see the CVE section below. Releases will follow [Semantic Versioning](https://semver.org/). Users tracking the Master branch should expect unpredictable breaking changes as the project continues to move forward. For stability, it is highly recommended to use a release. + +### Backward Compatibility +We will maintain two major releases in a moving window. The N-1 release will only receive bug fixes and security updates and will be dropped once N+1 is released. + +### Deprecation +Deprecation of Go versions or dependent packages will only occur in major releases. To reduce the change of this taking users by surprise, any large deprecation will be preceded by an announcement in the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) and an Issue on Github. + +### CVE +Maintainers will make every effort to release security patches in the case of a medium to high severity CVE directly impacting the library. The speed in which these patches reach a release is up to the discretion of the maintainers. A low severity CVE may be a lower priority than a high severity one. + +### Communication +Cobra maintainers will use GitHub issues and the [#cobra slack channel](https://gophers.slack.com/archives/CD3LP1199) as the primary means of communication with the community. This is to foster open communication with all users and contributors. + +### Breaking Changes +Breaking changes are generally allowed in the master branch, as this is the branch used to develop the next release of Cobra. + +There may be times, however, when master is closed for breaking changes. This is likely to happen as we near the release of a new version. + +Breaking changes are not allowed in release branches, as these represent minor versions that have already been released. These version have consumers who expect the APIs, behaviors, etc, to remain stable during the lifetime of the patch stream for the minor release. + +Examples of breaking changes include: +- Removing or renaming exported constant, variable, type, or function. +- Updating the version of critical libraries such as `spf13/pflag`, `spf13/viper` etc... + - Some version updates may be acceptable for picking up bug fixes, but maintainers must exercise caution when reviewing. + +There may, at times, need to be exceptions where breaking changes are allowed in release branches. These are at the discretion of the project's maintainers, and must be carefully considered before merging. + +### CI Testing +Maintainers will ensure the Cobra test suite utilizes the current supported versions of Golang. + +### Disclaimer +Changes to this document and the contents therein are at the discretion of the maintainers. +None of the contents of this document are legally binding in any way to the maintainers or the users. diff --git a/vendor/github.com/spf13/cobra/CONTRIBUTING.md b/vendor/github.com/spf13/cobra/CONTRIBUTING.md new file mode 100644 index 0000000..6f356e6 --- /dev/null +++ b/vendor/github.com/spf13/cobra/CONTRIBUTING.md @@ -0,0 +1,50 @@ +# Contributing to Cobra + +Thank you so much for contributing to Cobra. We appreciate your time and help. +Here are some guidelines to help you get started. + +## Code of Conduct + +Be kind and respectful to the members of the community. Take time to educate +others who are seeking help. Harassment of any kind will not be tolerated. + +## Questions + +If you have questions regarding Cobra, feel free to ask it in the community +[#cobra Slack channel][cobra-slack] + +## Filing a bug or feature + +1. Before filing an issue, please check the existing issues to see if a + similar one was already opened. If there is one already opened, feel free + to comment on it. +1. If you believe you've found a bug, please provide detailed steps of + reproduction, the version of Cobra and anything else you believe will be + useful to help troubleshoot it (e.g. OS environment, environment variables, + etc...). Also state the current behavior vs. the expected behavior. +1. If you'd like to see a feature or an enhancement please open an issue with + a clear title and description of what the feature is and why it would be + beneficial to the project and its users. + +## Submitting changes + +1. CLA: Upon submitting a Pull Request (PR), contributors will be prompted to + sign a CLA. Please sign the CLA :slightly_smiling_face: +1. Tests: If you are submitting code, please ensure you have adequate tests + for the feature. Tests can be run via `go test ./...` or `make test`. +1. Since this is golang project, ensure the new code is properly formatted to + ensure code consistency. Run `make all`. + +### Quick steps to contribute + +1. Fork the project. +1. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`) +1. Create your feature branch (`git checkout -b my-new-feature`) +1. Make changes and run tests (`make test`) +1. Add them to staging (`git add .`) +1. Commit your changes (`git commit -m 'Add some feature'`) +1. Push to the branch (`git push origin my-new-feature`) +1. Create new pull request + + +[cobra-slack]: https://gophers.slack.com/archives/CD3LP1199 diff --git a/vendor/github.com/spf13/cobra/LICENSE.txt b/vendor/github.com/spf13/cobra/LICENSE.txt new file mode 100644 index 0000000..298f0e2 --- /dev/null +++ b/vendor/github.com/spf13/cobra/LICENSE.txt @@ -0,0 +1,174 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. diff --git a/vendor/github.com/spf13/cobra/MAINTAINERS b/vendor/github.com/spf13/cobra/MAINTAINERS new file mode 100644 index 0000000..4c5ac3d --- /dev/null +++ b/vendor/github.com/spf13/cobra/MAINTAINERS @@ -0,0 +1,13 @@ +maintainers: +- spf13 +- johnSchnake +- jpmcb +- marckhouzam +inactive: +- anthonyfok +- bep +- bogem +- broady +- eparis +- jharshman +- wfernandes diff --git a/vendor/github.com/spf13/cobra/Makefile b/vendor/github.com/spf13/cobra/Makefile new file mode 100644 index 0000000..0da8d7a --- /dev/null +++ b/vendor/github.com/spf13/cobra/Makefile @@ -0,0 +1,35 @@ +BIN="./bin" +SRC=$(shell find . -name "*.go") + +ifeq (, $(shell which golangci-lint)) +$(warning "could not find golangci-lint in $(PATH), run: curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | sh") +endif + +.PHONY: fmt lint test install_deps clean + +default: all + +all: fmt test + +fmt: + $(info ******************** checking formatting ********************) + @test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1) + +lint: + $(info ******************** running lint tools ********************) + golangci-lint run -v + +test: install_deps + $(info ******************** running tests ********************) + go test -v ./... + +richtest: install_deps + $(info ******************** running tests with kyoh86/richgo ********************) + richgo test -v ./... + +install_deps: + $(info ******************** downloading dependencies ********************) + go get -v ./... + +clean: + rm -rf $(BIN) diff --git a/vendor/github.com/spf13/cobra/README.md b/vendor/github.com/spf13/cobra/README.md new file mode 100644 index 0000000..8416275 --- /dev/null +++ b/vendor/github.com/spf13/cobra/README.md @@ -0,0 +1,133 @@ +
+ +cobra-logo + +
+ +Cobra is a library for creating powerful modern CLI applications. + +Visit Cobra.dev for extensive documentation + + +Cobra is used in many Go projects such as [Kubernetes](https://kubernetes.io/), +[Hugo](https://gohugo.io), and [GitHub CLI](https://github.com/cli/cli) to +name a few. [This list](site/content/projects_using_cobra.md) contains a more extensive list of projects using Cobra. + +[![](https://img.shields.io/github/actions/workflow/status/spf13/cobra/test.yml?branch=main&longCache=true&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest) +[![Go Reference](https://pkg.go.dev/badge/github.com/spf13/cobra.svg)](https://pkg.go.dev/github.com/spf13/cobra) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra) +[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199) +
+
+ Supported by: +
+
+ + Warp sponsorship + + +### [Warp, the AI terminal for devs](https://www.warp.dev/cobra) +[Try Cobra in Warp today](https://www.warp.dev/cobra)
+ +
+
+ +# Overview + +Cobra is a library providing a simple interface to create powerful modern CLI +interfaces similar to git & go tools. + +Cobra provides: +* Easy subcommand-based CLIs: `app server`, `app fetch`, etc. +* Fully POSIX-compliant flags (including short & long versions) +* Nested subcommands +* Global, local and cascading flags +* Intelligent suggestions (`app srver`... did you mean `app server`?) +* Automatic help generation for commands and flags +* Grouping help for subcommands +* Automatic help flag recognition of `-h`, `--help`, etc. +* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell) +* Automatically generated man pages for your application +* Command aliases so you can change things without breaking them +* The flexibility to define your own help, usage, etc. +* Optional seamless integration with [viper](https://github.com/spf13/viper) for 12-factor apps + +# Concepts + +Cobra is built on a structure of commands, arguments & flags. + +**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions. + +The best applications read like sentences when used, and as a result, users +intuitively know how to interact with them. + +The pattern to follow is +`APPNAME VERB NOUN --ADJECTIVE` + or +`APPNAME COMMAND ARG --FLAG`. + +A few good real world examples may better illustrate this point. + +In the following example, 'server' is a command, and 'port' is a flag: + + hugo server --port=1313 + +In this command we are telling Git to clone the url bare. + + git clone URL --bare + +## Commands + +Command is the central point of the application. Each interaction that +the application supports will be contained in a Command. A command can +have children commands and optionally run an action. + +In the example above, 'server' is the command. + +[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command) + +## Flags + +A flag is a way to modify the behavior of a command. Cobra supports +fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/). +A Cobra command can define flags that persist through to children commands +and flags that are only available to that command. + +In the example above, 'port' is the flag. + +Flag functionality is provided by the [pflag +library](https://github.com/spf13/pflag), a fork of the flag standard library +which maintains the same interface while adding POSIX compliance. + +# Installing +Using Cobra is easy. First, use `go get` to install the latest version +of the library. + +``` +go get -u github.com/spf13/cobra@latest +``` + +Next, include Cobra in your application: + +```go +import "github.com/spf13/cobra" +``` + +# Usage +`cobra-cli` is a command line program to generate cobra applications and command files. +It will bootstrap your application scaffolding to rapidly +develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application. + +It can be installed by running: + +``` +go install github.com/spf13/cobra-cli@latest +``` + +For complete details on using the Cobra-CLI generator, please read [The Cobra Generator README](https://github.com/spf13/cobra-cli/blob/main/README.md) + +For complete details on using the Cobra library, please read [The Cobra User Guide](site/content/user_guide.md). + +# License + +Cobra is released under the Apache 2.0 license. See [LICENSE.txt](LICENSE.txt) diff --git a/vendor/github.com/spf13/cobra/SECURITY.md b/vendor/github.com/spf13/cobra/SECURITY.md new file mode 100644 index 0000000..54e60c2 --- /dev/null +++ b/vendor/github.com/spf13/cobra/SECURITY.md @@ -0,0 +1,105 @@ +# Security Policy + +## Reporting a Vulnerability + +The `cobra` maintainers take security issues seriously and +we appreciate your efforts to _**responsibly**_ disclose your findings. +We will make every effort to swiftly respond and address concerns. + +To report a security vulnerability: + +1. **DO NOT** create a public GitHub issue for the vulnerability! +2. **DO NOT** create a public GitHub Pull Request with a fix for the vulnerability! +3. Send an email to `cobra-security@googlegroups.com`. +4. Include the following details in your report: + - Description of the vulnerability + - Steps to reproduce + - Potential impact of the vulnerability (to your downstream project, to the Go ecosystem, etc.) + - Any potential mitigations you've already identified +5. Allow up to 7 days for an initial response. + You should receive an acknowledgment of your report and an estimated timeline for a fix. +6. (Optional) If you have a fix and would like to contribute your patch, please work + directly with the maintainers via `cobra-security@googlegroups.com` to + coordinate pushing the patch to GitHub, cutting a new release, and disclosing the change. + +## Response Process + +When a security vulnerability report is received, the `cobra` maintainers will: + +1. Confirm receipt of the vulnerability report within 7 days. +2. Assess the report to determine if it constitutes a security vulnerability. +3. If confirmed, assign the vulnerability a severity level and create a timeline for addressing it. +4. Develop and test a fix. +5. Patch the vulnerability and make a new GitHub release: the maintainers will coordinate disclosure with the reporter. +6. Create a new GitHub Security Advisory to inform the broader Go ecosystem + +## Disclosure Policy + +The `cobra` maintainers follow a coordinated disclosure process: + +1. Security vulnerabilities will be addressed as quickly as possible. +2. A CVE (Common Vulnerabilities and Exposures) identifier will be requested for significant vulnerabilities + that are within `cobra` itself. +3. Once a fix is ready, the maintainers will: + - Release a new version containing the fix. + - Update the security advisory with details about the vulnerability. + - Credit the reporter (unless they wish to remain anonymous). + - Credit the fixer (unless they wish to remain anonymous, this may be the same as the reporter). + - Announce the vulnerability through appropriate channels + (GitHub Security Advisory, mailing lists, GitHub Releases, etc.) + +## Supported Versions + +Security fixes will typically only be released for the most recent major release. + +## Upstream Security Issues + +`cobra` generally will not accept vulnerability reports that originate in upstream +dependencies. I.e., if there is a problem in Go code that `cobra` depends on, +it is best to engage that project's maintainers and owners. + +This security policy primarily pertains only to `cobra` itself but if you believe you've +identified a problem that originates in an upstream dependency and is being widely +distributed by `cobra`, please follow the disclosure procedure above: the `cobra` +maintainers will work with you to determine the severity and ecosystem impact. + +## Security Updates and CVEs + +Information about known security vulnerabilities and CVEs affecting `cobra` will +be published as GitHub Security Advisories at +https://github.com/spf13/cobra/security/advisories. + +All users are encouraged to watch the repository and upgrade promptly when +security releases are published. + +## `cobra` Security Best Practices for Users + +When using `cobra` in your CLIs, the `cobra` maintainers recommend the following: + +1. Always use the latest version of `cobra`. +2. [Use Go modules](https://go.dev/blog/using-go-modules) for dependency management. +3. Always use the latest possible version of Go. + +## Security Best Practices for Contributors + +When contributing to `cobra`: + +1. Be mindful of security implications when adding new features or modifying existing ones. +2. Be aware of `cobra`'s extremely large reach: it is used in nearly every Go CLI + (like Kubernetes, Docker, Prometheus, etc. etc.) +3. Write tests that explicitly cover edge cases and potential issues. +4. If you discover a security issue while working on `cobra`, please report it + following the process above rather than opening a public pull request or issue that + addresses the vulnerability. +5. Take personal sec-ops seriously and secure your GitHub account: use [two-factor authentication](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa), + [sign your commits with a GPG or SSH key](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification), + etc. + +## Acknowledgments + +The `cobra` maintainers would like to thank all security researchers and +community members who help keep cobra, its users, and the entire Go ecosystem secure through responsible disclosures!! + +--- + +*This security policy is inspired by the [Open Web Application Security Project (OWASP)](https://owasp.org/) guidelines and security best practices.* diff --git a/vendor/github.com/spf13/cobra/active_help.go b/vendor/github.com/spf13/cobra/active_help.go new file mode 100644 index 0000000..b3e2dad --- /dev/null +++ b/vendor/github.com/spf13/cobra/active_help.go @@ -0,0 +1,60 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "os" +) + +const ( + activeHelpMarker = "_activeHelp_ " + // The below values should not be changed: programs will be using them explicitly + // in their user documentation, and users will be using them explicitly. + activeHelpEnvVarSuffix = "ACTIVE_HELP" + activeHelpGlobalEnvVar = configEnvVarGlobalPrefix + "_" + activeHelpEnvVarSuffix + activeHelpGlobalDisable = "0" +) + +// AppendActiveHelp adds the specified string to the specified array to be used as ActiveHelp. +// Such strings will be processed by the completion script and will be shown as ActiveHelp +// to the user. +// The array parameter should be the array that will contain the completions. +// This function can be called multiple times before and/or after completions are added to +// the array. Each time this function is called with the same array, the new +// ActiveHelp line will be shown below the previous ones when completion is triggered. +func AppendActiveHelp(compArray []Completion, activeHelpStr string) []Completion { + return append(compArray, fmt.Sprintf("%s%s", activeHelpMarker, activeHelpStr)) +} + +// GetActiveHelpConfig returns the value of the ActiveHelp environment variable +// _ACTIVE_HELP where is the name of the root command in upper +// case, with all non-ASCII-alphanumeric characters replaced by `_`. +// It will always return "0" if the global environment variable COBRA_ACTIVE_HELP +// is set to "0". +func GetActiveHelpConfig(cmd *Command) string { + activeHelpCfg := os.Getenv(activeHelpGlobalEnvVar) + if activeHelpCfg != activeHelpGlobalDisable { + activeHelpCfg = os.Getenv(activeHelpEnvVar(cmd.Root().Name())) + } + return activeHelpCfg +} + +// activeHelpEnvVar returns the name of the program-specific ActiveHelp environment +// variable. It has the format _ACTIVE_HELP where is the name of the +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. +func activeHelpEnvVar(name string) string { + return configEnvVar(name, activeHelpEnvVarSuffix) +} diff --git a/vendor/github.com/spf13/cobra/args.go b/vendor/github.com/spf13/cobra/args.go new file mode 100644 index 0000000..ed1e70c --- /dev/null +++ b/vendor/github.com/spf13/cobra/args.go @@ -0,0 +1,131 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "strings" +) + +type PositionalArgs func(cmd *Command, args []string) error + +// legacyArgs validation has the following behaviour: +// - root commands with no subcommands can take arbitrary arguments +// - root commands with subcommands will do subcommand validity checking +// - subcommands will always accept arbitrary arguments +func legacyArgs(cmd *Command, args []string) error { + // no subcommand, always take args + if !cmd.HasSubCommands() { + return nil + } + + // root command with subcommands, do subcommand checking. + if !cmd.HasParent() && len(args) > 0 { + return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0])) + } + return nil +} + +// NoArgs returns an error if any args are included. +func NoArgs(cmd *Command, args []string) error { + if len(args) > 0 { + return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath()) + } + return nil +} + +// OnlyValidArgs returns an error if there are any positional args that are not in +// the `ValidArgs` field of `Command` +func OnlyValidArgs(cmd *Command, args []string) error { + if len(cmd.ValidArgs) > 0 { + // Remove any description that may be included in ValidArgs. + // A description is following a tab character. + validArgs := make([]string, 0, len(cmd.ValidArgs)) + for _, v := range cmd.ValidArgs { + validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0]) + } + for _, v := range args { + if !stringInSlice(v, validArgs) { + return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0])) + } + } + } + return nil +} + +// ArbitraryArgs never returns an error. +func ArbitraryArgs(cmd *Command, args []string) error { + return nil +} + +// MinimumNArgs returns an error if there is not at least N args. +func MinimumNArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) < n { + return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args)) + } + return nil + } +} + +// MaximumNArgs returns an error if there are more than N args. +func MaximumNArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) > n { + return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args)) + } + return nil + } +} + +// ExactArgs returns an error if there are not exactly n args. +func ExactArgs(n int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) != n { + return fmt.Errorf("accepts %d arg(s), received %d", n, len(args)) + } + return nil + } +} + +// RangeArgs returns an error if the number of args is not within the expected range. +func RangeArgs(min int, max int) PositionalArgs { + return func(cmd *Command, args []string) error { + if len(args) < min || len(args) > max { + return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args)) + } + return nil + } +} + +// MatchAll allows combining several PositionalArgs to work in concert. +func MatchAll(pargs ...PositionalArgs) PositionalArgs { + return func(cmd *Command, args []string) error { + for _, parg := range pargs { + if err := parg(cmd, args); err != nil { + return err + } + } + return nil + } +} + +// ExactValidArgs returns an error if there are not exactly N positional args OR +// there are any positional args that are not in the `ValidArgs` field of `Command` +// +// Deprecated: use MatchAll(ExactArgs(n), OnlyValidArgs) instead +func ExactValidArgs(n int) PositionalArgs { + return MatchAll(ExactArgs(n), OnlyValidArgs) +} diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go new file mode 100644 index 0000000..f4d198c --- /dev/null +++ b/vendor/github.com/spf13/cobra/bash_completions.go @@ -0,0 +1,709 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "sort" + "strings" + + "github.com/spf13/pflag" +) + +// Annotations for Bash completion. +const ( + BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions" + BashCompCustom = "cobra_annotation_bash_completion_custom" + BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag" + BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir" +) + +func writePreamble(buf io.StringWriter, name string) { + WriteStringAndCheck(buf, fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name)) + WriteStringAndCheck(buf, fmt.Sprintf(` +__%[1]s_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE:-} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi +} + +# Homebrew on Macs have version 1.3 of bash-completion which doesn't include +# _init_completion. This is a very minimal version of that function. +__%[1]s_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +__%[1]s_index_of_word() +{ + local w word=$1 + shift + index=0 + for w in "$@"; do + [[ $w = "$word" ]] && return + index=$((index+1)) + done + index=-1 +} + +__%[1]s_contains_word() +{ + local w word=$1; shift + for w in "$@"; do + [[ $w = "$word" ]] && return + done + return 1 +} + +__%[1]s_handle_go_custom_completion() +{ + __%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}" + + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + + local out requestComp lastParam lastChar comp directive args + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly %[1]s allows handling aliases + args=("${words[@]:1}") + # Disable ActiveHelp which is not supported for bash completion v1 + requestComp="%[8]s=0 ${words[0]} %[2]s ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}" + + if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%%:*} + if [ "${directive}" = "${out}" ]; then + # There is not directive specified + directive=0 + fi + __%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}" + __%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + # Error code. No completion. + __%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code" + return + else + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "${FUNCNAME[0]}: activating no space" + compopt -o nospace + fi + fi + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + if [[ $(type -t compopt) = "builtin" ]]; then + __%[1]s_debug "${FUNCNAME[0]}: activating no file completion" + compopt +o default + fi + fi + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local fullFilter filter filteringCmd + # Do not use quotes around the $out variable or else newline + # characters will be kept. + for filter in ${out}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __%[1]s_debug "File filtering command: $filteringCmd" + $filteringCmd + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subdir + # Use printf to strip any trailing newline + subdir=$(printf "%%s" "${out}") + if [ -n "$subdir" ]; then + __%[1]s_debug "Listing directories in $subdir" + __%[1]s_handle_subdirs_in_dir_flag "$subdir" + else + __%[1]s_debug "Listing directories in ." + _filedir -d + fi + else + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${out}" -- "$cur") + fi +} + +__%[1]s_handle_reply() +{ + __%[1]s_debug "${FUNCNAME[0]}" + local comp + case $cur in + -*) + if [[ $(type -t compopt) = "builtin" ]]; then + compopt -o nospace + fi + local allflags + if [ ${#must_have_one_flag[@]} -ne 0 ]; then + allflags=("${must_have_one_flag[@]}") + else + allflags=("${flags[*]} ${two_word_flags[*]}") + fi + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${allflags[*]}" -- "$cur") + if [[ $(type -t compopt) = "builtin" ]]; then + [[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace + fi + + # complete after --flag=abc + if [[ $cur == *=* ]]; then + if [[ $(type -t compopt) = "builtin" ]]; then + compopt +o nospace + fi + + local index flag + flag="${cur%%=*}" + __%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}" + COMPREPLY=() + if [[ ${index} -ge 0 ]]; then + PREFIX="" + cur="${cur#*=}" + ${flags_completion[${index}]} + if [ -n "${ZSH_VERSION:-}" ]; then + # zsh completion needs --flag= prefix + eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )" + fi + fi + fi + + if [[ -z "${flag_parsing_disabled}" ]]; then + # If flag parsing is enabled, we have completed the flags and can return. + # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough + # to possibly call handle_go_custom_completion. + return 0; + fi + ;; + esac + + # check if we are handling a flag with special work handling + local index + __%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}" + if [[ ${index} -ge 0 ]]; then + ${flags_completion[${index}]} + return + fi + + # we are parsing a flag and don't have a special handler, no completion + if [[ ${cur} != "${words[cword]}" ]]; then + return + fi + + local completions + completions=("${commands[@]}") + if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then + completions+=("${must_have_one_noun[@]}") + elif [[ -n "${has_completion_function}" ]]; then + # if a go completion function is provided, defer to that function + __%[1]s_handle_go_custom_completion + fi + if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then + completions+=("${must_have_one_flag[@]}") + fi + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${completions[*]}" -- "$cur") + + if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then + while IFS='' read -r comp; do + COMPREPLY+=("$comp") + done < <(compgen -W "${noun_aliases[*]}" -- "$cur") + fi + + if [[ ${#COMPREPLY[@]} -eq 0 ]]; then + if declare -F __%[1]s_custom_func >/dev/null; then + # try command name qualified custom func + __%[1]s_custom_func + else + # otherwise fall back to unqualified for compatibility + declare -F __custom_func >/dev/null && __custom_func + fi + fi + + # available in bash-completion >= 2, not always present on macOS + if declare -F __ltrim_colon_completions >/dev/null; then + __ltrim_colon_completions "$cur" + fi + + # If there is only 1 completion and it is a flag with an = it will be completed + # but we don't want a space after the = + if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then + compopt -o nospace + fi +} + +# The arguments should be in the form "ext1|ext2|extn" +__%[1]s_handle_filename_extension_flag() +{ + local ext="$1" + _filedir "@(${ext})" +} + +__%[1]s_handle_subdirs_in_dir_flag() +{ + local dir="$1" + pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return +} + +__%[1]s_handle_flag() +{ + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + + # if a command required a flag, and we found it, unset must_have_one_flag() + local flagname=${words[c]} + local flagvalue="" + # if the word contained an = + if [[ ${words[c]} == *"="* ]]; then + flagvalue=${flagname#*=} # take in as flagvalue after the = + flagname=${flagname%%=*} # strip everything after the = + flagname="${flagname}=" # but put the = back + fi + __%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}" + if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then + must_have_one_flag=() + fi + + # if you set a flag which only applies to this command, don't show subcommands + if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then + commands=() + fi + + # keep flag value with flagname as flaghash + # flaghash variable is an associative array which is only supported in bash > 3. + if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then + if [ -n "${flagvalue}" ] ; then + flaghash[${flagname}]=${flagvalue} + elif [ -n "${words[ $((c+1)) ]}" ] ; then + flaghash[${flagname}]=${words[ $((c+1)) ]} + else + flaghash[${flagname}]="true" # pad "true" for bool flag + fi + fi + + # skip the argument to a two word flag + if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then + __%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument" + c=$((c+1)) + # if we are looking for a flags value, don't show commands + if [[ $c -eq $cword ]]; then + commands=() + fi + fi + + c=$((c+1)) + +} + +__%[1]s_handle_noun() +{ + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + + if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then + must_have_one_noun=() + elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then + must_have_one_noun=() + fi + + nouns+=("${words[c]}") + c=$((c+1)) +} + +__%[1]s_handle_command() +{ + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + + local next_command + if [[ -n ${last_command} ]]; then + next_command="_${last_command}_${words[c]//:/__}" + else + if [[ $c -eq 0 ]]; then + next_command="_%[1]s_root_command" + else + next_command="_${words[c]//:/__}" + fi + fi + c=$((c+1)) + __%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}" + declare -F "$next_command" >/dev/null && $next_command +} + +__%[1]s_handle_word() +{ + if [[ $c -ge $cword ]]; then + __%[1]s_handle_reply + return + fi + __%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}" + if [[ "${words[c]}" == -* ]]; then + __%[1]s_handle_flag + elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then + __%[1]s_handle_command + elif [[ $c -eq 0 ]]; then + __%[1]s_handle_command + elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then + # aliashash variable is an associative array which is only supported in bash > 3. + if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then + words[c]=${aliashash[${words[c]}]} + __%[1]s_handle_command + else + __%[1]s_handle_noun + fi + else + __%[1]s_handle_noun + fi + __%[1]s_handle_word +} + +`, name, ShellCompNoDescRequestCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, activeHelpEnvVar(name))) +} + +func writePostscript(buf io.StringWriter, name string) { + name = strings.ReplaceAll(name, ":", "__") + WriteStringAndCheck(buf, fmt.Sprintf("__start_%s()\n", name)) + WriteStringAndCheck(buf, fmt.Sprintf(`{ + local cur prev words cword split + declare -A flaghash 2>/dev/null || : + declare -A aliashash 2>/dev/null || : + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -s || return + else + __%[1]s_init_completion -n "=" || return + fi + + local c=0 + local flag_parsing_disabled= + local flags=() + local two_word_flags=() + local local_nonpersistent_flags=() + local flags_with_completion=() + local flags_completion=() + local commands=("%[1]s") + local command_aliases=() + local must_have_one_flag=() + local must_have_one_noun=() + local has_completion_function="" + local last_command="" + local nouns=() + local noun_aliases=() + + __%[1]s_handle_word +} + +`, name)) + WriteStringAndCheck(buf, fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_%s %s +else + complete -o default -o nospace -F __start_%s %s +fi + +`, name, name, name, name)) + WriteStringAndCheck(buf, "# ex: ts=4 sw=4 et filetype=sh\n") +} + +func writeCommands(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " commands=()\n") + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() && c != cmd.helpCommand { + continue + } + WriteStringAndCheck(buf, fmt.Sprintf(" commands+=(%q)\n", c.Name())) + writeCmdAliases(buf, c) + } + WriteStringAndCheck(buf, "\n") +} + +func writeFlagHandler(buf io.StringWriter, name string, annotations map[string][]string, cmd *Command) { + for key, value := range annotations { + switch key { + case BashCompFilenameExt: + WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + + var ext string + if len(value) > 0 { + ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|") + } else { + ext = "_filedir" + } + WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) + case BashCompCustom: + WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + + if len(value) > 0 { + handlers := strings.Join(value, "; ") + WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", handlers)) + } else { + WriteStringAndCheck(buf, " flags_completion+=(:)\n") + } + case BashCompSubdirsInDir: + WriteStringAndCheck(buf, fmt.Sprintf(" flags_with_completion+=(%q)\n", name)) + + var ext string + if len(value) == 1 { + ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0] + } else { + ext = "_filedir -d" + } + WriteStringAndCheck(buf, fmt.Sprintf(" flags_completion+=(%q)\n", ext)) + } + } +} + +const cbn = "\")\n" + +func writeShortFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { + name := flag.Shorthand + format := " " + if len(flag.NoOptDefVal) == 0 { + format += "two_word_" + } + format += "flags+=(\"-%s" + cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + writeFlagHandler(buf, "-"+name, flag.Annotations, cmd) +} + +func writeFlag(buf io.StringWriter, flag *pflag.Flag, cmd *Command) { + name := flag.Name + format := " flags+=(\"--%s" + if len(flag.NoOptDefVal) == 0 { + format += "=" + } + format += cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + if len(flag.NoOptDefVal) == 0 { + format = " two_word_flags+=(\"--%s" + cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + } + writeFlagHandler(buf, "--"+name, flag.Annotations, cmd) +} + +func writeLocalNonPersistentFlag(buf io.StringWriter, flag *pflag.Flag) { + name := flag.Name + format := " local_nonpersistent_flags+=(\"--%[1]s" + cbn + if len(flag.NoOptDefVal) == 0 { + format += " local_nonpersistent_flags+=(\"--%[1]s=" + cbn + } + WriteStringAndCheck(buf, fmt.Sprintf(format, name)) + if len(flag.Shorthand) > 0 { + WriteStringAndCheck(buf, fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand)) + } +} + +// prepareCustomAnnotationsForFlags setup annotations for go completions for registered flags +func prepareCustomAnnotationsForFlags(cmd *Command) { + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() + for flag := range flagCompletionFunctions { + // Make sure the completion script calls the __*_go_custom_completion function for + // every registered flag. We need to do this here (and not when the flag was registered + // for completion) so that we can know the root command name for the prefix + // of ___go_custom_completion + if flag.Annotations == nil { + flag.Annotations = map[string][]string{} + } + flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())} + } +} + +func writeFlags(buf io.StringWriter, cmd *Command) { + prepareCustomAnnotationsForFlags(cmd) + WriteStringAndCheck(buf, ` flags=() + two_word_flags=() + local_nonpersistent_flags=() + flags_with_completion=() + flags_completion=() + +`) + + if cmd.DisableFlagParsing { + WriteStringAndCheck(buf, " flag_parsing_disabled=1\n") + } + + localNonPersistentFlags := cmd.LocalNonPersistentFlags() + cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + writeFlag(buf, flag, cmd) + if len(flag.Shorthand) > 0 { + writeShortFlag(buf, flag, cmd) + } + // localNonPersistentFlags are used to stop the completion of subcommands when one is set + // if TraverseChildren is true we should allow to complete subcommands + if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren { + writeLocalNonPersistentFlag(buf, flag) + } + }) + cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + writeFlag(buf, flag, cmd) + if len(flag.Shorthand) > 0 { + writeShortFlag(buf, flag, cmd) + } + }) + + WriteStringAndCheck(buf, "\n") +} + +func writeRequiredFlag(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " must_have_one_flag=()\n") + flags := cmd.NonInheritedFlags() + flags.VisitAll(func(flag *pflag.Flag) { + if nonCompletableFlag(flag) { + return + } + if _, ok := flag.Annotations[BashCompOneRequiredFlag]; ok { + format := " must_have_one_flag+=(\"--%s" + if flag.Value.Type() != "bool" { + format += "=" + } + format += cbn + WriteStringAndCheck(buf, fmt.Sprintf(format, flag.Name)) + + if len(flag.Shorthand) > 0 { + WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_flag+=(\"-%s"+cbn, flag.Shorthand)) + } + } + }) +} + +func writeRequiredNouns(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " must_have_one_noun=()\n") + sort.Strings(cmd.ValidArgs) + for _, value := range cmd.ValidArgs { + // Remove any description that may be included following a tab character. + // Descriptions are not supported by bash completion. + value = strings.SplitN(value, "\t", 2)[0] + WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value)) + } + if cmd.ValidArgsFunction != nil { + WriteStringAndCheck(buf, " has_completion_function=1\n") + } +} + +func writeCmdAliases(buf io.StringWriter, cmd *Command) { + if len(cmd.Aliases) == 0 { + return + } + + sort.Strings(cmd.Aliases) + + WriteStringAndCheck(buf, fmt.Sprint(` if [[ -z "${BASH_VERSION:-}" || "${BASH_VERSINFO[0]:-}" -gt 3 ]]; then`, "\n")) + for _, value := range cmd.Aliases { + WriteStringAndCheck(buf, fmt.Sprintf(" command_aliases+=(%q)\n", value)) + WriteStringAndCheck(buf, fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name())) + } + WriteStringAndCheck(buf, ` fi`) + WriteStringAndCheck(buf, "\n") +} +func writeArgAliases(buf io.StringWriter, cmd *Command) { + WriteStringAndCheck(buf, " noun_aliases=()\n") + sort.Strings(cmd.ArgAliases) + for _, value := range cmd.ArgAliases { + WriteStringAndCheck(buf, fmt.Sprintf(" noun_aliases+=(%q)\n", value)) + } +} + +func gen(buf io.StringWriter, cmd *Command) { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() && c != cmd.helpCommand { + continue + } + gen(buf, c) + } + commandName := cmd.CommandPath() + commandName = strings.ReplaceAll(commandName, " ", "_") + commandName = strings.ReplaceAll(commandName, ":", "__") + + if cmd.Root() == cmd { + WriteStringAndCheck(buf, fmt.Sprintf("_%s_root_command()\n{\n", commandName)) + } else { + WriteStringAndCheck(buf, fmt.Sprintf("_%s()\n{\n", commandName)) + } + + WriteStringAndCheck(buf, fmt.Sprintf(" last_command=%q\n", commandName)) + WriteStringAndCheck(buf, "\n") + WriteStringAndCheck(buf, " command_aliases=()\n") + WriteStringAndCheck(buf, "\n") + + writeCommands(buf, cmd) + writeFlags(buf, cmd) + writeRequiredFlag(buf, cmd) + writeRequiredNouns(buf, cmd) + writeArgAliases(buf, cmd) + WriteStringAndCheck(buf, "}\n\n") +} + +// GenBashCompletion generates bash completion file and writes to the passed writer. +func (c *Command) GenBashCompletion(w io.Writer) error { + buf := new(bytes.Buffer) + writePreamble(buf, c.Name()) + if len(c.BashCompletionFunction) > 0 { + buf.WriteString(c.BashCompletionFunction + "\n") + } + gen(buf, c) + writePostscript(buf, c.Name()) + + _, err := buf.WriteTo(w) + return err +} + +func nonCompletableFlag(flag *pflag.Flag) bool { + return flag.Hidden || len(flag.Deprecated) > 0 +} + +// GenBashCompletionFile generates bash completion file. +func (c *Command) GenBashCompletionFile(filename string) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenBashCompletion(outFile) +} diff --git a/vendor/github.com/spf13/cobra/bash_completionsV2.go b/vendor/github.com/spf13/cobra/bash_completionsV2.go new file mode 100644 index 0000000..d2397aa --- /dev/null +++ b/vendor/github.com/spf13/cobra/bash_completionsV2.go @@ -0,0 +1,484 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" +) + +func (c *Command) genBashCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genBashComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func genBashComp(buf io.StringWriter, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + + WriteStringAndCheck(buf, fmt.Sprintf(`# bash completion V2 for %-36[1]s -*- shell-script -*- + +__%[1]s_debug() +{ + if [[ -n ${BASH_COMP_DEBUG_FILE-} ]]; then + echo "$*" >> "${BASH_COMP_DEBUG_FILE}" + fi +} + +# Macs have bash3 for which the bash-completion package doesn't include +# _init_completion. This is a minimal version of that function. +__%[1]s_init_completion() +{ + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +# This function calls the %[1]s program to obtain the completion +# results and the directive. It fills the 'out' and 'directive' vars. +__%[1]s_get_completion_results() { + local requestComp lastParam lastChar args + + # Prepare the command to request completions for the program. + # Calling ${words[0]} instead of directly %[1]s allows handling aliases + args=("${words[@]:1}") + requestComp="${words[0]} %[2]s ${args[*]}" + + lastParam=${words[$((${#words[@]}-1))]} + lastChar=${lastParam:$((${#lastParam}-1)):1} + __%[1]s_debug "lastParam ${lastParam}, lastChar ${lastChar}" + + if [[ -z ${cur} && ${lastChar} != = ]]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "Adding extra empty parameter" + requestComp="${requestComp} ''" + fi + + # When completing a flag with an = (e.g., %[1]s -n=) + # bash focuses on the part after the =, so we need to remove + # the flag part from $cur + if [[ ${cur} == -*=* ]]; then + cur="${cur#*=}" + fi + + __%[1]s_debug "Calling ${requestComp}" + # Use eval to handle any environment variables and such + out=$(eval "${requestComp}" 2>/dev/null) + + # Extract the directive integer at the very end of the output following a colon (:) + directive=${out##*:} + # Remove the directive + out=${out%%:*} + if [[ ${directive} == "${out}" ]]; then + # There is not directive specified + directive=0 + fi + __%[1]s_debug "The completion directive is: ${directive}" + __%[1]s_debug "The completions are: ${out}" +} + +__%[1]s_process_completion_results() { + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d + + if (((directive & shellCompDirectiveError) != 0)); then + # Error code. No completion. + __%[1]s_debug "Received error from custom completion go code" + return + else + if (((directive & shellCompDirectiveNoSpace) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + __%[1]s_debug "Activating no space" + compopt -o nospace + else + __%[1]s_debug "No space directive not supported in this version of bash" + fi + fi + if (((directive & shellCompDirectiveKeepOrder) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + # no sort isn't supported for bash less than < 4.4 + if [[ ${BASH_VERSINFO[0]} -lt 4 || ( ${BASH_VERSINFO[0]} -eq 4 && ${BASH_VERSINFO[1]} -lt 4 ) ]]; then + __%[1]s_debug "No sort directive not supported in this version of bash" + else + __%[1]s_debug "Activating keep order" + compopt -o nosort + fi + else + __%[1]s_debug "No sort directive not supported in this version of bash" + fi + fi + if (((directive & shellCompDirectiveNoFileComp) != 0)); then + if [[ $(type -t compopt) == builtin ]]; then + __%[1]s_debug "Activating no file completion" + compopt +o default + else + __%[1]s_debug "No file completion directive not supported in this version of bash" + fi + fi + fi + + # Separate activeHelp from normal completions + local completions=() + local activeHelp=() + __%[1]s_extract_activeHelp + + if (((directive & shellCompDirectiveFilterFileExt) != 0)); then + # File extension filtering + local fullFilter="" filter filteringCmd + + # Do not use quotes around the $completions variable or else newline + # characters will be kept. + for filter in ${completions[*]}; do + fullFilter+="$filter|" + done + + filteringCmd="_filedir $fullFilter" + __%[1]s_debug "File filtering command: $filteringCmd" + $filteringCmd + elif (((directive & shellCompDirectiveFilterDirs) != 0)); then + # File completion for directories only + + local subdir + subdir=${completions[0]} + if [[ -n $subdir ]]; then + __%[1]s_debug "Listing directories in $subdir" + pushd "$subdir" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return + else + __%[1]s_debug "Listing directories in ." + _filedir -d + fi + else + __%[1]s_handle_completion_types + fi + + __%[1]s_handle_special_char "$cur" : + __%[1]s_handle_special_char "$cur" = + + # Print the activeHelp statements before we finish + __%[1]s_handle_activeHelp +} + +__%[1]s_handle_activeHelp() { + # Print the activeHelp statements + if ((${#activeHelp[*]} != 0)); then + if [ -z $COMP_TYPE ]; then + # Bash v3 does not set the COMP_TYPE variable. + printf "\n"; + printf "%%s\n" "${activeHelp[@]}" + printf "\n" + __%[1]s_reprint_commandLine + return + fi + + # Only print ActiveHelp on the second TAB press + if [ $COMP_TYPE -eq 63 ]; then + printf "\n" + printf "%%s\n" "${activeHelp[@]}" + + if ((${#COMPREPLY[*]} == 0)); then + # When there are no completion choices from the program, file completion + # may kick in if the program has not disabled it; in such a case, we want + # to know if any files will match what the user typed, so that we know if + # there will be completions presented, so that we know how to handle ActiveHelp. + # To find out, we actually trigger the file completion ourselves; + # the call to _filedir will fill COMPREPLY if files match. + if (((directive & shellCompDirectiveNoFileComp) == 0)); then + __%[1]s_debug "Listing files" + _filedir + fi + fi + + if ((${#COMPREPLY[*]} != 0)); then + # If there are completion choices to be shown, print a delimiter. + # Re-printing the command-line will automatically be done + # by the shell when it prints the completion choices. + printf -- "--" + else + # When there are no completion choices at all, we need + # to re-print the command-line since the shell will + # not be doing it itself. + __%[1]s_reprint_commandLine + fi + elif [ $COMP_TYPE -eq 37 ] || [ $COMP_TYPE -eq 42 ]; then + # For completion type: menu-complete/menu-complete-backward and insert-completions + # the completions are immediately inserted into the command-line, so we first + # print the activeHelp message and reprint the command-line since the shell won't. + printf "\n" + printf "%%s\n" "${activeHelp[@]}" + + __%[1]s_reprint_commandLine + fi + fi +} + +__%[1]s_reprint_commandLine() { + # The prompt format is only available from bash 4.4. + # We test if it is available before using it. + if (x=${PS1@P}) 2> /dev/null; then + printf "%%s" "${PS1@P}${COMP_LINE[@]}" + else + # Can't print the prompt. Just print the + # text the user had typed, it is workable enough. + printf "%%s" "${COMP_LINE[@]}" + fi +} + +# Separate activeHelp lines from real completions. +# Fills the $activeHelp and $completions arrays. +__%[1]s_extract_activeHelp() { + local activeHelpMarker="%[9]s" + local endIndex=${#activeHelpMarker} + + while IFS='' read -r comp; do + [[ -z $comp ]] && continue + + if [[ ${comp:0:endIndex} == $activeHelpMarker ]]; then + comp=${comp:endIndex} + __%[1]s_debug "ActiveHelp found: $comp" + if [[ -n $comp ]]; then + activeHelp+=("$comp") + fi + else + # Not an activeHelp line but a normal completion + completions+=("$comp") + fi + done <<<"${out}" +} + +__%[1]s_handle_completion_types() { + __%[1]s_debug "__%[1]s_handle_completion_types: COMP_TYPE is $COMP_TYPE" + + case $COMP_TYPE in + 37|42) + # Type: menu-complete/menu-complete-backward and insert-completions + # If the user requested inserting one completion at a time, or all + # completions at once on the command-line we must remove the descriptions. + # https://github.com/spf13/cobra/issues/1508 + + # If there are no completions, we don't need to do anything + (( ${#completions[@]} == 0 )) && return 0 + + local tab=$'\t' + + # Strip any description and escape the completion to handled special characters + IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]%%%%$tab*}") + + # Only consider the completions that match + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") + + # compgen looses the escaping so we need to escape all completions again since they will + # all be inserted on the command-line. + IFS=$'\n' read -ra COMPREPLY -d '' < <(printf "%%q\n" "${COMPREPLY[@]}") + ;; + + *) + # Type: complete (normal completion) + __%[1]s_handle_standard_completion_case + ;; + esac +} + +__%[1]s_handle_standard_completion_case() { + local tab=$'\t' + + # If there are no completions, we don't need to do anything + (( ${#completions[@]} == 0 )) && return 0 + + # Short circuit to optimize if we don't have descriptions + if [[ "${completions[*]}" != *$tab* ]]; then + # First, escape the completions to handle special characters + IFS=$'\n' read -ra completions -d '' < <(printf "%%q\n" "${completions[@]}") + # Only consider the completions that match what the user typed + IFS=$'\n' read -ra COMPREPLY -d '' < <(IFS=$'\n'; compgen -W "${completions[*]}" -- "${cur}") + + # compgen looses the escaping so, if there is only a single completion, we need to + # escape it again because it will be inserted on the command-line. If there are multiple + # completions, we don't want to escape them because they will be printed in a list + # and we don't want to show escape characters in that list. + if (( ${#COMPREPLY[@]} == 1 )); then + COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]}") + fi + return 0 + fi + + local longest=0 + local compline + # Look for the longest completion so that we can format things nicely + while IFS='' read -r compline; do + [[ -z $compline ]] && continue + + # Before checking if the completion matches what the user typed, + # we need to strip any description and escape the completion to handle special + # characters because those escape characters are part of what the user typed. + # Don't call "printf" in a sub-shell because it will be much slower + # since we are in a loop. + printf -v comp "%%q" "${compline%%%%$tab*}" &>/dev/null || comp=$(printf "%%q" "${compline%%%%$tab*}") + + # Only consider the completions that match + [[ $comp == "$cur"* ]] || continue + + # The completions matches. Add it to the list of full completions including + # its description. We don't escape the completion because it may get printed + # in a list if there are more than one and we don't want show escape characters + # in that list. + COMPREPLY+=("$compline") + + # Strip any description before checking the length, and again, don't escape + # the completion because this length is only used when printing the completions + # in a list and we don't want show escape characters in that list. + comp=${compline%%%%$tab*} + if ((${#comp}>longest)); then + longest=${#comp} + fi + done < <(printf "%%s\n" "${completions[@]}") + + # If there is a single completion left, remove the description text and escape any special characters + if ((${#COMPREPLY[*]} == 1)); then + __%[1]s_debug "COMPREPLY[0]: ${COMPREPLY[0]}" + COMPREPLY[0]=$(printf "%%q" "${COMPREPLY[0]%%%%$tab*}") + __%[1]s_debug "Removed description from single completion, which is now: ${COMPREPLY[0]}" + else + # Format the descriptions + __%[1]s_format_comp_descriptions $longest + fi +} + +__%[1]s_handle_special_char() +{ + local comp="$1" + local char=$2 + if [[ "$comp" == *${char}* && "$COMP_WORDBREAKS" == *${char}* ]]; then + local word=${comp%%"${comp##*${char}}"} + local idx=${#COMPREPLY[*]} + while ((--idx >= 0)); do + COMPREPLY[idx]=${COMPREPLY[idx]#"$word"} + done + fi +} + +__%[1]s_format_comp_descriptions() +{ + local tab=$'\t' + local comp desc maxdesclength + local longest=$1 + + local i ci + for ci in ${!COMPREPLY[*]}; do + comp=${COMPREPLY[ci]} + # Properly format the description string which follows a tab character if there is one + if [[ "$comp" == *$tab* ]]; then + __%[1]s_debug "Original comp: $comp" + desc=${comp#*$tab} + comp=${comp%%%%$tab*} + + # $COLUMNS stores the current shell width. + # Remove an extra 4 because we add 2 spaces and 2 parentheses. + maxdesclength=$(( COLUMNS - longest - 4 )) + + # Make sure we can fit a description of at least 8 characters + # if we are to align the descriptions. + if ((maxdesclength > 8)); then + # Add the proper number of spaces to align the descriptions + for ((i = ${#comp} ; i < longest ; i++)); do + comp+=" " + done + else + # Don't pad the descriptions so we can fit more text after the completion + maxdesclength=$(( COLUMNS - ${#comp} - 4 )) + fi + + # If there is enough space for any description text, + # truncate the descriptions that are too long for the shell width + if ((maxdesclength > 0)); then + if ((${#desc} > maxdesclength)); then + desc=${desc:0:$(( maxdesclength - 1 ))} + desc+="…" + fi + comp+=" ($desc)" + fi + COMPREPLY[ci]=$comp + __%[1]s_debug "Final comp: $comp" + fi + done +} + +__start_%[1]s() +{ + local cur prev words cword split + + COMPREPLY=() + + # Call _init_completion from the bash-completion package + # to prepare the arguments properly + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n =: || return + else + __%[1]s_init_completion -n =: || return + fi + + __%[1]s_debug + __%[1]s_debug "========= starting completion logic ==========" + __%[1]s_debug "cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}, cword is $cword" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $cword location, so we need + # to truncate the command-line ($words) up to the $cword location. + words=("${words[@]:0:$cword+1}") + __%[1]s_debug "Truncated words[*]: ${words[*]}," + + local out directive + __%[1]s_get_completion_results + __%[1]s_process_completion_results +} + +if [[ $(type -t compopt) = "builtin" ]]; then + complete -o default -F __start_%[1]s %[1]s +else + complete -o default -o nospace -F __start_%[1]s %[1]s +fi + +# ex: ts=4 sw=4 et filetype=sh +`, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, + activeHelpMarker)) +} + +// GenBashCompletionFileV2 generates Bash completion version 2. +func (c *Command) GenBashCompletionFileV2(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenBashCompletionV2(outFile, includeDesc) +} + +// GenBashCompletionV2 generates Bash completion file version 2 +// and writes it to the passed writer. +func (c *Command) GenBashCompletionV2(w io.Writer, includeDesc bool) error { + return c.genBashCompletion(w, includeDesc) +} diff --git a/vendor/github.com/spf13/cobra/cobra.go b/vendor/github.com/spf13/cobra/cobra.go new file mode 100644 index 0000000..d9cd241 --- /dev/null +++ b/vendor/github.com/spf13/cobra/cobra.go @@ -0,0 +1,246 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Commands similar to git, go tools and other modern CLI tools +// inspired by go, go-Commander, gh and subcommand + +package cobra + +import ( + "fmt" + "io" + "os" + "reflect" + "strconv" + "strings" + "text/template" + "time" + "unicode" +) + +var templateFuncs = template.FuncMap{ + "trim": strings.TrimSpace, + "trimRightSpace": trimRightSpace, + "trimTrailingWhitespaces": trimRightSpace, + "appendIfNotPresent": appendIfNotPresent, + "rpad": rpad, + "gt": Gt, + "eq": Eq, +} + +var initializers []func() +var finalizers []func() + +const ( + defaultPrefixMatching = false + defaultCommandSorting = true + defaultCaseInsensitive = false + defaultTraverseRunHooks = false +) + +// EnablePrefixMatching allows setting automatic prefix matching. Automatic prefix matching can be a dangerous thing +// to automatically enable in CLI tools. +// Set this to true to enable it. +var EnablePrefixMatching = defaultPrefixMatching + +// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default. +// To disable sorting, set it to false. +var EnableCommandSorting = defaultCommandSorting + +// EnableCaseInsensitive allows case-insensitive commands names. (case sensitive by default) +var EnableCaseInsensitive = defaultCaseInsensitive + +// EnableTraverseRunHooks executes persistent pre-run and post-run hooks from all parents. +// By default this is disabled, which means only the first run hook to be found is executed. +var EnableTraverseRunHooks = defaultTraverseRunHooks + +// MousetrapHelpText enables an information splash screen on Windows +// if the CLI is started from explorer.exe. +// To disable the mousetrap, just set this variable to blank string (""). +// Works only on Microsoft Windows. +var MousetrapHelpText = `This is a command line tool. + +You need to open cmd.exe and run it from there. +` + +// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows +// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed. +// To disable the mousetrap, just set MousetrapHelpText to blank string (""). +// Works only on Microsoft Windows. +var MousetrapDisplayDuration = 5 * time.Second + +// AddTemplateFunc adds a template function that's available to Usage and Help +// template generation. +func AddTemplateFunc(name string, tmplFunc interface{}) { + templateFuncs[name] = tmplFunc +} + +// AddTemplateFuncs adds multiple template functions that are available to Usage and +// Help template generation. +func AddTemplateFuncs(tmplFuncs template.FuncMap) { + for k, v := range tmplFuncs { + templateFuncs[k] = v + } +} + +// OnInitialize sets the passed functions to be run when each command's +// Execute method is called. +func OnInitialize(y ...func()) { + initializers = append(initializers, y...) +} + +// OnFinalize sets the passed functions to be run when each command's +// Execute method is terminated. +func OnFinalize(y ...func()) { + finalizers = append(finalizers, y...) +} + +// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. + +// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, +// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as +// ints and then compared. +func Gt(a interface{}, b interface{}) bool { + var left, right int64 + av := reflect.ValueOf(a) + + switch av.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + left = int64(av.Len()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + left = av.Int() + case reflect.String: + left, _ = strconv.ParseInt(av.String(), 10, 64) + } + + bv := reflect.ValueOf(b) + + switch bv.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + right = int64(bv.Len()) + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + right = bv.Int() + case reflect.String: + right, _ = strconv.ParseInt(bv.String(), 10, 64) + } + + return left > right +} + +// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. + +// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic. +func Eq(a interface{}, b interface{}) bool { + av := reflect.ValueOf(a) + bv := reflect.ValueOf(b) + + switch av.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice: + panic("Eq called on unsupported type") + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return av.Int() == bv.Int() + case reflect.String: + return av.String() == bv.String() + } + return false +} + +func trimRightSpace(s string) string { + return strings.TrimRightFunc(s, unicode.IsSpace) +} + +// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra. + +// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s. +func appendIfNotPresent(s, stringToAppend string) string { + if strings.Contains(s, stringToAppend) { + return s + } + return s + " " + stringToAppend +} + +// rpad adds padding to the right of a string. +func rpad(s string, padding int) string { + formattedString := fmt.Sprintf("%%-%ds", padding) + return fmt.Sprintf(formattedString, s) +} + +func tmpl(text string) *tmplFunc { + return &tmplFunc{ + tmpl: text, + fn: func(w io.Writer, data interface{}) error { + t := template.New("top") + t.Funcs(templateFuncs) + template.Must(t.Parse(text)) + return t.Execute(w, data) + }, + } +} + +// ld compares two strings and returns the levenshtein distance between them. +func ld(s, t string, ignoreCase bool) int { + if ignoreCase { + s = strings.ToLower(s) + t = strings.ToLower(t) + } + d := make([][]int, len(s)+1) + for i := range d { + d[i] = make([]int, len(t)+1) + d[i][0] = i + } + for j := range d[0] { + d[0][j] = j + } + for j := 1; j <= len(t); j++ { + for i := 1; i <= len(s); i++ { + if s[i-1] == t[j-1] { + d[i][j] = d[i-1][j-1] + } else { + min := d[i-1][j] + if d[i][j-1] < min { + min = d[i][j-1] + } + if d[i-1][j-1] < min { + min = d[i-1][j-1] + } + d[i][j] = min + 1 + } + } + + } + return d[len(s)][len(t)] +} + +func stringInSlice(a string, list []string) bool { + for _, b := range list { + if b == a { + return true + } + } + return false +} + +// CheckErr prints the msg with the prefix 'Error:' and exits with error code 1. If the msg is nil, it does nothing. +func CheckErr(msg interface{}) { + if msg != nil { + fmt.Fprintln(os.Stderr, "Error:", msg) + os.Exit(1) + } +} + +// WriteStringAndCheck writes a string into a buffer, and checks if the error is not nil. +func WriteStringAndCheck(b io.StringWriter, s string) { + _, err := b.WriteString(s) + CheckErr(err) +} diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go new file mode 100644 index 0000000..c05fed4 --- /dev/null +++ b/vendor/github.com/spf13/cobra/command.go @@ -0,0 +1,2072 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package cobra is a commander providing a simple interface to create powerful modern CLI interfaces. +// In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. +package cobra + +import ( + "bytes" + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + flag "github.com/spf13/pflag" +) + +const ( + FlagSetByCobraAnnotation = "cobra_annotation_flag_set_by_cobra" + CommandDisplayNameAnnotation = "cobra_annotation_command_display_name" + + helpFlagName = "help" + helpCommandName = "help" +) + +// FParseErrWhitelist configures Flag parse errors to be ignored +type FParseErrWhitelist flag.ParseErrorsAllowlist + +// Group Structure to manage groups for commands +type Group struct { + ID string + Title string +} + +// Command is just that, a command for your application. +// E.g. 'go run ...' - 'run' is the command. Cobra requires +// you to define the usage and description as part of your command +// definition to ensure usability. +type Command struct { + // Use is the one-line usage message. + // Recommended syntax is as follows: + // [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required. + // ... indicates that you can specify multiple values for the previous argument. + // | indicates mutually exclusive information. You can use the argument to the left of the separator or the + // argument to the right of the separator. You cannot use both arguments in a single use of the command. + // { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are + // optional, they are enclosed in brackets ([ ]). + // Example: add [-F file | -D dir]... [-f format] profile + Use string + + // Aliases is an array of aliases that can be used instead of the first word in Use. + Aliases []string + + // SuggestFor is an array of command names for which this command will be suggested - + // similar to aliases but only suggests. + SuggestFor []string + + // Short is the short description shown in the 'help' output. + Short string + + // The group id under which this subcommand is grouped in the 'help' output of its parent. + GroupID string + + // Long is the long message shown in the 'help ' output. + Long string + + // Example is examples of how to use the command. + Example string + + // ValidArgs is list of all valid non-flag arguments that are accepted in shell completions + ValidArgs []Completion + // ValidArgsFunction is an optional function that provides valid non-flag arguments for shell completion. + // It is a dynamic version of using ValidArgs. + // Only one of ValidArgs and ValidArgsFunction can be used for a command. + ValidArgsFunction CompletionFunc + + // Expected arguments + Args PositionalArgs + + // ArgAliases is List of aliases for ValidArgs. + // These are not suggested to the user in the shell completion, + // but accepted if entered manually. + ArgAliases []string + + // BashCompletionFunction is custom bash functions used by the legacy bash autocompletion generator. + // For portability with other shells, it is recommended to instead use ValidArgsFunction + BashCompletionFunction string + + // Deprecated defines, if this command is deprecated and should print this string when used. + Deprecated string + + // Annotations are key/value pairs that can be used by applications to identify or + // group commands or set special options. + Annotations map[string]string + + // Version defines the version for this command. If this value is non-empty and the command does not + // define a "version" flag, a "version" boolean flag will be added to the command and, if specified, + // will print content of the "Version" variable. A shorthand "v" flag will also be added if the + // command does not define one. + Version string + + // The *Run functions are executed in the following order: + // * PersistentPreRun() + // * PreRun() + // * Run() + // * PostRun() + // * PersistentPostRun() + // All functions get the same args, the arguments after the command name. + // The *PreRun and *PostRun functions will only be executed if the Run function of the current + // command has been declared. + // + // PersistentPreRun: children of this command will inherit and execute. + PersistentPreRun func(cmd *Command, args []string) + // PersistentPreRunE: PersistentPreRun but returns an error. + PersistentPreRunE func(cmd *Command, args []string) error + // PreRun: children of this command will not inherit. + PreRun func(cmd *Command, args []string) + // PreRunE: PreRun but returns an error. + PreRunE func(cmd *Command, args []string) error + // Run: Typically the actual work function. Most commands will only implement this. + Run func(cmd *Command, args []string) + // RunE: Run but returns an error. + RunE func(cmd *Command, args []string) error + // PostRun: run after the Run command. + PostRun func(cmd *Command, args []string) + // PostRunE: PostRun but returns an error. + PostRunE func(cmd *Command, args []string) error + // PersistentPostRun: children of this command will inherit and execute after PostRun. + PersistentPostRun func(cmd *Command, args []string) + // PersistentPostRunE: PersistentPostRun but returns an error. + PersistentPostRunE func(cmd *Command, args []string) error + + // groups for subcommands + commandgroups []*Group + + // args is actual args parsed from flags. + args []string + // flagErrorBuf contains all error messages from pflag. + flagErrorBuf *bytes.Buffer + // flags is full set of flags. + flags *flag.FlagSet + // pflags contains persistent flags. + pflags *flag.FlagSet + // lflags contains local flags. + // This field does not represent internal state, it's used as a cache to optimise LocalFlags function call + lflags *flag.FlagSet + // iflags contains inherited flags. + // This field does not represent internal state, it's used as a cache to optimise InheritedFlags function call + iflags *flag.FlagSet + // parentsPflags is all persistent flags of cmd's parents. + parentsPflags *flag.FlagSet + // globNormFunc is the global normalization function + // that we can use on every pflag set and children commands + globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName + + // usageFunc is usage func defined by user. + usageFunc func(*Command) error + // usageTemplate is usage template defined by user. + usageTemplate *tmplFunc + // flagErrorFunc is func defined by user and it's called when the parsing of + // flags returns an error. + flagErrorFunc func(*Command, error) error + // helpTemplate is help template defined by user. + helpTemplate *tmplFunc + // helpFunc is help func defined by user. + helpFunc func(*Command, []string) + // helpCommand is command with usage 'help'. If it's not defined by user, + // cobra uses default help command. + helpCommand *Command + // helpCommandGroupID is the group id for the helpCommand + helpCommandGroupID string + + // completionCommandGroupID is the group id for the completion command + completionCommandGroupID string + + // versionTemplate is the version template defined by user. + versionTemplate *tmplFunc + + // errPrefix is the error message prefix defined by user. + errPrefix string + + // inReader is a reader defined by the user that replaces stdin + inReader io.Reader + // outWriter is a writer defined by the user that replaces stdout + outWriter io.Writer + // errWriter is a writer defined by the user that replaces stderr + errWriter io.Writer + + // FParseErrWhitelist flag parse errors to be ignored + FParseErrWhitelist FParseErrWhitelist + + // CompletionOptions is a set of options to control the handling of shell completion + CompletionOptions CompletionOptions + + // commandsAreSorted defines, if command slice are sorted or not. + commandsAreSorted bool + // commandCalledAs is the name or alias value used to call this command. + commandCalledAs struct { + name string + called bool + } + + ctx context.Context + + // commands is the list of commands supported by this program. + commands []*Command + // parent is a parent command for this command. + parent *Command + // Max lengths of commands' string lengths for use in padding. + commandsMaxUseLen int + commandsMaxCommandPathLen int + commandsMaxNameLen int + + // TraverseChildren parses flags on all parents before executing child command. + TraverseChildren bool + + // Hidden defines, if this command is hidden and should NOT show up in the list of available commands. + Hidden bool + + // SilenceErrors is an option to quiet errors down stream. + SilenceErrors bool + + // SilenceUsage is an option to silence usage when an error occurs. + SilenceUsage bool + + // DisableFlagParsing disables the flag parsing. + // If this is true all flags will be passed to the command as arguments. + DisableFlagParsing bool + + // DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...") + // will be printed by generating docs for this command. + DisableAutoGenTag bool + + // DisableFlagsInUseLine will disable the addition of [flags] to the usage + // line of a command when printing help or generating docs + DisableFlagsInUseLine bool + + // DisableSuggestions disables the suggestions based on Levenshtein distance + // that go along with 'unknown command' messages. + DisableSuggestions bool + + // SuggestionsMinimumDistance defines minimum levenshtein distance to display suggestions. + // Must be > 0. + SuggestionsMinimumDistance int +} + +// Context returns underlying command context. If command was executed +// with ExecuteContext or the context was set with SetContext, the +// previously set context will be returned. Otherwise, nil is returned. +// +// Notice that a call to Execute and ExecuteC will replace a nil context of +// a command with a context.Background, so a background context will be +// returned by Context after one of these functions has been called. +func (c *Command) Context() context.Context { + return c.ctx +} + +// SetContext sets context for the command. This context will be overwritten by +// Command.ExecuteContext or Command.ExecuteContextC. +func (c *Command) SetContext(ctx context.Context) { + c.ctx = ctx +} + +// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden +// particularly useful when testing. +func (c *Command) SetArgs(a []string) { + c.args = a +} + +// SetOutput sets the destination for usage and error messages. +// If output is nil, os.Stderr is used. +// +// Deprecated: Use SetOut and/or SetErr instead +func (c *Command) SetOutput(output io.Writer) { + c.outWriter = output + c.errWriter = output +} + +// SetOut sets the destination for usage messages. +// If newOut is nil, os.Stdout is used. +func (c *Command) SetOut(newOut io.Writer) { + c.outWriter = newOut +} + +// SetErr sets the destination for error messages. +// If newErr is nil, os.Stderr is used. +func (c *Command) SetErr(newErr io.Writer) { + c.errWriter = newErr +} + +// SetIn sets the source for input data +// If newIn is nil, os.Stdin is used. +func (c *Command) SetIn(newIn io.Reader) { + c.inReader = newIn +} + +// SetUsageFunc sets usage function. Usage can be defined by application. +func (c *Command) SetUsageFunc(f func(*Command) error) { + c.usageFunc = f +} + +// SetUsageTemplate sets usage template. Can be defined by Application. +func (c *Command) SetUsageTemplate(s string) { + if s == "" { + c.usageTemplate = nil + return + } + c.usageTemplate = tmpl(s) +} + +// SetFlagErrorFunc sets a function to generate an error when flag parsing +// fails. +func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { + c.flagErrorFunc = f +} + +// SetHelpFunc sets help function. Can be defined by Application. +func (c *Command) SetHelpFunc(f func(*Command, []string)) { + c.helpFunc = f +} + +// SetHelpCommand sets help command. +func (c *Command) SetHelpCommand(cmd *Command) { + c.helpCommand = cmd +} + +// SetHelpCommandGroupID sets the group id of the help command. +func (c *Command) SetHelpCommandGroupID(groupID string) { + if c.helpCommand != nil { + c.helpCommand.GroupID = groupID + } + // helpCommandGroupID is used if no helpCommand is defined by the user + c.helpCommandGroupID = groupID +} + +// SetCompletionCommandGroupID sets the group id of the completion command. +func (c *Command) SetCompletionCommandGroupID(groupID string) { + // completionCommandGroupID is used if no completion command is defined by the user + c.Root().completionCommandGroupID = groupID +} + +// SetHelpTemplate sets help template to be used. Application can use it to set custom template. +func (c *Command) SetHelpTemplate(s string) { + if s == "" { + c.helpTemplate = nil + return + } + c.helpTemplate = tmpl(s) +} + +// SetVersionTemplate sets version template to be used. Application can use it to set custom template. +func (c *Command) SetVersionTemplate(s string) { + if s == "" { + c.versionTemplate = nil + return + } + c.versionTemplate = tmpl(s) +} + +// SetErrPrefix sets error message prefix to be used. Application can use it to set custom prefix. +func (c *Command) SetErrPrefix(s string) { + c.errPrefix = s +} + +// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. +// The user should not have a cyclic dependency on commands. +func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { + c.Flags().SetNormalizeFunc(n) + c.PersistentFlags().SetNormalizeFunc(n) + c.globNormFunc = n + + for _, command := range c.commands { + command.SetGlobalNormalizationFunc(n) + } +} + +// OutOrStdout returns output to stdout. +func (c *Command) OutOrStdout() io.Writer { + return c.getOut(os.Stdout) +} + +// OutOrStderr returns output to stderr +func (c *Command) OutOrStderr() io.Writer { + return c.getOut(os.Stderr) +} + +// ErrOrStderr returns output to stderr +func (c *Command) ErrOrStderr() io.Writer { + return c.getErr(os.Stderr) +} + +// InOrStdin returns input to stdin +func (c *Command) InOrStdin() io.Reader { + return c.getIn(os.Stdin) +} + +func (c *Command) getOut(def io.Writer) io.Writer { + if c.outWriter != nil { + return c.outWriter + } + if c.HasParent() { + return c.parent.getOut(def) + } + return def +} + +func (c *Command) getErr(def io.Writer) io.Writer { + if c.errWriter != nil { + return c.errWriter + } + if c.HasParent() { + return c.parent.getErr(def) + } + return def +} + +func (c *Command) getIn(def io.Reader) io.Reader { + if c.inReader != nil { + return c.inReader + } + if c.HasParent() { + return c.parent.getIn(def) + } + return def +} + +// UsageFunc returns either the function set by SetUsageFunc for this command +// or a parent, or it returns a default usage function. +func (c *Command) UsageFunc() (f func(*Command) error) { + if c.usageFunc != nil { + return c.usageFunc + } + if c.HasParent() { + return c.Parent().UsageFunc() + } + return func(c *Command) error { + c.mergePersistentFlags() + fn := c.getUsageTemplateFunc() + err := fn(c.OutOrStderr(), c) + if err != nil { + c.PrintErrln(err) + } + return err + } +} + +// getUsageTemplateFunc returns the usage template function for the command +// going up the command tree if necessary. +func (c *Command) getUsageTemplateFunc() func(w io.Writer, data interface{}) error { + if c.usageTemplate != nil { + return c.usageTemplate.fn + } + + if c.HasParent() { + return c.parent.getUsageTemplateFunc() + } + return defaultUsageFunc +} + +// Usage puts out the usage for the command. +// Used when a user provides invalid input. +// Can be defined by user by overriding UsageFunc. +func (c *Command) Usage() error { + return c.UsageFunc()(c) +} + +// HelpFunc returns either the function set by SetHelpFunc for this command +// or a parent, or it returns a function with default help behavior. +func (c *Command) HelpFunc() func(*Command, []string) { + if c.helpFunc != nil { + return c.helpFunc + } + if c.HasParent() { + return c.Parent().HelpFunc() + } + return func(c *Command, a []string) { + c.mergePersistentFlags() + fn := c.getHelpTemplateFunc() + // The help should be sent to stdout + // See https://github.com/spf13/cobra/issues/1002 + err := fn(c.OutOrStdout(), c) + if err != nil { + c.PrintErrln(err) + } + } +} + +// getHelpTemplateFunc returns the help template function for the command +// going up the command tree if necessary. +func (c *Command) getHelpTemplateFunc() func(w io.Writer, data interface{}) error { + if c.helpTemplate != nil { + return c.helpTemplate.fn + } + + if c.HasParent() { + return c.parent.getHelpTemplateFunc() + } + + return defaultHelpFunc +} + +// Help puts out the help for the command. +// Used when a user calls help [command]. +// Can be defined by user by overriding HelpFunc. +func (c *Command) Help() error { + c.HelpFunc()(c, []string{}) + return nil +} + +// UsageString returns usage string. +func (c *Command) UsageString() string { + // Storing normal writers + tmpOutput := c.outWriter + tmpErr := c.errWriter + + bb := new(bytes.Buffer) + c.outWriter = bb + c.errWriter = bb + + CheckErr(c.Usage()) + + // Setting things back to normal + c.outWriter = tmpOutput + c.errWriter = tmpErr + + return bb.String() +} + +// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this +// command or a parent, or it returns a function which returns the original +// error. +func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { + if c.flagErrorFunc != nil { + return c.flagErrorFunc + } + + if c.HasParent() { + return c.parent.FlagErrorFunc() + } + return func(c *Command, err error) error { + return err + } +} + +const minUsagePadding = 25 + +// UsagePadding return padding for the usage. +func (c *Command) UsagePadding() int { + if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { + return minUsagePadding + } + return c.parent.commandsMaxUseLen +} + +const minCommandPathPadding = 11 + +// CommandPathPadding return padding for the command path. +func (c *Command) CommandPathPadding() int { + if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { + return minCommandPathPadding + } + return c.parent.commandsMaxCommandPathLen +} + +const minNamePadding = 11 + +// NamePadding returns padding for the name. +func (c *Command) NamePadding() int { + if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { + return minNamePadding + } + return c.parent.commandsMaxNameLen +} + +// UsageTemplate returns usage template for the command. +// This function is kept for backwards-compatibility reasons. +func (c *Command) UsageTemplate() string { + if c.usageTemplate != nil { + return c.usageTemplate.tmpl + } + + if c.HasParent() { + return c.parent.UsageTemplate() + } + return defaultUsageTemplate +} + +// HelpTemplate return help template for the command. +// This function is kept for backwards-compatibility reasons. +func (c *Command) HelpTemplate() string { + if c.helpTemplate != nil { + return c.helpTemplate.tmpl + } + + if c.HasParent() { + return c.parent.HelpTemplate() + } + return defaultHelpTemplate +} + +// VersionTemplate return version template for the command. +// This function is kept for backwards-compatibility reasons. +func (c *Command) VersionTemplate() string { + if c.versionTemplate != nil { + return c.versionTemplate.tmpl + } + + if c.HasParent() { + return c.parent.VersionTemplate() + } + return defaultVersionTemplate +} + +// getVersionTemplateFunc returns the version template function for the command +// going up the command tree if necessary. +func (c *Command) getVersionTemplateFunc() func(w io.Writer, data interface{}) error { + if c.versionTemplate != nil { + return c.versionTemplate.fn + } + + if c.HasParent() { + return c.parent.getVersionTemplateFunc() + } + return defaultVersionFunc +} + +// ErrPrefix return error message prefix for the command +func (c *Command) ErrPrefix() string { + if c.errPrefix != "" { + return c.errPrefix + } + + if c.HasParent() { + return c.parent.ErrPrefix() + } + return "Error:" +} + +func hasNoOptDefVal(name string, fs *flag.FlagSet) bool { + flag := fs.Lookup(name) + if flag == nil { + return false + } + return flag.NoOptDefVal != "" +} + +func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool { + if len(name) == 0 { + return false + } + + flag := fs.ShorthandLookup(name[:1]) + if flag == nil { + return false + } + return flag.NoOptDefVal != "" +} + +func stripFlags(args []string, c *Command) []string { + if len(args) == 0 { + return args + } + c.mergePersistentFlags() + + commands := []string{} + flags := c.Flags() + +Loop: + for len(args) > 0 { + s := args[0] + args = args[1:] + switch { + case s == "--": + // "--" terminates the flags + break Loop + case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): + // If '--flag arg' then + // delete arg from args. + fallthrough // (do the same as below) + case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): + // If '-f arg' then + // delete 'arg' from args or break the loop if len(args) <= 1. + if len(args) <= 1 { + break Loop + } else { + args = args[1:] + continue + } + case s != "" && !strings.HasPrefix(s, "-"): + commands = append(commands, s) + } + } + + return commands +} + +// argsMinusFirstX removes only the first x from args. Otherwise, commands that look like +// openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). +// Special care needs to be taken not to remove a flag value. +func (c *Command) argsMinusFirstX(args []string, x string) []string { + if len(args) == 0 { + return args + } + c.mergePersistentFlags() + flags := c.Flags() + +Loop: + for pos := 0; pos < len(args); pos++ { + s := args[pos] + switch { + case s == "--": + // -- means we have reached the end of the parseable args. Break out of the loop now. + break Loop + case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags): + fallthrough + case strings.HasPrefix(s, "-") && !strings.Contains(s, "=") && len(s) == 2 && !shortHasNoOptDefVal(s[1:], flags): + // This is a flag without a default value, and an equal sign is not used. Increment pos in order to skip + // over the next arg, because that is the value of this flag. + pos++ + continue + case !strings.HasPrefix(s, "-"): + // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so, + // return the args, excluding the one at this position. + if s == x { + ret := make([]string, 0, len(args)-1) + ret = append(ret, args[:pos]...) + ret = append(ret, args[pos+1:]...) + return ret + } + } + } + return args +} + +func isFlagArg(arg string) bool { + return ((len(arg) >= 3 && arg[0:2] == "--") || + (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) +} + +// Find the target command given the args and command tree +// Meant to be run on the highest node. Only searches down. +func (c *Command) Find(args []string) (*Command, []string, error) { + var innerfind func(*Command, []string) (*Command, []string) + + innerfind = func(c *Command, innerArgs []string) (*Command, []string) { + argsWOflags := stripFlags(innerArgs, c) + if len(argsWOflags) == 0 { + return c, innerArgs + } + nextSubCmd := argsWOflags[0] + + cmd := c.findNext(nextSubCmd) + if cmd != nil { + return innerfind(cmd, c.argsMinusFirstX(innerArgs, nextSubCmd)) + } + return c, innerArgs + } + + commandFound, a := innerfind(c, args) + if commandFound.Args == nil { + return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) + } + return commandFound, a, nil +} + +func (c *Command) findSuggestions(arg string) string { + if c.DisableSuggestions { + return "" + } + if c.SuggestionsMinimumDistance <= 0 { + c.SuggestionsMinimumDistance = 2 + } + var sb strings.Builder + if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { + sb.WriteString("\n\nDid you mean this?\n") + for _, s := range suggestions { + _, _ = fmt.Fprintf(&sb, "\t%v\n", s) + } + } + return sb.String() +} + +func (c *Command) findNext(next string) *Command { + matches := make([]*Command, 0) + for _, cmd := range c.commands { + if commandNameMatches(cmd.Name(), next) || cmd.HasAlias(next) { + cmd.commandCalledAs.name = next + return cmd + } + if EnablePrefixMatching && cmd.hasNameOrAliasPrefix(next) { + matches = append(matches, cmd) + } + } + + if len(matches) == 1 { + // Temporarily disable gosec G602, which produces a false positive. + // See https://github.com/securego/gosec/issues/1005. + return matches[0] // #nosec G602 + } + + return nil +} + +// Traverse the command tree to find the command, and parse args for +// each parent. +func (c *Command) Traverse(args []string) (*Command, []string, error) { + flags := []string{} + inFlag := false + + for i, arg := range args { + switch { + // A long flag with a space separated value + case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): + // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' + inFlag = !hasNoOptDefVal(arg[2:], c.Flags()) + flags = append(flags, arg) + continue + // A short flag with a space separated value + case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !shortHasNoOptDefVal(arg[1:], c.Flags()): + inFlag = true + flags = append(flags, arg) + continue + // The value for a flag + case inFlag: + inFlag = false + flags = append(flags, arg) + continue + // A flag without a value, or with an `=` separated value + case isFlagArg(arg): + flags = append(flags, arg) + continue + } + + cmd := c.findNext(arg) + if cmd == nil { + return c, args, nil + } + + if err := c.ParseFlags(flags); err != nil { + return nil, args, err + } + return cmd.Traverse(args[i+1:]) + } + return c, args, nil +} + +// SuggestionsFor provides suggestions for the typedName. +func (c *Command) SuggestionsFor(typedName string) []string { + suggestions := []string{} + for _, cmd := range c.commands { + if cmd.IsAvailableCommand() { + levenshteinDistance := ld(typedName, cmd.Name(), true) + suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance + suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) + if suggestByLevenshtein || suggestByPrefix { + suggestions = append(suggestions, cmd.Name()) + } + for _, explicitSuggestion := range cmd.SuggestFor { + if strings.EqualFold(typedName, explicitSuggestion) { + suggestions = append(suggestions, cmd.Name()) + } + } + } + } + return suggestions +} + +// VisitParents visits all parents of the command and invokes fn on each parent. +func (c *Command) VisitParents(fn func(*Command)) { + if c.HasParent() { + fn(c.Parent()) + c.Parent().VisitParents(fn) + } +} + +// Root finds root command. +func (c *Command) Root() *Command { + if c.HasParent() { + return c.Parent().Root() + } + return c +} + +// ArgsLenAtDash will return the length of c.Flags().Args at the moment +// when a -- was found during args parsing. +func (c *Command) ArgsLenAtDash() int { + return c.Flags().ArgsLenAtDash() +} + +func (c *Command) execute(a []string) (err error) { + if c == nil { + return fmt.Errorf("called Execute() on a nil Command") + } + + if len(c.Deprecated) > 0 { + c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) + } + + // initialize help and version flag at the last point possible to allow for user + // overriding + c.InitDefaultHelpFlag() + c.InitDefaultVersionFlag() + + err = c.ParseFlags(a) + if err != nil { + return c.FlagErrorFunc()(c, err) + } + + // If help is called, regardless of other flags, return we want help. + // Also say we need help if the command isn't runnable. + helpVal, err := c.Flags().GetBool(helpFlagName) + if err != nil { + // should be impossible to get here as we always declare a help + // flag in InitDefaultHelpFlag() + c.Println("\"help\" flag declared as non-bool. Please correct your code") + return err + } + + if helpVal { + return flag.ErrHelp + } + + // for back-compat, only add version flag behavior if version is defined + if c.Version != "" { + versionVal, err := c.Flags().GetBool("version") + if err != nil { + c.Println("\"version\" flag declared as non-bool. Please correct your code") + return err + } + if versionVal { + fn := c.getVersionTemplateFunc() + err := fn(c.OutOrStdout(), c) + if err != nil { + c.Println(err) + } + return err + } + } + + if !c.Runnable() { + return flag.ErrHelp + } + + c.preRun() + + defer c.postRun() + + argWoFlags := c.Flags().Args() + if c.DisableFlagParsing { + argWoFlags = a + } + + if err := c.ValidateArgs(argWoFlags); err != nil { + return err + } + + parents := make([]*Command, 0, 5) + for p := c; p != nil; p = p.Parent() { + if EnableTraverseRunHooks { + // When EnableTraverseRunHooks is set: + // - Execute all persistent pre-runs from the root parent till this command. + // - Execute all persistent post-runs from this command till the root parent. + parents = append([]*Command{p}, parents...) + } else { + // Otherwise, execute only the first found persistent hook. + parents = append(parents, p) + } + } + for _, p := range parents { + if p.PersistentPreRunE != nil { + if err := p.PersistentPreRunE(c, argWoFlags); err != nil { + return err + } + if !EnableTraverseRunHooks { + break + } + } else if p.PersistentPreRun != nil { + p.PersistentPreRun(c, argWoFlags) + if !EnableTraverseRunHooks { + break + } + } + } + if c.PreRunE != nil { + if err := c.PreRunE(c, argWoFlags); err != nil { + return err + } + } else if c.PreRun != nil { + c.PreRun(c, argWoFlags) + } + + if err := c.ValidateRequiredFlags(); err != nil { + return err + } + if err := c.ValidateFlagGroups(); err != nil { + return err + } + + if c.RunE != nil { + if err := c.RunE(c, argWoFlags); err != nil { + return err + } + } else { + c.Run(c, argWoFlags) + } + if c.PostRunE != nil { + if err := c.PostRunE(c, argWoFlags); err != nil { + return err + } + } else if c.PostRun != nil { + c.PostRun(c, argWoFlags) + } + for p := c; p != nil; p = p.Parent() { + if p.PersistentPostRunE != nil { + if err := p.PersistentPostRunE(c, argWoFlags); err != nil { + return err + } + if !EnableTraverseRunHooks { + break + } + } else if p.PersistentPostRun != nil { + p.PersistentPostRun(c, argWoFlags) + if !EnableTraverseRunHooks { + break + } + } + } + + return nil +} + +func (c *Command) preRun() { + for _, x := range initializers { + x() + } +} + +func (c *Command) postRun() { + for _, x := range finalizers { + x() + } +} + +// ExecuteContext is the same as Execute(), but sets the ctx on the command. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs +// functions. +func (c *Command) ExecuteContext(ctx context.Context) error { + c.ctx = ctx + return c.Execute() +} + +// Execute uses the args (os.Args[1:] by default) +// and run through the command tree finding appropriate matches +// for commands and then corresponding flags. +func (c *Command) Execute() error { + _, err := c.ExecuteC() + return err +} + +// ExecuteContextC is the same as ExecuteC(), but sets the ctx on the command. +// Retrieve ctx by calling cmd.Context() inside your *Run lifecycle or ValidArgs +// functions. +func (c *Command) ExecuteContextC(ctx context.Context) (*Command, error) { + c.ctx = ctx + return c.ExecuteC() +} + +// ExecuteC executes the command. +func (c *Command) ExecuteC() (cmd *Command, err error) { + if c.ctx == nil { + c.ctx = context.Background() + } + + // Regardless of what command execute is called on, run on Root only + if c.HasParent() { + return c.Root().ExecuteC() + } + + // windows hook + if preExecHookFn != nil { + preExecHookFn(c) + } + + // initialize help at the last point to allow for user overriding + c.InitDefaultHelpCmd() + + args := c.args + + // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 + if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { + args = os.Args[1:] + } + + // initialize the __complete command to be used for shell completion + c.initCompleteCmd(args) + + // initialize the default completion command + c.InitDefaultCompletionCmd(args...) + + // Now that all commands have been created, let's make sure all groups + // are properly created also + c.checkCommandGroups() + + var flags []string + if c.TraverseChildren { + cmd, flags, err = c.Traverse(args) + } else { + cmd, flags, err = c.Find(args) + } + if err != nil { + // If found parse to a subcommand and then failed, talk about the subcommand + if cmd != nil { + c = cmd + } + if !c.SilenceErrors { + c.PrintErrln(c.ErrPrefix(), err.Error()) + c.PrintErrf("Run '%v --help' for usage.\n", c.CommandPath()) + } + return c, err + } + + cmd.commandCalledAs.called = true + if cmd.commandCalledAs.name == "" { + cmd.commandCalledAs.name = cmd.Name() + } + + // We have to pass global context to children command + // if context is present on the parent command. + if cmd.ctx == nil { + cmd.ctx = c.ctx + } + + err = cmd.execute(flags) + if err != nil { + // Always show help if requested, even if SilenceErrors is in + // effect + if errors.Is(err, flag.ErrHelp) { + cmd.HelpFunc()(cmd, args) + return cmd, nil + } + + // If root command has SilenceErrors flagged, + // all subcommands should respect it + if !cmd.SilenceErrors && !c.SilenceErrors { + c.PrintErrln(cmd.ErrPrefix(), err.Error()) + } + + // If root command has SilenceUsage flagged, + // all subcommands should respect it + if !cmd.SilenceUsage && !c.SilenceUsage { + c.Println(cmd.UsageString()) + } + } + return cmd, err +} + +func (c *Command) ValidateArgs(args []string) error { + if c.Args == nil { + return ArbitraryArgs(c, args) + } + return c.Args(c, args) +} + +// ValidateRequiredFlags validates all required flags are present and returns an error otherwise +func (c *Command) ValidateRequiredFlags() error { + if c.DisableFlagParsing { + return nil + } + + flags := c.Flags() + missingFlagNames := []string{} + flags.VisitAll(func(pflag *flag.Flag) { + requiredAnnotation, found := pflag.Annotations[BashCompOneRequiredFlag] + if !found { + return + } + if (requiredAnnotation[0] == "true") && !pflag.Changed { + missingFlagNames = append(missingFlagNames, pflag.Name) + } + }) + + if len(missingFlagNames) > 0 { + return fmt.Errorf(`required flag(s) "%s" not set`, strings.Join(missingFlagNames, `", "`)) + } + return nil +} + +// checkCommandGroups checks if a command has been added to a group that does not exists. +// If so, we panic because it indicates a coding error that should be corrected. +func (c *Command) checkCommandGroups() { + for _, sub := range c.commands { + // if Group is not defined let the developer know right away + if sub.GroupID != "" && !c.ContainsGroup(sub.GroupID) { + panic(fmt.Sprintf("group id '%s' is not defined for subcommand '%s'", sub.GroupID, sub.CommandPath())) + } + + sub.checkCommandGroups() + } +} + +// InitDefaultHelpFlag adds default help flag to c. +// It is called automatically by executing the c or by calling help and usage. +// If c already has help flag, it will do nothing. +func (c *Command) InitDefaultHelpFlag() { + c.mergePersistentFlags() + if c.Flags().Lookup(helpFlagName) == nil { + usage := "help for " + name := c.DisplayName() + if name == "" { + usage += "this command" + } else { + usage += name + } + c.Flags().BoolP(helpFlagName, "h", false, usage) + _ = c.Flags().SetAnnotation(helpFlagName, FlagSetByCobraAnnotation, []string{"true"}) + } +} + +// InitDefaultVersionFlag adds default version flag to c. +// It is called automatically by executing the c. +// If c already has a version flag, it will do nothing. +// If c.Version is empty, it will do nothing. +func (c *Command) InitDefaultVersionFlag() { + if c.Version == "" { + return + } + + c.mergePersistentFlags() + if c.Flags().Lookup("version") == nil { + usage := "version for " + if c.Name() == "" { + usage += "this command" + } else { + usage += c.DisplayName() + } + if c.Flags().ShorthandLookup("v") == nil { + c.Flags().BoolP("version", "v", false, usage) + } else { + c.Flags().Bool("version", false, usage) + } + _ = c.Flags().SetAnnotation("version", FlagSetByCobraAnnotation, []string{"true"}) + } +} + +// InitDefaultHelpCmd adds default help command to c. +// It is called automatically by executing the c or by calling help and usage. +// If c already has help command or c has no subcommands, it will do nothing. +func (c *Command) InitDefaultHelpCmd() { + if !c.HasSubCommands() { + return + } + + if c.helpCommand == nil { + c.helpCommand = &Command{ + Use: "help [command]", + Short: "Help about any command", + Long: `Help provides help for any command in the application. +Simply type ` + c.DisplayName() + ` help [path to command] for full details.`, + ValidArgsFunction: func(c *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + var completions []Completion + cmd, _, e := c.Root().Find(args) + if e != nil { + return nil, ShellCompDirectiveNoFileComp + } + if cmd == nil { + // Root help command. + cmd = c.Root() + } + for _, subCmd := range cmd.Commands() { + if subCmd.IsAvailableCommand() || subCmd == cmd.helpCommand { + if strings.HasPrefix(subCmd.Name(), toComplete) { + completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) + } + } + } + return completions, ShellCompDirectiveNoFileComp + }, + Run: func(c *Command, args []string) { + cmd, _, e := c.Root().Find(args) + if cmd == nil || e != nil { + c.Printf("Unknown help topic %#q\n", args) + CheckErr(c.Root().Usage()) + } else { + // FLow the context down to be used in help text + if cmd.ctx == nil { + cmd.ctx = c.ctx + } + + cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown + cmd.InitDefaultVersionFlag() // make possible 'version' flag to be shown + CheckErr(cmd.Help()) + } + }, + GroupID: c.helpCommandGroupID, + } + } + c.RemoveCommand(c.helpCommand) + c.AddCommand(c.helpCommand) +} + +// ResetCommands delete parent, subcommand and help command from c. +func (c *Command) ResetCommands() { + c.parent = nil + c.commands = nil + c.helpCommand = nil + c.parentsPflags = nil +} + +// Sorts commands by their names. +type commandSorterByName []*Command + +func (c commandSorterByName) Len() int { return len(c) } +func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } +func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } + +// Commands returns a sorted slice of child commands. +func (c *Command) Commands() []*Command { + // do not sort commands if it already sorted or sorting was disabled + if EnableCommandSorting && !c.commandsAreSorted { + sort.Sort(commandSorterByName(c.commands)) + c.commandsAreSorted = true + } + return c.commands +} + +// AddCommand adds one or more commands to this parent command. +func (c *Command) AddCommand(cmds ...*Command) { + for i, x := range cmds { + if cmds[i] == c { + panic("Command can't be a child of itself") + } + cmds[i].parent = c + // update max lengths + usageLen := len(x.Use) + if usageLen > c.commandsMaxUseLen { + c.commandsMaxUseLen = usageLen + } + commandPathLen := len(x.CommandPath()) + if commandPathLen > c.commandsMaxCommandPathLen { + c.commandsMaxCommandPathLen = commandPathLen + } + nameLen := len(x.Name()) + if nameLen > c.commandsMaxNameLen { + c.commandsMaxNameLen = nameLen + } + // If global normalization function exists, update all children + if c.globNormFunc != nil { + x.SetGlobalNormalizationFunc(c.globNormFunc) + } + c.commands = append(c.commands, x) + c.commandsAreSorted = false + } +} + +// Groups returns a slice of child command groups. +func (c *Command) Groups() []*Group { + return c.commandgroups +} + +// AllChildCommandsHaveGroup returns if all subcommands are assigned to a group +func (c *Command) AllChildCommandsHaveGroup() bool { + for _, sub := range c.commands { + if (sub.IsAvailableCommand() || sub == c.helpCommand) && sub.GroupID == "" { + return false + } + } + return true +} + +// ContainsGroup return if groupID exists in the list of command groups. +func (c *Command) ContainsGroup(groupID string) bool { + for _, x := range c.commandgroups { + if x.ID == groupID { + return true + } + } + return false +} + +// AddGroup adds one or more command groups to this parent command. +func (c *Command) AddGroup(groups ...*Group) { + c.commandgroups = append(c.commandgroups, groups...) +} + +// RemoveCommand removes one or more commands from a parent command. +func (c *Command) RemoveCommand(cmds ...*Command) { + commands := []*Command{} +main: + for _, command := range c.commands { + for _, cmd := range cmds { + if command == cmd { + command.parent = nil + continue main + } + } + commands = append(commands, command) + } + c.commands = commands + // recompute all lengths + c.commandsMaxUseLen = 0 + c.commandsMaxCommandPathLen = 0 + c.commandsMaxNameLen = 0 + for _, command := range c.commands { + usageLen := len(command.Use) + if usageLen > c.commandsMaxUseLen { + c.commandsMaxUseLen = usageLen + } + commandPathLen := len(command.CommandPath()) + if commandPathLen > c.commandsMaxCommandPathLen { + c.commandsMaxCommandPathLen = commandPathLen + } + nameLen := len(command.Name()) + if nameLen > c.commandsMaxNameLen { + c.commandsMaxNameLen = nameLen + } + } +} + +// Print is a convenience method to Print to the defined output, fallback to Stderr if not set. +func (c *Command) Print(i ...interface{}) { + fmt.Fprint(c.OutOrStderr(), i...) +} + +// Println is a convenience method to Println to the defined output, fallback to Stderr if not set. +func (c *Command) Println(i ...interface{}) { + c.Print(fmt.Sprintln(i...)) +} + +// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set. +func (c *Command) Printf(format string, i ...interface{}) { + c.Print(fmt.Sprintf(format, i...)) +} + +// PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set. +func (c *Command) PrintErr(i ...interface{}) { + fmt.Fprint(c.ErrOrStderr(), i...) +} + +// PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set. +func (c *Command) PrintErrln(i ...interface{}) { + c.PrintErr(fmt.Sprintln(i...)) +} + +// PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set. +func (c *Command) PrintErrf(format string, i ...interface{}) { + c.PrintErr(fmt.Sprintf(format, i...)) +} + +// CommandPath returns the full path to this command. +func (c *Command) CommandPath() string { + if c.HasParent() { + return c.Parent().CommandPath() + " " + c.Name() + } + return c.DisplayName() +} + +// DisplayName returns the name to display in help text. Returns command Name() +// If CommandDisplayNameAnnoation is not set +func (c *Command) DisplayName() string { + if displayName, ok := c.Annotations[CommandDisplayNameAnnotation]; ok { + return displayName + } + return c.Name() +} + +// UseLine puts out the full usage for a given command (including parents). +func (c *Command) UseLine() string { + var useline string + use := strings.Replace(c.Use, c.Name(), c.DisplayName(), 1) + if c.HasParent() { + useline = c.parent.CommandPath() + " " + use + } else { + useline = use + } + if c.DisableFlagsInUseLine { + return useline + } + if c.HasAvailableFlags() && !strings.Contains(useline, "[flags]") { + useline += " [flags]" + } + return useline +} + +// DebugFlags used to determine which flags have been assigned to which commands +// and which persist. +func (c *Command) DebugFlags() { + c.Println("DebugFlags called on", c.Name()) + var debugflags func(*Command) + + debugflags = func(x *Command) { + if x.HasFlags() || x.HasPersistentFlags() { + c.Println(x.Name()) + } + if x.HasFlags() { + x.flags.VisitAll(func(f *flag.Flag) { + if x.HasPersistentFlags() && x.persistentFlag(f.Name) != nil { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") + } else { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") + } + }) + } + if x.HasPersistentFlags() { + x.pflags.VisitAll(func(f *flag.Flag) { + if x.HasFlags() { + if x.flags.Lookup(f.Name) == nil { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") + } + } else { + c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") + } + }) + } + c.Println(x.flagErrorBuf) + if x.HasSubCommands() { + for _, y := range x.commands { + debugflags(y) + } + } + } + + debugflags(c) +} + +// Name returns the command's name: the first word in the use line. +func (c *Command) Name() string { + name := c.Use + i := strings.Index(name, " ") + if i >= 0 { + name = name[:i] + } + return name +} + +// HasAlias determines if a given string is an alias of the command. +func (c *Command) HasAlias(s string) bool { + for _, a := range c.Aliases { + if commandNameMatches(a, s) { + return true + } + } + return false +} + +// CalledAs returns the command name or alias that was used to invoke +// this command or an empty string if the command has not been called. +func (c *Command) CalledAs() string { + if c.commandCalledAs.called { + return c.commandCalledAs.name + } + return "" +} + +// hasNameOrAliasPrefix returns true if the Name or any of aliases start +// with prefix +func (c *Command) hasNameOrAliasPrefix(prefix string) bool { + if strings.HasPrefix(c.Name(), prefix) { + c.commandCalledAs.name = c.Name() + return true + } + for _, alias := range c.Aliases { + if strings.HasPrefix(alias, prefix) { + c.commandCalledAs.name = alias + return true + } + } + return false +} + +// NameAndAliases returns a list of the command name and all aliases +func (c *Command) NameAndAliases() string { + return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") +} + +// HasExample determines if the command has example. +func (c *Command) HasExample() bool { + return len(c.Example) > 0 +} + +// Runnable determines if the command is itself runnable. +func (c *Command) Runnable() bool { + return c.Run != nil || c.RunE != nil +} + +// HasSubCommands determines if the command has children commands. +func (c *Command) HasSubCommands() bool { + return len(c.commands) > 0 +} + +// IsAvailableCommand determines if a command is available as a non-help command +// (this includes all non deprecated/hidden commands). +func (c *Command) IsAvailableCommand() bool { + if len(c.Deprecated) != 0 || c.Hidden { + return false + } + + if c.HasParent() && c.Parent().helpCommand == c { + return false + } + + if c.Runnable() || c.HasAvailableSubCommands() { + return true + } + + return false +} + +// IsAdditionalHelpTopicCommand determines if a command is an additional +// help topic command; additional help topic command is determined by the +// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that +// are runnable/hidden/deprecated. +// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924. +func (c *Command) IsAdditionalHelpTopicCommand() bool { + // if a command is runnable, deprecated, or hidden it is not a 'help' command + if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { + return false + } + + // if any non-help sub commands are found, the command is not a 'help' command + for _, sub := range c.commands { + if !sub.IsAdditionalHelpTopicCommand() { + return false + } + } + + // the command either has no sub commands, or no non-help sub commands + return true +} + +// HasHelpSubCommands determines if a command has any available 'help' sub commands +// that need to be shown in the usage/help default template under 'additional help +// topics'. +func (c *Command) HasHelpSubCommands() bool { + // return true on the first found available 'help' sub command + for _, sub := range c.commands { + if sub.IsAdditionalHelpTopicCommand() { + return true + } + } + + // the command either has no sub commands, or no available 'help' sub commands + return false +} + +// HasAvailableSubCommands determines if a command has available sub commands that +// need to be shown in the usage/help default template under 'available commands'. +func (c *Command) HasAvailableSubCommands() bool { + // return true on the first found available (non deprecated/help/hidden) + // sub command + for _, sub := range c.commands { + if sub.IsAvailableCommand() { + return true + } + } + + // the command either has no sub commands, or no available (non deprecated/help/hidden) + // sub commands + return false +} + +// HasParent determines if the command is a child command. +func (c *Command) HasParent() bool { + return c.parent != nil +} + +// GlobalNormalizationFunc returns the global normalization function or nil if it doesn't exist. +func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { + return c.globNormFunc +} + +// Flags returns the complete FlagSet that applies +// to this command (local and persistent declared here and by all parents). +func (c *Command) Flags() *flag.FlagSet { + if c.flags == nil { + c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.flags.SetOutput(c.flagErrorBuf) + } + + return c.flags +} + +// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { + persistentFlags := c.PersistentFlags() + + out := flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.LocalFlags().VisitAll(func(f *flag.Flag) { + if persistentFlags.Lookup(f.Name) == nil { + out.AddFlag(f) + } + }) + return out +} + +// LocalFlags returns the local FlagSet specifically set in the current command. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) LocalFlags() *flag.FlagSet { + c.mergePersistentFlags() + + if c.lflags == nil { + c.lflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.lflags.SetOutput(c.flagErrorBuf) + } + c.lflags.SortFlags = c.Flags().SortFlags + if c.globNormFunc != nil { + c.lflags.SetNormalizeFunc(c.globNormFunc) + } + + addToLocal := func(f *flag.Flag) { + // Add the flag if it is not a parent PFlag, or it shadows a parent PFlag + if c.lflags.Lookup(f.Name) == nil && f != c.parentsPflags.Lookup(f.Name) { + c.lflags.AddFlag(f) + } + } + c.Flags().VisitAll(addToLocal) + c.PersistentFlags().VisitAll(addToLocal) + return c.lflags +} + +// InheritedFlags returns all flags which were inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) InheritedFlags() *flag.FlagSet { + c.mergePersistentFlags() + + if c.iflags == nil { + c.iflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.iflags.SetOutput(c.flagErrorBuf) + } + + local := c.LocalFlags() + if c.globNormFunc != nil { + c.iflags.SetNormalizeFunc(c.globNormFunc) + } + + c.parentsPflags.VisitAll(func(f *flag.Flag) { + if c.iflags.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { + c.iflags.AddFlag(f) + } + }) + return c.iflags +} + +// NonInheritedFlags returns all flags which were not inherited from parent commands. +// This function does not modify the flags of the current command, it's purpose is to return the current state. +func (c *Command) NonInheritedFlags() *flag.FlagSet { + return c.LocalFlags() +} + +// PersistentFlags returns the persistent FlagSet specifically set in the current command. +func (c *Command) PersistentFlags() *flag.FlagSet { + if c.pflags == nil { + c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + c.pflags.SetOutput(c.flagErrorBuf) + } + return c.pflags +} + +// ResetFlags deletes all flags from command. +func (c *Command) ResetFlags() { + c.flagErrorBuf = new(bytes.Buffer) + c.flagErrorBuf.Reset() + c.flags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.flags.SetOutput(c.flagErrorBuf) + c.pflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.pflags.SetOutput(c.flagErrorBuf) + + c.lflags = nil + c.iflags = nil + c.parentsPflags = nil +} + +// HasFlags checks if the command contains any flags (local plus persistent from the entire structure). +func (c *Command) HasFlags() bool { + return c.Flags().HasFlags() +} + +// HasPersistentFlags checks if the command contains persistent flags. +func (c *Command) HasPersistentFlags() bool { + return c.PersistentFlags().HasFlags() +} + +// HasLocalFlags checks if the command has flags specifically declared locally. +func (c *Command) HasLocalFlags() bool { + return c.LocalFlags().HasFlags() +} + +// HasInheritedFlags checks if the command has flags inherited from its parent command. +func (c *Command) HasInheritedFlags() bool { + return c.InheritedFlags().HasFlags() +} + +// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire +// structure) which are not hidden or deprecated. +func (c *Command) HasAvailableFlags() bool { + return c.Flags().HasAvailableFlags() +} + +// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated. +func (c *Command) HasAvailablePersistentFlags() bool { + return c.PersistentFlags().HasAvailableFlags() +} + +// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden +// or deprecated. +func (c *Command) HasAvailableLocalFlags() bool { + return c.LocalFlags().HasAvailableFlags() +} + +// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are +// not hidden or deprecated. +func (c *Command) HasAvailableInheritedFlags() bool { + return c.InheritedFlags().HasAvailableFlags() +} + +// Flag climbs up the command tree looking for matching flag. +func (c *Command) Flag(name string) (flag *flag.Flag) { + flag = c.Flags().Lookup(name) + + if flag == nil { + flag = c.persistentFlag(name) + } + + return +} + +// Recursively find matching persistent flag. +func (c *Command) persistentFlag(name string) (flag *flag.Flag) { + if c.HasPersistentFlags() { + flag = c.PersistentFlags().Lookup(name) + } + + if flag == nil { + c.updateParentsPflags() + flag = c.parentsPflags.Lookup(name) + } + return +} + +// ParseFlags parses persistent flag tree and local flags. +func (c *Command) ParseFlags(args []string) error { + if c.DisableFlagParsing { + return nil + } + + if c.flagErrorBuf == nil { + c.flagErrorBuf = new(bytes.Buffer) + } + beforeErrorBufLen := c.flagErrorBuf.Len() + c.mergePersistentFlags() + + // do it here after merging all flags and just before parse + c.Flags().ParseErrorsAllowlist = flag.ParseErrorsAllowlist(c.FParseErrWhitelist) + + err := c.Flags().Parse(args) + // Print warnings if they occurred (e.g. deprecated flag messages). + if c.flagErrorBuf.Len()-beforeErrorBufLen > 0 && err == nil { + c.Print(c.flagErrorBuf.String()) + } + + return err +} + +// Parent returns a commands parent command. +func (c *Command) Parent() *Command { + return c.parent +} + +// mergePersistentFlags merges c.PersistentFlags() to c.Flags() +// and adds missing persistent flags of all parents. +func (c *Command) mergePersistentFlags() { + c.updateParentsPflags() + c.Flags().AddFlagSet(c.PersistentFlags()) + c.Flags().AddFlagSet(c.parentsPflags) +} + +// updateParentsPflags updates c.parentsPflags by adding +// new persistent flags of all parents. +// If c.parentsPflags == nil, it makes new. +func (c *Command) updateParentsPflags() { + if c.parentsPflags == nil { + c.parentsPflags = flag.NewFlagSet(c.DisplayName(), flag.ContinueOnError) + c.parentsPflags.SetOutput(c.flagErrorBuf) + c.parentsPflags.SortFlags = false + } + + if c.globNormFunc != nil { + c.parentsPflags.SetNormalizeFunc(c.globNormFunc) + } + + c.Root().PersistentFlags().AddFlagSet(flag.CommandLine) + + c.VisitParents(func(parent *Command) { + c.parentsPflags.AddFlagSet(parent.PersistentFlags()) + }) +} + +// commandNameMatches checks if two command names are equal +// taking into account case sensitivity according to +// EnableCaseInsensitive global configuration. +func commandNameMatches(s string, t string) bool { + if EnableCaseInsensitive { + return strings.EqualFold(s, t) + } + + return s == t +} + +// tmplFunc holds a template and a function that will execute said template. +type tmplFunc struct { + tmpl string + fn func(io.Writer, interface{}) error +} + +const defaultUsageTemplate = `Usage:{{if .Runnable}} + {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}} + {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}} + +Aliases: + {{.NameAndAliases}}{{end}}{{if .HasExample}} + +Examples: +{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}} + +Available Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name "help"))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}} + +{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}} + +Additional Commands:{{range $cmds}}{{if (and (eq .GroupID "") (or .IsAvailableCommand (eq .Name "help")))}} + {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}} + +Flags: +{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}} + +Global Flags: +{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}} + +Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}} + {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}} + +Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} +` + +// defaultUsageFunc is equivalent to executing defaultUsageTemplate. The two should be changed in sync. +func defaultUsageFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + fmt.Fprint(w, "Usage:") + if c.Runnable() { + fmt.Fprintf(w, "\n %s", c.UseLine()) + } + if c.HasAvailableSubCommands() { + fmt.Fprintf(w, "\n %s [command]", c.CommandPath()) + } + if len(c.Aliases) > 0 { + fmt.Fprintf(w, "\n\nAliases:\n") + fmt.Fprintf(w, " %s", c.NameAndAliases()) + } + if c.HasExample() { + fmt.Fprintf(w, "\n\nExamples:\n") + fmt.Fprintf(w, "%s", c.Example) + } + if c.HasAvailableSubCommands() { + cmds := c.Commands() + if len(c.Groups()) == 0 { + fmt.Fprintf(w, "\n\nAvailable Commands:") + for _, subcmd := range cmds { + if subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } else { + for _, group := range c.Groups() { + fmt.Fprintf(w, "\n\n%s", group.Title) + for _, subcmd := range cmds { + if subcmd.GroupID == group.ID && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } + if !c.AllChildCommandsHaveGroup() { + fmt.Fprintf(w, "\n\nAdditional Commands:") + for _, subcmd := range cmds { + if subcmd.GroupID == "" && (subcmd.IsAvailableCommand() || subcmd.Name() == helpCommandName) { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.Name(), subcmd.NamePadding()), subcmd.Short) + } + } + } + } + } + if c.HasAvailableLocalFlags() { + fmt.Fprintf(w, "\n\nFlags:\n") + fmt.Fprint(w, trimRightSpace(c.LocalFlags().FlagUsages())) + } + if c.HasAvailableInheritedFlags() { + fmt.Fprintf(w, "\n\nGlobal Flags:\n") + fmt.Fprint(w, trimRightSpace(c.InheritedFlags().FlagUsages())) + } + if c.HasHelpSubCommands() { + fmt.Fprintf(w, "\n\nAdditional help topics:") + for _, subcmd := range c.Commands() { + if subcmd.IsAdditionalHelpTopicCommand() { + fmt.Fprintf(w, "\n %s %s", rpad(subcmd.CommandPath(), subcmd.CommandPathPadding()), subcmd.Short) + } + } + } + if c.HasAvailableSubCommands() { + fmt.Fprintf(w, "\n\nUse \"%s [command] --help\" for more information about a command.", c.CommandPath()) + } + fmt.Fprintln(w) + return nil +} + +const defaultHelpTemplate = `{{with (or .Long .Short)}}{{. | trimTrailingWhitespaces}} + +{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` + +// defaultHelpFunc is equivalent to executing defaultHelpTemplate. The two should be changed in sync. +func defaultHelpFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + usage := c.Long + if usage == "" { + usage = c.Short + } + usage = trimRightSpace(usage) + if usage != "" { + fmt.Fprintln(w, usage) + fmt.Fprintln(w) + } + if c.Runnable() || c.HasSubCommands() { + fmt.Fprint(w, c.UsageString()) + } + return nil +} + +const defaultVersionTemplate = `{{with .DisplayName}}{{printf "%s " .}}{{end}}{{printf "version %s" .Version}} +` + +// defaultVersionFunc is equivalent to executing defaultVersionTemplate. The two should be changed in sync. +func defaultVersionFunc(w io.Writer, in interface{}) error { + c := in.(*Command) + _, err := fmt.Fprintf(w, "%s version %s\n", c.DisplayName(), c.Version) + return err +} diff --git a/vendor/github.com/spf13/cobra/command_notwin.go b/vendor/github.com/spf13/cobra/command_notwin.go new file mode 100644 index 0000000..307f0c1 --- /dev/null +++ b/vendor/github.com/spf13/cobra/command_notwin.go @@ -0,0 +1,20 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build !windows +// +build !windows + +package cobra + +var preExecHookFn func(*Command) diff --git a/vendor/github.com/spf13/cobra/command_win.go b/vendor/github.com/spf13/cobra/command_win.go new file mode 100644 index 0000000..adbef39 --- /dev/null +++ b/vendor/github.com/spf13/cobra/command_win.go @@ -0,0 +1,41 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//go:build windows +// +build windows + +package cobra + +import ( + "fmt" + "os" + "time" + + "github.com/inconshreveable/mousetrap" +) + +var preExecHookFn = preExecHook + +func preExecHook(c *Command) { + if MousetrapHelpText != "" && mousetrap.StartedByExplorer() { + c.Print(MousetrapHelpText) + if MousetrapDisplayDuration > 0 { + time.Sleep(MousetrapDisplayDuration) + } else { + c.Println("Press return to continue...") + fmt.Scanln() + } + os.Exit(1) + } +} diff --git a/vendor/github.com/spf13/cobra/completions.go b/vendor/github.com/spf13/cobra/completions.go new file mode 100644 index 0000000..d3607c2 --- /dev/null +++ b/vendor/github.com/spf13/cobra/completions.go @@ -0,0 +1,1020 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "os" + "regexp" + "strconv" + "strings" + "sync" + + "github.com/spf13/pflag" +) + +const ( + // ShellCompRequestCmd is the name of the hidden command that is used to request + // completion results from the program. It is used by the shell completion scripts. + ShellCompRequestCmd = "__complete" + // ShellCompNoDescRequestCmd is the name of the hidden command that is used to request + // completion results without their description. It is used by the shell completion scripts. + ShellCompNoDescRequestCmd = "__completeNoDesc" +) + +// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it. +var flagCompletionFunctions = map[*pflag.Flag]CompletionFunc{} + +// lock for reading and writing from flagCompletionFunctions +var flagCompletionMutex = &sync.RWMutex{} + +// ShellCompDirective is a bit map representing the different behaviors the shell +// can be instructed to have once completions have been provided. +type ShellCompDirective int + +type flagCompError struct { + subCommand string + flagName string +} + +func (e *flagCompError) Error() string { + return "Subcommand '" + e.subCommand + "' does not support flag '" + e.flagName + "'" +} + +const ( + // ShellCompDirectiveError indicates an error occurred and completions should be ignored. + ShellCompDirectiveError ShellCompDirective = 1 << iota + + // ShellCompDirectiveNoSpace indicates that the shell should not add a space + // after the completion even if there is a single completion provided. + ShellCompDirectiveNoSpace + + // ShellCompDirectiveNoFileComp indicates that the shell should not provide + // file completion even when no completion is provided. + ShellCompDirectiveNoFileComp + + // ShellCompDirectiveFilterFileExt indicates that the provided completions + // should be used as file extension filters. + // For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename() + // is a shortcut to using this directive explicitly. The BashCompFilenameExt + // annotation can also be used to obtain the same behavior for flags. + ShellCompDirectiveFilterFileExt + + // ShellCompDirectiveFilterDirs indicates that only directory names should + // be provided in file completion. To request directory names within another + // directory, the returned completions should specify the directory within + // which to search. The BashCompSubdirsInDir annotation can be used to + // obtain the same behavior but only for flags. + ShellCompDirectiveFilterDirs + + // ShellCompDirectiveKeepOrder indicates that the shell should preserve the order + // in which the completions are provided + ShellCompDirectiveKeepOrder + + // =========================================================================== + + // All directives using iota should be above this one. + // For internal use. + shellCompDirectiveMaxValue + + // ShellCompDirectiveDefault indicates to let the shell perform its default + // behavior after completions have been provided. + // This one must be last to avoid messing up the iota count. + ShellCompDirectiveDefault ShellCompDirective = 0 +) + +const ( + // Constants for the completion command + compCmdName = "completion" + compCmdNoDescFlagName = "no-descriptions" + compCmdNoDescFlagDesc = "disable completion descriptions" + compCmdNoDescFlagDefault = false +) + +// CompletionOptions are the options to control shell completion +type CompletionOptions struct { + // DisableDefaultCmd prevents Cobra from creating a default 'completion' command + DisableDefaultCmd bool + // DisableNoDescFlag prevents Cobra from creating the '--no-descriptions' flag + // for shells that support completion descriptions + DisableNoDescFlag bool + // DisableDescriptions turns off all completion descriptions for shells + // that support them + DisableDescriptions bool + // HiddenDefaultCmd makes the default 'completion' command hidden + HiddenDefaultCmd bool + // DefaultShellCompDirective sets the ShellCompDirective that is returned + // if no special directive can be determined + DefaultShellCompDirective *ShellCompDirective +} + +func (receiver *CompletionOptions) SetDefaultShellCompDirective(directive ShellCompDirective) { + receiver.DefaultShellCompDirective = &directive +} + +// Completion is a string that can be used for completions +// +// two formats are supported: +// - the completion choice +// - the completion choice with a textual description (separated by a TAB). +// +// [CompletionWithDesc] can be used to create a completion string with a textual description. +// +// Note: Go type alias is used to provide a more descriptive name in the documentation, but any string can be used. +type Completion = string + +// CompletionFunc is a function that provides completion results. +type CompletionFunc = func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) + +// CompletionWithDesc returns a [Completion] with a description by using the TAB delimited format. +func CompletionWithDesc(choice string, description string) Completion { + return choice + "\t" + description +} + +// NoFileCompletions can be used to disable file completion for commands that should +// not trigger file completions. +// +// This method satisfies [CompletionFunc]. +// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction]. +func NoFileCompletions(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + return nil, ShellCompDirectiveNoFileComp +} + +// FixedCompletions can be used to create a completion function which always +// returns the same results. +// +// This method returns a function that satisfies [CompletionFunc] +// It can be used with [Command.RegisterFlagCompletionFunc] and for [Command.ValidArgsFunction]. +func FixedCompletions(choices []Completion, directive ShellCompDirective) CompletionFunc { + return func(cmd *Command, args []string, toComplete string) ([]Completion, ShellCompDirective) { + return choices, directive + } +} + +// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag. +// +// You can use pre-defined completion functions such as [FixedCompletions] or [NoFileCompletions], +// or you can define your own. +func (c *Command) RegisterFlagCompletionFunc(flagName string, f CompletionFunc) error { + flag := c.Flag(flagName) + if flag == nil { + return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) + } + flagCompletionMutex.Lock() + defer flagCompletionMutex.Unlock() + + if _, exists := flagCompletionFunctions[flag]; exists { + return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) + } + flagCompletionFunctions[flag] = f + return nil +} + +// GetFlagCompletionFunc returns the completion function for the given flag of the command, if available. +func (c *Command) GetFlagCompletionFunc(flagName string) (CompletionFunc, bool) { + flag := c.Flag(flagName) + if flag == nil { + return nil, false + } + + flagCompletionMutex.RLock() + defer flagCompletionMutex.RUnlock() + + completionFunc, exists := flagCompletionFunctions[flag] + return completionFunc, exists +} + +// Returns a string listing the different directive enabled in the specified parameter +func (d ShellCompDirective) string() string { + var directives []string + if d&ShellCompDirectiveError != 0 { + directives = append(directives, "ShellCompDirectiveError") + } + if d&ShellCompDirectiveNoSpace != 0 { + directives = append(directives, "ShellCompDirectiveNoSpace") + } + if d&ShellCompDirectiveNoFileComp != 0 { + directives = append(directives, "ShellCompDirectiveNoFileComp") + } + if d&ShellCompDirectiveFilterFileExt != 0 { + directives = append(directives, "ShellCompDirectiveFilterFileExt") + } + if d&ShellCompDirectiveFilterDirs != 0 { + directives = append(directives, "ShellCompDirectiveFilterDirs") + } + if d&ShellCompDirectiveKeepOrder != 0 { + directives = append(directives, "ShellCompDirectiveKeepOrder") + } + if len(directives) == 0 { + directives = append(directives, "ShellCompDirectiveDefault") + } + + if d >= shellCompDirectiveMaxValue { + return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d) + } + return strings.Join(directives, ", ") +} + +// initCompleteCmd adds a special hidden command that can be used to request custom completions. +func (c *Command) initCompleteCmd(args []string) { + completeCmd := &Command{ + Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd), + Aliases: []string{ShellCompNoDescRequestCmd}, + DisableFlagsInUseLine: true, + Hidden: true, + DisableFlagParsing: true, + Args: MinimumNArgs(1), + Short: "Request shell completion choices for the specified command-line", + Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s", + "to request completion choices for the specified command-line.", ShellCompRequestCmd), + Run: func(cmd *Command, args []string) { + finalCmd, completions, directive, err := cmd.getCompletions(args) + if err != nil { + CompErrorln(err.Error()) + // Keep going for multiple reasons: + // 1- There could be some valid completions even though there was an error + // 2- Even without completions, we need to print the directive + } + + noDescriptions := cmd.CalledAs() == ShellCompNoDescRequestCmd + if !noDescriptions { + if doDescriptions, err := strconv.ParseBool(getEnvConfig(cmd, configEnvVarSuffixDescriptions)); err == nil { + noDescriptions = !doDescriptions + } + } + noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable + out := finalCmd.OutOrStdout() + for _, comp := range completions { + if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) { + // Remove all activeHelp entries if it's disabled. + continue + } + if noDescriptions { + // Remove any description that may be included following a tab character. + comp = strings.SplitN(comp, "\t", 2)[0] + } + + // Make sure we only write the first line to the output. + // This is needed if a description contains a linebreak. + // Otherwise the shell scripts will interpret the other lines as new flags + // and could therefore provide a wrong completion. + comp = strings.SplitN(comp, "\n", 2)[0] + + // Finally trim the completion. This is especially important to get rid + // of a trailing tab when there are no description following it. + // For example, a sub-command without a description should not be completed + // with a tab at the end (or else zsh will show a -- following it + // although there is no description). + comp = strings.TrimSpace(comp) + + // Print each possible completion to the output for the completion script to consume. + fmt.Fprintln(out, comp) + } + + // As the last printout, print the completion directive for the completion script to parse. + // The directive integer must be that last character following a single colon (:). + // The completion script expects : + fmt.Fprintf(out, ":%d\n", directive) + + // Print some helpful info to stderr for the user to understand. + // Output from stderr must be ignored by the completion script. + fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string()) + }, + } + c.AddCommand(completeCmd) + subCmd, _, err := c.Find(args) + if err != nil || subCmd.Name() != ShellCompRequestCmd { + // Only create this special command if it is actually being called. + // This reduces possible side-effects of creating such a command; + // for example, having this command would cause problems to a + // cobra program that only consists of the root command, since this + // command would cause the root command to suddenly have a subcommand. + c.RemoveCommand(completeCmd) + } +} + +// SliceValue is a reduced version of [pflag.SliceValue]. It is used to detect +// flags that accept multiple values and therefore can provide completion +// multiple times. +type SliceValue interface { + // GetSlice returns the flag value list as an array of strings. + GetSlice() []string +} + +func (c *Command) getCompletions(args []string) (*Command, []Completion, ShellCompDirective, error) { + // The last argument, which is not completely typed by the user, + // should not be part of the list of arguments + toComplete := args[len(args)-1] + trimmedArgs := args[:len(args)-1] + + var finalCmd *Command + var finalArgs []string + var err error + // Find the real command for which completion must be performed + // check if we need to traverse here to parse local flags on parent commands + if c.Root().TraverseChildren { + finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs) + } else { + // For Root commands that don't specify any value for their Args fields, when we call + // Find(), if those Root commands don't have any sub-commands, they will accept arguments. + // However, because we have added the __complete sub-command in the current code path, the + // call to Find() -> legacyArgs() will return an error if there are any arguments. + // To avoid this, we first remove the __complete command to get back to having no sub-commands. + rootCmd := c.Root() + if len(rootCmd.Commands()) == 1 { + rootCmd.RemoveCommand(c) + } + + finalCmd, finalArgs, err = rootCmd.Find(trimmedArgs) + } + if err != nil { + // Unable to find the real command. E.g., someInvalidCmd + return c, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("unable to find a command for arguments: %v", trimmedArgs) + } + finalCmd.ctx = c.ctx + + // These flags are normally added when `execute()` is called on `finalCmd`, + // however, when doing completion, we don't call `finalCmd.execute()`. + // Let's add the --help and --version flag ourselves but only if the finalCmd + // has not disabled flag parsing; if flag parsing is disabled, it is up to the + // finalCmd itself to handle the completion of *all* flags. + if !finalCmd.DisableFlagParsing { + finalCmd.InitDefaultHelpFlag() + finalCmd.InitDefaultVersionFlag() + } + + // Check if we are doing flag value completion before parsing the flags. + // This is important because if we are completing a flag value, we need to also + // remove the flag name argument from the list of finalArgs or else the parsing + // could fail due to an invalid value (incomplete) for the flag. + flag, finalArgs, toComplete, flagErr := checkIfFlagCompletion(finalCmd, finalArgs, toComplete) + + // Check if interspersed is false or -- was set on a previous arg. + // This works by counting the arguments. Normally -- is not counted as arg but + // if -- was already set or interspersed is false and there is already one arg then + // the extra added -- is counted as arg. + flagCompletion := true + _ = finalCmd.ParseFlags(append(finalArgs, "--")) + newArgCount := finalCmd.Flags().NArg() + + // Parse the flags early so we can check if required flags are set + if err = finalCmd.ParseFlags(finalArgs); err != nil { + return finalCmd, []Completion{}, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error()) + } + + realArgCount := finalCmd.Flags().NArg() + if newArgCount > realArgCount { + // don't do flag completion (see above) + flagCompletion = false + } + // Error while attempting to parse flags + if flagErr != nil { + // If error type is flagCompError and we don't want flagCompletion we should ignore the error + if _, ok := flagErr.(*flagCompError); !ok || flagCompletion { + return finalCmd, []Completion{}, ShellCompDirectiveDefault, flagErr + } + } + + // Look for the --help or --version flags. If they are present, + // there should be no further completions. + if helpOrVersionFlagPresent(finalCmd) { + return finalCmd, []Completion{}, ShellCompDirectiveNoFileComp, nil + } + + // We only remove the flags from the arguments if DisableFlagParsing is not set. + // This is important for commands which have requested to do their own flag completion. + if !finalCmd.DisableFlagParsing { + finalArgs = finalCmd.Flags().Args() + } + + if flag != nil && flagCompletion { + // Check if we are completing a flag value subject to annotations + if validExts, present := flag.Annotations[BashCompFilenameExt]; present { + if len(validExts) != 0 { + // File completion filtered by extensions + return finalCmd, validExts, ShellCompDirectiveFilterFileExt, nil + } + + // The annotation requests simple file completion. There is no reason to do + // that since it is the default behavior anyway. Let's ignore this annotation + // in case the program also registered a completion function for this flag. + // Even though it is a mistake on the program's side, let's be nice when we can. + } + + if subDir, present := flag.Annotations[BashCompSubdirsInDir]; present { + if len(subDir) == 1 { + // Directory completion from within a directory + return finalCmd, subDir, ShellCompDirectiveFilterDirs, nil + } + // Directory completion + return finalCmd, []Completion{}, ShellCompDirectiveFilterDirs, nil + } + } + + var completions []Completion + var directive ShellCompDirective + + // Enforce flag groups before doing flag completions + finalCmd.enforceFlagGroupsForCompletion() + + // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true; + // doing this allows for completion of persistent flag names even for commands that disable flag parsing. + // + // When doing completion of a flag name, as soon as an argument starts with + // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires + // the flag name to be complete + if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion { + // First check for required flags + completions = completeRequireFlags(finalCmd, toComplete) + + // If we have not found any required flags, only then can we show regular flags + if len(completions) == 0 { + doCompleteFlags := func(flag *pflag.Flag) { + _, acceptsMultiple := flag.Value.(SliceValue) + acceptsMultiple = acceptsMultiple || + strings.Contains(flag.Value.Type(), "Slice") || + strings.Contains(flag.Value.Type(), "Array") || + strings.HasPrefix(flag.Value.Type(), "stringTo") + + if !flag.Changed || acceptsMultiple { + // If the flag is not already present, or if it can be specified multiple times (Array, Slice, or stringTo) + // we suggest it as a completion + completions = append(completions, getFlagNameCompletions(flag, toComplete)...) + } + } + + // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands + // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and + // non-inherited flags. + finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteFlags(flag) + }) + // Try to complete non-inherited flags even if DisableFlagParsing==true. + // This allows programs to tell Cobra about flags for completion even + // if the actual parsing of flags is not done by Cobra. + // For instance, Helm uses this to provide flag name completion for + // some of its plugins. + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteFlags(flag) + }) + } + + directive = ShellCompDirectiveNoFileComp + if len(completions) == 1 && strings.HasSuffix(completions[0], "=") { + // If there is a single completion, the shell usually adds a space + // after the completion. We don't want that if the flag ends with an = + directive = ShellCompDirectiveNoSpace + } + + if !finalCmd.DisableFlagParsing { + // If DisableFlagParsing==false, we have completed the flags as known by Cobra; + // we can return what we found. + // If DisableFlagParsing==true, Cobra may not be aware of all flags, so we + // let the logic continue to see if ValidArgsFunction needs to be called. + return finalCmd, completions, directive, nil + } + } else { + directive = ShellCompDirectiveDefault + // check current and parent commands for a custom DefaultShellCompDirective + for cmd := finalCmd; cmd != nil; cmd = cmd.parent { + if cmd.CompletionOptions.DefaultShellCompDirective != nil { + directive = *cmd.CompletionOptions.DefaultShellCompDirective + break + } + } + + if flag == nil { + foundLocalNonPersistentFlag := false + // If TraverseChildren is true on the root command we don't check for + // local flags because we can use a local flag on a parent command + if !finalCmd.Root().TraverseChildren { + // Check if there are any local, non-persistent flags on the command-line + localNonPersistentFlags := finalCmd.LocalNonPersistentFlags() + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed { + foundLocalNonPersistentFlag = true + } + }) + } + + // Complete subcommand names, including the help command + if len(finalArgs) == 0 && !foundLocalNonPersistentFlag { + // We only complete sub-commands if: + // - there are no arguments on the command-line and + // - there are no local, non-persistent flags on the command-line or TraverseChildren is true + for _, subCmd := range finalCmd.Commands() { + if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand { + if strings.HasPrefix(subCmd.Name(), toComplete) { + completions = append(completions, CompletionWithDesc(subCmd.Name(), subCmd.Short)) + } + directive = ShellCompDirectiveNoFileComp + } + } + } + + // Complete required flags even without the '-' prefix + completions = append(completions, completeRequireFlags(finalCmd, toComplete)...) + + // Always complete ValidArgs, even if we are completing a subcommand name. + // This is for commands that have both subcommands and ValidArgs. + if len(finalCmd.ValidArgs) > 0 { + if len(finalArgs) == 0 { + // ValidArgs are only for the first argument + for _, validArg := range finalCmd.ValidArgs { + if strings.HasPrefix(validArg, toComplete) { + completions = append(completions, validArg) + } + } + directive = ShellCompDirectiveNoFileComp + + // If no completions were found within commands or ValidArgs, + // see if there are any ArgAliases that should be completed. + if len(completions) == 0 { + for _, argAlias := range finalCmd.ArgAliases { + if strings.HasPrefix(argAlias, toComplete) { + completions = append(completions, argAlias) + } + } + } + } + + // If there are ValidArgs specified (even if they don't match), we stop completion. + // Only one of ValidArgs or ValidArgsFunction can be used for a single command. + return finalCmd, completions, directive, nil + } + + // Let the logic continue so as to add any ValidArgsFunction completions, + // even if we already found sub-commands. + // This is for commands that have subcommands but also specify a ValidArgsFunction. + } + } + + // Find the completion function for the flag or command + var completionFn CompletionFunc + if flag != nil && flagCompletion { + flagCompletionMutex.RLock() + completionFn = flagCompletionFunctions[flag] + flagCompletionMutex.RUnlock() + } else { + completionFn = finalCmd.ValidArgsFunction + } + if completionFn != nil { + // Go custom completion defined for this flag or command. + // Call the registered completion function to get the completions. + var comps []Completion + comps, directive = completionFn(finalCmd, finalArgs, toComplete) + completions = append(completions, comps...) + } + + return finalCmd, completions, directive, nil +} + +func helpOrVersionFlagPresent(cmd *Command) bool { + if versionFlag := cmd.Flags().Lookup("version"); versionFlag != nil && + len(versionFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && versionFlag.Changed { + return true + } + if helpFlag := cmd.Flags().Lookup(helpFlagName); helpFlag != nil && + len(helpFlag.Annotations[FlagSetByCobraAnnotation]) > 0 && helpFlag.Changed { + return true + } + return false +} + +func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []Completion { + if nonCompletableFlag(flag) { + return []Completion{} + } + + var completions []Completion + flagName := "--" + flag.Name + if strings.HasPrefix(flagName, toComplete) { + // Flag without the = + completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) + + // Why suggest both long forms: --flag and --flag= ? + // This forces the user to *always* have to type either an = or a space after the flag name. + // Let's be nice and avoid making users have to do that. + // Since boolean flags and shortname flags don't show the = form, let's go that route and never show it. + // The = form will still work, we just won't suggest it. + // This also makes the list of suggested flags shorter as we avoid all the = forms. + // + // if len(flag.NoOptDefVal) == 0 { + // // Flag requires a value, so it can be suffixed with = + // flagName += "=" + // completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) + // } + } + + flagName = "-" + flag.Shorthand + if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) { + completions = append(completions, CompletionWithDesc(flagName, flag.Usage)) + } + + return completions +} + +func completeRequireFlags(finalCmd *Command, toComplete string) []Completion { + var completions []Completion + + doCompleteRequiredFlags := func(flag *pflag.Flag) { + if _, present := flag.Annotations[BashCompOneRequiredFlag]; present { + if !flag.Changed { + // If the flag is not already present, we suggest it as a completion + completions = append(completions, getFlagNameCompletions(flag, toComplete)...) + } + } + } + + // We cannot use finalCmd.Flags() because we may not have called ParsedFlags() for commands + // that have set DisableFlagParsing; it is ParseFlags() that merges the inherited and + // non-inherited flags. + finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteRequiredFlags(flag) + }) + finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) { + doCompleteRequiredFlags(flag) + }) + + return completions +} + +func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) { + if finalCmd.DisableFlagParsing { + // We only do flag completion if we are allowed to parse flags + // This is important for commands which have requested to do their own flag completion. + return nil, args, lastArg, nil + } + + var flagName string + trimmedArgs := args + flagWithEqual := false + orgLastArg := lastArg + + // When doing completion of a flag name, as soon as an argument starts with + // a '-' we know it is a flag. We cannot use isFlagArg() here as that function + // requires the flag name to be complete + if len(lastArg) > 0 && lastArg[0] == '-' { + if index := strings.Index(lastArg, "="); index >= 0 { + // Flag with an = + if strings.HasPrefix(lastArg[:index], "--") { + // Flag has full name + flagName = lastArg[2:index] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = lastArg[index-1 : index] + } + lastArg = lastArg[index+1:] + flagWithEqual = true + } else { + // Normal flag completion + return nil, args, lastArg, nil + } + } + + if len(flagName) == 0 { + if len(args) > 0 { + prevArg := args[len(args)-1] + if isFlagArg(prevArg) { + // Only consider the case where the flag does not contain an =. + // If the flag contains an = it means it has already been fully processed, + // so we don't need to deal with it here. + if index := strings.Index(prevArg, "="); index < 0 { + if strings.HasPrefix(prevArg, "--") { + // Flag has full name + flagName = prevArg[2:] + } else { + // Flag is shorthand + // We have to get the last shorthand flag name + // e.g. `-asd` => d to provide the correct completion + // https://github.com/spf13/cobra/issues/1257 + flagName = prevArg[len(prevArg)-1:] + } + // Remove the uncompleted flag or else there could be an error created + // for an invalid value for that flag + trimmedArgs = args[:len(args)-1] + } + } + } + } + + if len(flagName) == 0 { + // Not doing flag completion + return nil, trimmedArgs, lastArg, nil + } + + flag := findFlag(finalCmd, flagName) + if flag == nil { + // Flag not supported by this command, the interspersed option might be set so return the original args + return nil, args, orgLastArg, &flagCompError{subCommand: finalCmd.Name(), flagName: flagName} + } + + if !flagWithEqual { + if len(flag.NoOptDefVal) != 0 { + // We had assumed dealing with a two-word flag but the flag is a boolean flag. + // In that case, there is no value following it, so we are not really doing flag completion. + // Reset everything to do noun completion. + trimmedArgs = args + flag = nil + } + } + + return flag, trimmedArgs, lastArg, nil +} + +// InitDefaultCompletionCmd adds a default 'completion' command to c. +// This function will do nothing if any of the following is true: +// 1- the feature has been explicitly disabled by the program, +// 2- c has no subcommands (to avoid creating one), +// 3- c already has a 'completion' command provided by the program. +func (c *Command) InitDefaultCompletionCmd(args ...string) { + if c.CompletionOptions.DisableDefaultCmd { + return + } + + for _, cmd := range c.commands { + if cmd.Name() == compCmdName || cmd.HasAlias(compCmdName) { + // A completion command is already available + return + } + } + + haveNoDescFlag := !c.CompletionOptions.DisableNoDescFlag && !c.CompletionOptions.DisableDescriptions + + // Special case to know if there are sub-commands or not. + hasSubCommands := false + for _, cmd := range c.commands { + if cmd.Name() != ShellCompRequestCmd && cmd.Name() != helpCommandName { + // We found a real sub-command (not 'help' or '__complete') + hasSubCommands = true + break + } + } + + completionCmd := &Command{ + Use: compCmdName, + Short: "Generate the autocompletion script for the specified shell", + Long: fmt.Sprintf(`Generate the autocompletion script for %[1]s for the specified shell. +See each sub-command's help for details on how to use the generated script. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + Hidden: c.CompletionOptions.HiddenDefaultCmd, + GroupID: c.completionCommandGroupID, + } + c.AddCommand(completionCmd) + + if !hasSubCommands { + // If the 'completion' command will be the only sub-command, + // we only create it if it is actually being called. + // This avoids breaking programs that would suddenly find themselves with + // a subcommand, which would prevent them from accepting arguments. + // We also create the 'completion' command if the user is triggering + // shell completion for it (prog __complete completion '') + subCmd, cmdArgs, err := c.Find(args) + if err != nil || subCmd.Name() != compCmdName && + (subCmd.Name() != ShellCompRequestCmd || len(cmdArgs) <= 1 || cmdArgs[0] != compCmdName) { + // The completion command is not being called or being completed so we remove it. + c.RemoveCommand(completionCmd) + return + } + } + + out := c.OutOrStdout() + noDesc := c.CompletionOptions.DisableDescriptions + shortDesc := "Generate the autocompletion script for %s" + bash := &Command{ + Use: "bash", + Short: fmt.Sprintf(shortDesc, "bash"), + Long: fmt.Sprintf(`Generate the autocompletion script for the bash shell. + +This script depends on the 'bash-completion' package. +If it is not installed already, you can install it via your OS's package manager. + +To load completions in your current shell session: + + source <(%[1]s completion bash) + +To load completions for every new session, execute once: + +#### Linux: + + %[1]s completion bash > /etc/bash_completion.d/%[1]s + +#### macOS: + + %[1]s completion bash > $(brew --prefix)/etc/bash_completion.d/%[1]s + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + DisableFlagsInUseLine: true, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + return cmd.Root().GenBashCompletionV2(out, !noDesc) + }, + } + if haveNoDescFlag { + bash.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + zsh := &Command{ + Use: "zsh", + Short: fmt.Sprintf(shortDesc, "zsh"), + Long: fmt.Sprintf(`Generate the autocompletion script for the zsh shell. + +If shell completion is not already enabled in your environment you will need +to enable it. You can execute the following once: + + echo "autoload -U compinit; compinit" >> ~/.zshrc + +To load completions in your current shell session: + + source <(%[1]s completion zsh) + +To load completions for every new session, execute once: + +#### Linux: + + %[1]s completion zsh > "${fpath[1]}/_%[1]s" + +#### macOS: + + %[1]s completion zsh > $(brew --prefix)/share/zsh/site-functions/_%[1]s + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + if noDesc { + return cmd.Root().GenZshCompletionNoDesc(out) + } + return cmd.Root().GenZshCompletion(out) + }, + } + if haveNoDescFlag { + zsh.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + fish := &Command{ + Use: "fish", + Short: fmt.Sprintf(shortDesc, "fish"), + Long: fmt.Sprintf(`Generate the autocompletion script for the fish shell. + +To load completions in your current shell session: + + %[1]s completion fish | source + +To load completions for every new session, execute once: + + %[1]s completion fish > ~/.config/fish/completions/%[1]s.fish + +You will need to start a new shell for this setup to take effect. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + return cmd.Root().GenFishCompletion(out, !noDesc) + }, + } + if haveNoDescFlag { + fish.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + powershell := &Command{ + Use: "powershell", + Short: fmt.Sprintf(shortDesc, "powershell"), + Long: fmt.Sprintf(`Generate the autocompletion script for powershell. + +To load completions in your current shell session: + + %[1]s completion powershell | Out-String | Invoke-Expression + +To load completions for every new session, add the output of the above command +to your powershell profile. +`, c.Root().Name()), + Args: NoArgs, + ValidArgsFunction: NoFileCompletions, + RunE: func(cmd *Command, args []string) error { + if noDesc { + return cmd.Root().GenPowerShellCompletion(out) + } + return cmd.Root().GenPowerShellCompletionWithDesc(out) + + }, + } + if haveNoDescFlag { + powershell.Flags().BoolVar(&noDesc, compCmdNoDescFlagName, compCmdNoDescFlagDefault, compCmdNoDescFlagDesc) + } + + completionCmd.AddCommand(bash, zsh, fish, powershell) +} + +func findFlag(cmd *Command, name string) *pflag.Flag { + flagSet := cmd.Flags() + if len(name) == 1 { + // First convert the short flag into a long flag + // as the cmd.Flag() search only accepts long flags + if short := flagSet.ShorthandLookup(name); short != nil { + name = short.Name + } else { + set := cmd.InheritedFlags() + if short = set.ShorthandLookup(name); short != nil { + name = short.Name + } else { + return nil + } + } + } + return cmd.Flag(name) +} + +// CompDebug prints the specified string to the same file as where the +// completion script prints its logs. +// Note that completion printouts should never be on stdout as they would +// be wrongly interpreted as actual completion choices by the completion script. +func CompDebug(msg string, printToStdErr bool) { + msg = fmt.Sprintf("[Debug] %s", msg) + + // Such logs are only printed when the user has set the environment + // variable BASH_COMP_DEBUG_FILE to the path of some file to be used. + if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" { + f, err := os.OpenFile(path, + os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if err == nil { + defer f.Close() + WriteStringAndCheck(f, msg) + } + } + + if printToStdErr { + // Must print to stderr for this not to be read by the completion script. + fmt.Fprint(os.Stderr, msg) + } +} + +// CompDebugln prints the specified string with a newline at the end +// to the same file as where the completion script prints its logs. +// Such logs are only printed when the user has set the environment +// variable BASH_COMP_DEBUG_FILE to the path of some file to be used. +func CompDebugln(msg string, printToStdErr bool) { + CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr) +} + +// CompError prints the specified completion message to stderr. +func CompError(msg string) { + msg = fmt.Sprintf("[Error] %s", msg) + CompDebug(msg, true) +} + +// CompErrorln prints the specified completion message to stderr with a newline at the end. +func CompErrorln(msg string) { + CompError(fmt.Sprintf("%s\n", msg)) +} + +// These values should not be changed: users will be using them explicitly. +const ( + configEnvVarGlobalPrefix = "COBRA" + configEnvVarSuffixDescriptions = "COMPLETION_DESCRIPTIONS" +) + +var configEnvVarPrefixSubstRegexp = regexp.MustCompile(`[^A-Z0-9_]`) + +// configEnvVar returns the name of the program-specific configuration environment +// variable. It has the format _ where is the name of the +// root command in upper case, with all non-ASCII-alphanumeric characters replaced by `_`. +func configEnvVar(name, suffix string) string { + // This format should not be changed: users will be using it explicitly. + v := strings.ToUpper(fmt.Sprintf("%s_%s", name, suffix)) + v = configEnvVarPrefixSubstRegexp.ReplaceAllString(v, "_") + return v +} + +// getEnvConfig returns the value of the configuration environment variable +// _ where is the name of the root command in upper +// case, with all non-ASCII-alphanumeric characters replaced by `_`. +// If the value is empty or not set, the value of the environment variable +// COBRA_ is returned instead. +func getEnvConfig(cmd *Command, suffix string) string { + v := os.Getenv(configEnvVar(cmd.Root().Name(), suffix)) + if v == "" { + v = os.Getenv(configEnvVar(configEnvVarGlobalPrefix, suffix)) + } + return v +} diff --git a/vendor/github.com/spf13/cobra/fish_completions.go b/vendor/github.com/spf13/cobra/fish_completions.go new file mode 100644 index 0000000..12d61b6 --- /dev/null +++ b/vendor/github.com/spf13/cobra/fish_completions.go @@ -0,0 +1,292 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "strings" +) + +func genFishComp(buf io.StringWriter, name string, includeDesc bool) { + // Variables should not contain a '-' or ':' character + nameForVar := name + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") + + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + WriteStringAndCheck(buf, fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name)) + WriteStringAndCheck(buf, fmt.Sprintf(` +function __%[1]s_debug + set -l file "$BASH_COMP_DEBUG_FILE" + if test -n "$file" + echo "$argv" >> $file + end +end + +function __%[1]s_perform_completion + __%[1]s_debug "Starting __%[1]s_perform_completion" + + # Extract all args except the last one + set -l args (commandline -opc) + # Extract the last arg and escape it in case it is a space + set -l lastArg (string escape -- (commandline -ct)) + + __%[1]s_debug "args: $args" + __%[1]s_debug "last arg: $lastArg" + + # Disable ActiveHelp which is not supported for fish shell + set -l requestComp "%[10]s=0 $args[1] %[3]s $args[2..-1] $lastArg" + + __%[1]s_debug "Calling $requestComp" + set -l results (eval $requestComp 2> /dev/null) + + # Some programs may output extra empty lines after the directive. + # Let's ignore them or else it will break completion. + # Ref: https://github.com/spf13/cobra/issues/1279 + for line in $results[-1..1] + if test (string trim -- $line) = "" + # Found an empty line, remove it + set results $results[1..-2] + else + # Found non-empty line, we have our proper output + break + end + end + + set -l comps $results[1..-2] + set -l directiveLine $results[-1] + + # For Fish, when completing a flag with an = (e.g., -n=) + # completions must be prefixed with the flag + set -l flagPrefix (string match -r -- '-.*=' "$lastArg") + + __%[1]s_debug "Comps: $comps" + __%[1]s_debug "DirectiveLine: $directiveLine" + __%[1]s_debug "flagPrefix: $flagPrefix" + + for comp in $comps + printf "%%s%%s\n" "$flagPrefix" "$comp" + end + + printf "%%s\n" "$directiveLine" +end + +# this function limits calls to __%[1]s_perform_completion, by caching the result behind $__%[1]s_perform_completion_once_result +function __%[1]s_perform_completion_once + __%[1]s_debug "Starting __%[1]s_perform_completion_once" + + if test -n "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Seems like a valid result already exists, skipping __%[1]s_perform_completion" + return 0 + end + + set --global __%[1]s_perform_completion_once_result (__%[1]s_perform_completion) + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "No completions, probably due to a failure" + return 1 + end + + __%[1]s_debug "Performed completions and set __%[1]s_perform_completion_once_result" + return 0 +end + +# this function is used to clear the $__%[1]s_perform_completion_once_result variable after completions are run +function __%[1]s_clear_perform_completion_once_result + __%[1]s_debug "" + __%[1]s_debug "========= clearing previously set __%[1]s_perform_completion_once_result variable ==========" + set --erase __%[1]s_perform_completion_once_result + __%[1]s_debug "Successfully erased the variable __%[1]s_perform_completion_once_result" +end + +function __%[1]s_requires_order_preservation + __%[1]s_debug "" + __%[1]s_debug "========= checking if order preservation is required ==========" + + __%[1]s_perform_completion_once + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "Error determining if order preservation is required" + return 1 + end + + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + __%[1]s_debug "Directive is: $directive" + + set -l shellCompDirectiveKeepOrder %[9]d + set -l keeporder (math (math --scale 0 $directive / $shellCompDirectiveKeepOrder) %% 2) + __%[1]s_debug "Keeporder is: $keeporder" + + if test $keeporder -ne 0 + __%[1]s_debug "This does require order preservation" + return 0 + end + + __%[1]s_debug "This doesn't require order preservation" + return 1 +end + + +# This function does two things: +# - Obtain the completions and store them in the global __%[1]s_comp_results +# - Return false if file completion should be performed +function __%[1]s_prepare_completions + __%[1]s_debug "" + __%[1]s_debug "========= starting completion logic ==========" + + # Start fresh + set --erase __%[1]s_comp_results + + __%[1]s_perform_completion_once + __%[1]s_debug "Completion results: $__%[1]s_perform_completion_once_result" + + if test -z "$__%[1]s_perform_completion_once_result" + __%[1]s_debug "No completion, probably due to a failure" + # Might as well do file completion, in case it helps + return 1 + end + + set -l directive (string sub --start 2 $__%[1]s_perform_completion_once_result[-1]) + set --global __%[1]s_comp_results $__%[1]s_perform_completion_once_result[1..-2] + + __%[1]s_debug "Completions are: $__%[1]s_comp_results" + __%[1]s_debug "Directive is: $directive" + + set -l shellCompDirectiveError %[4]d + set -l shellCompDirectiveNoSpace %[5]d + set -l shellCompDirectiveNoFileComp %[6]d + set -l shellCompDirectiveFilterFileExt %[7]d + set -l shellCompDirectiveFilterDirs %[8]d + + if test -z "$directive" + set directive 0 + end + + set -l compErr (math (math --scale 0 $directive / $shellCompDirectiveError) %% 2) + if test $compErr -eq 1 + __%[1]s_debug "Received error directive: aborting." + # Might as well do file completion, in case it helps + return 1 + end + + set -l filefilter (math (math --scale 0 $directive / $shellCompDirectiveFilterFileExt) %% 2) + set -l dirfilter (math (math --scale 0 $directive / $shellCompDirectiveFilterDirs) %% 2) + if test $filefilter -eq 1; or test $dirfilter -eq 1 + __%[1]s_debug "File extension filtering or directory filtering not supported" + # Do full file completion instead + return 1 + end + + set -l nospace (math (math --scale 0 $directive / $shellCompDirectiveNoSpace) %% 2) + set -l nofiles (math (math --scale 0 $directive / $shellCompDirectiveNoFileComp) %% 2) + + __%[1]s_debug "nospace: $nospace, nofiles: $nofiles" + + # If we want to prevent a space, or if file completion is NOT disabled, + # we need to count the number of valid completions. + # To do so, we will filter on prefix as the completions we have received + # may not already be filtered so as to allow fish to match on different + # criteria than the prefix. + if test $nospace -ne 0; or test $nofiles -eq 0 + set -l prefix (commandline -t | string escape --style=regex) + __%[1]s_debug "prefix: $prefix" + + set -l completions (string match -r -- "^$prefix.*" $__%[1]s_comp_results) + set --global __%[1]s_comp_results $completions + __%[1]s_debug "Filtered completions are: $__%[1]s_comp_results" + + # Important not to quote the variable for count to work + set -l numComps (count $__%[1]s_comp_results) + __%[1]s_debug "numComps: $numComps" + + if test $numComps -eq 1; and test $nospace -ne 0 + # We must first split on \t to get rid of the descriptions to be + # able to check what the actual completion will be. + # We don't need descriptions anyway since there is only a single + # real completion which the shell will expand immediately. + set -l split (string split --max 1 \t $__%[1]s_comp_results[1]) + + # Fish won't add a space if the completion ends with any + # of the following characters: @=/:., + set -l lastChar (string sub -s -1 -- $split) + if not string match -r -q "[@=/:.,]" -- "$lastChar" + # In other cases, to support the "nospace" directive we trick the shell + # by outputting an extra, longer completion. + __%[1]s_debug "Adding second completion to perform nospace directive" + set --global __%[1]s_comp_results $split[1] $split[1]. + __%[1]s_debug "Completions are now: $__%[1]s_comp_results" + end + end + + if test $numComps -eq 0; and test $nofiles -eq 0 + # To be consistent with bash and zsh, we only trigger file + # completion when there are no other completions + __%[1]s_debug "Requesting file completion" + return 1 + end + end + + return 0 +end + +# Since Fish completions are only loaded once the user triggers them, we trigger them ourselves +# so we can properly delete any completions provided by another script. +# Only do this if the program can be found, or else fish may print some errors; besides, +# the existing completions will only be loaded if the program can be found. +if type -q "%[2]s" + # The space after the program name is essential to trigger completion for the program + # and not completion of the program name itself. + # Also, we use '> /dev/null 2>&1' since '&>' is not supported in older versions of fish. + complete --do-complete "%[2]s " > /dev/null 2>&1 +end + +# Remove any pre-existing completions for the program since we will be handling all of them. +complete -c %[2]s -e + +# this will get called after the two calls below and clear the $__%[1]s_perform_completion_once_result global +complete -c %[2]s -n '__%[1]s_clear_perform_completion_once_result' +# The call to __%[1]s_prepare_completions will setup __%[1]s_comp_results +# which provides the program's completion choices. +# If this doesn't require order preservation, we don't use the -k flag +complete -c %[2]s -n 'not __%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' +# otherwise we use the -k flag +complete -k -c %[2]s -n '__%[1]s_requires_order_preservation && __%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results' +`, nameForVar, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) +} + +// GenFishCompletion generates fish completion file and writes to the passed writer. +func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genFishComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +// GenFishCompletionFile generates fish completion file. +func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.GenFishCompletion(outFile, includeDesc) +} diff --git a/vendor/github.com/spf13/cobra/flag_groups.go b/vendor/github.com/spf13/cobra/flag_groups.go new file mode 100644 index 0000000..560612f --- /dev/null +++ b/vendor/github.com/spf13/cobra/flag_groups.go @@ -0,0 +1,290 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "fmt" + "sort" + "strings" + + flag "github.com/spf13/pflag" +) + +const ( + requiredAsGroupAnnotation = "cobra_annotation_required_if_others_set" + oneRequiredAnnotation = "cobra_annotation_one_required" + mutuallyExclusiveAnnotation = "cobra_annotation_mutually_exclusive" +) + +// MarkFlagsRequiredTogether marks the given flags with annotations so that Cobra errors +// if the command is invoked with a subset (but not all) of the given flags. +func (c *Command) MarkFlagsRequiredTogether(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being required in a flag group", v)) + } + if err := c.Flags().SetAnnotation(v, requiredAsGroupAnnotation, append(f.Annotations[requiredAsGroupAnnotation], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + +// MarkFlagsOneRequired marks the given flags with annotations so that Cobra errors +// if the command is invoked without at least one flag from the given set of flags. +func (c *Command) MarkFlagsOneRequired(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a one-required flag group", v)) + } + if err := c.Flags().SetAnnotation(v, oneRequiredAnnotation, append(f.Annotations[oneRequiredAnnotation], strings.Join(flagNames, " "))); err != nil { + // Only errs if the flag isn't found. + panic(err) + } + } +} + +// MarkFlagsMutuallyExclusive marks the given flags with annotations so that Cobra errors +// if the command is invoked with more than one flag from the given set of flags. +func (c *Command) MarkFlagsMutuallyExclusive(flagNames ...string) { + c.mergePersistentFlags() + for _, v := range flagNames { + f := c.Flags().Lookup(v) + if f == nil { + panic(fmt.Sprintf("Failed to find flag %q and mark it as being in a mutually exclusive flag group", v)) + } + // Each time this is called is a single new entry; this allows it to be a member of multiple groups if needed. + if err := c.Flags().SetAnnotation(v, mutuallyExclusiveAnnotation, append(f.Annotations[mutuallyExclusiveAnnotation], strings.Join(flagNames, " "))); err != nil { + panic(err) + } + } +} + +// ValidateFlagGroups validates the mutuallyExclusive/oneRequired/requiredAsGroup logic and returns the +// first error encountered. +func (c *Command) ValidateFlagGroups() error { + if c.DisableFlagParsing { + return nil + } + + flags := c.Flags() + + // groupStatus format is the list of flags as a unique ID, + // then a map of each flag name and whether it is set or not. + groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} + mutuallyExclusiveGroupStatus := map[string]map[string]bool{} + flags.VisitAll(func(pflag *flag.Flag) { + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) + }) + + if err := validateRequiredFlagGroups(groupStatus); err != nil { + return err + } + if err := validateOneRequiredFlagGroups(oneRequiredGroupStatus); err != nil { + return err + } + if err := validateExclusiveFlagGroups(mutuallyExclusiveGroupStatus); err != nil { + return err + } + return nil +} + +func hasAllFlags(fs *flag.FlagSet, flagnames ...string) bool { + for _, fname := range flagnames { + f := fs.Lookup(fname) + if f == nil { + return false + } + } + return true +} + +func processFlagForGroupAnnotation(flags *flag.FlagSet, pflag *flag.Flag, annotation string, groupStatus map[string]map[string]bool) { + groupInfo, found := pflag.Annotations[annotation] + if found { + for _, group := range groupInfo { + if groupStatus[group] == nil { + flagnames := strings.Split(group, " ") + + // Only consider this flag group at all if all the flags are defined. + if !hasAllFlags(flags, flagnames...) { + continue + } + + groupStatus[group] = make(map[string]bool, len(flagnames)) + for _, name := range flagnames { + groupStatus[group][name] = false + } + } + + groupStatus[group][pflag.Name] = pflag.Changed + } + } +} + +func validateRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + + unset := []string{} + for flagname, isSet := range flagnameAndStatus { + if !isSet { + unset = append(unset, flagname) + } + } + if len(unset) == len(flagnameAndStatus) || len(unset) == 0 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(unset) + return fmt.Errorf("if any flags in the group [%v] are set they must all be set; missing %v", flagList, unset) + } + + return nil +} + +func validateOneRequiredFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) >= 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("at least one of the flags in the group [%v] is required", flagList) + } + return nil +} + +func validateExclusiveFlagGroups(data map[string]map[string]bool) error { + keys := sortedKeys(data) + for _, flagList := range keys { + flagnameAndStatus := data[flagList] + var set []string + for flagname, isSet := range flagnameAndStatus { + if isSet { + set = append(set, flagname) + } + } + if len(set) == 0 || len(set) == 1 { + continue + } + + // Sort values, so they can be tested/scripted against consistently. + sort.Strings(set) + return fmt.Errorf("if any flags in the group [%v] are set none of the others can be; %v were all set", flagList, set) + } + return nil +} + +func sortedKeys(m map[string]map[string]bool) []string { + keys := make([]string, len(m)) + i := 0 + for k := range m { + keys[i] = k + i++ + } + sort.Strings(keys) + return keys +} + +// enforceFlagGroupsForCompletion will do the following: +// - when a flag in a group is present, other flags in the group will be marked required +// - when none of the flags in a one-required group are present, all flags in the group will be marked required +// - when a flag in a mutually exclusive group is present, other flags in the group will be marked as hidden +// This allows the standard completion logic to behave appropriately for flag groups +func (c *Command) enforceFlagGroupsForCompletion() { + if c.DisableFlagParsing { + return + } + + flags := c.Flags() + groupStatus := map[string]map[string]bool{} + oneRequiredGroupStatus := map[string]map[string]bool{} + mutuallyExclusiveGroupStatus := map[string]map[string]bool{} + c.Flags().VisitAll(func(pflag *flag.Flag) { + processFlagForGroupAnnotation(flags, pflag, requiredAsGroupAnnotation, groupStatus) + processFlagForGroupAnnotation(flags, pflag, oneRequiredAnnotation, oneRequiredGroupStatus) + processFlagForGroupAnnotation(flags, pflag, mutuallyExclusiveAnnotation, mutuallyExclusiveGroupStatus) + }) + + // If a flag that is part of a group is present, we make all the other flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range groupStatus { + for _, isSet := range flagnameAndStatus { + if isSet { + // One of the flags of the group is set, mark the other ones as required + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + } + + // If none of the flags of a one-required group are present, we make all the flags + // of that group required so that the shell completion suggests them automatically + for flagList, flagnameAndStatus := range oneRequiredGroupStatus { + isSet := false + + for _, isSet = range flagnameAndStatus { + if isSet { + break + } + } + + // None of the flags of the group are set, mark all flags in the group + // as required + if !isSet { + for _, fName := range strings.Split(flagList, " ") { + _ = c.MarkFlagRequired(fName) + } + } + } + + // If a flag that is mutually exclusive to others is present, we hide the other + // flags of that group so the shell completion does not suggest them + for flagList, flagnameAndStatus := range mutuallyExclusiveGroupStatus { + for flagName, isSet := range flagnameAndStatus { + if isSet { + // One of the flags of the mutually exclusive group is set, mark the other ones as hidden + // Don't mark the flag that is already set as hidden because it may be an + // array or slice flag and therefore must continue being suggested + for _, fName := range strings.Split(flagList, " ") { + if fName != flagName { + flag := c.Flags().Lookup(fName) + flag.Hidden = true + } + } + } + } + } +} diff --git a/vendor/github.com/spf13/cobra/powershell_completions.go b/vendor/github.com/spf13/cobra/powershell_completions.go new file mode 100644 index 0000000..746dcb9 --- /dev/null +++ b/vendor/github.com/spf13/cobra/powershell_completions.go @@ -0,0 +1,350 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but +// can be downloaded separately for windows 7 or 8.1). + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" + "strings" +) + +func genPowerShellComp(buf io.StringWriter, name string, includeDesc bool) { + // Variables should not contain a '-' or ':' character + nameForVar := name + nameForVar = strings.ReplaceAll(nameForVar, "-", "_") + nameForVar = strings.ReplaceAll(nameForVar, ":", "_") + + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + WriteStringAndCheck(buf, fmt.Sprintf(`# powershell completion for %-36[1]s -*- shell-script -*- + +function __%[1]s_debug { + if ($env:BASH_COMP_DEBUG_FILE) { + "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE" + } +} + +filter __%[1]s_escapeStringWithSpecialChars { +`+" $_ -replace '\\s|#|@|\\$|;|,|''|\\{|\\}|\\(|\\)|\"|`|\\||<|>|&','`$&'"+` +} + +[scriptblock]${__%[2]sCompleterBlock} = { + param( + $WordToComplete, + $CommandAst, + $CursorPosition + ) + + # Get the current command line and convert into a string + $Command = $CommandAst.CommandElements + $Command = "$Command" + + __%[1]s_debug "" + __%[1]s_debug "========= starting completion logic ==========" + __%[1]s_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CursorPosition location, so we need + # to truncate the command-line ($Command) up to the $CursorPosition location. + # Make sure the $Command is longer then the $CursorPosition before we truncate. + # This happens because the $Command does not include the last space. + if ($Command.Length -gt $CursorPosition) { + $Command=$Command.Substring(0,$CursorPosition) + } + __%[1]s_debug "Truncated command: $Command" + + $ShellCompDirectiveError=%[4]d + $ShellCompDirectiveNoSpace=%[5]d + $ShellCompDirectiveNoFileComp=%[6]d + $ShellCompDirectiveFilterFileExt=%[7]d + $ShellCompDirectiveFilterDirs=%[8]d + $ShellCompDirectiveKeepOrder=%[9]d + + # Prepare the command to request completions for the program. + # Split the command at the first space to separate the program and arguments. + $Program,$Arguments = $Command.Split(" ",2) + + $RequestComp="$Program %[3]s $Arguments" + __%[1]s_debug "RequestComp: $RequestComp" + + # we cannot use $WordToComplete because it + # has the wrong values if the cursor was moved + # so use the last argument + if ($WordToComplete -ne "" ) { + $WordToComplete = $Arguments.Split(" ")[-1] + } + __%[1]s_debug "New WordToComplete: $WordToComplete" + + + # Check for flag with equal sign + $IsEqualFlag = ($WordToComplete -Like "--*=*" ) + if ( $IsEqualFlag ) { + __%[1]s_debug "Completing equal sign flag" + # Remove the flag part + $Flag,$WordToComplete = $WordToComplete.Split("=",2) + } + + if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) { + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go method. + __%[1]s_debug "Adding extra empty parameter" + # PowerShell 7.2+ changed the way how the arguments are passed to executables, + # so for pre-7.2 or when Legacy argument passing is enabled we need to use +`+" # `\"`\" to pass an empty argument, a \"\" or '' does not work!!!"+` + if ($PSVersionTable.PsVersion -lt [version]'7.2.0' -or + ($PSVersionTable.PsVersion -lt [version]'7.3.0' -and -not [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -or + (($PSVersionTable.PsVersion -ge [version]'7.3.0' -or [ExperimentalFeature]::IsEnabled("PSNativeCommandArgumentPassing")) -and + $PSNativeCommandArgumentPassing -eq 'Legacy')) { +`+" $RequestComp=\"$RequestComp\" + ' `\"`\"'"+` + } else { + $RequestComp="$RequestComp" + ' ""' + } + } + + __%[1]s_debug "Calling $RequestComp" + # First disable ActiveHelp which is not supported for Powershell + ${env:%[10]s}=0 + + #call the command store the output in $out and redirect stderr and stdout to null + # $Out is an array contains each line per element + Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null + + # get directive from last line + [int]$Directive = $Out[-1].TrimStart(':') + if ($Directive -eq "") { + # There is no directive specified + $Directive = 0 + } + __%[1]s_debug "The completion directive is: $Directive" + + # remove directive (last element) from out + $Out = $Out | Where-Object { $_ -ne $Out[-1] } + __%[1]s_debug "The completions are: $Out" + + if (($Directive -band $ShellCompDirectiveError) -ne 0 ) { + # Error code. No completion. + __%[1]s_debug "Received error from custom completion go code" + return + } + + $Longest = 0 + [Array]$Values = $Out | ForEach-Object { + #Split the output in name and description +`+" $Name, $Description = $_.Split(\"`t\",2)"+` + __%[1]s_debug "Name: $Name Description: $Description" + + # Look for the longest completion so that we can format things nicely + if ($Longest -lt $Name.Length) { + $Longest = $Name.Length + } + + # Set the description to a one space string if there is none set. + # This is needed because the CompletionResult does not accept an empty string as argument + if (-Not $Description) { + $Description = " " + } + New-Object -TypeName PSCustomObject -Property @{ + Name = "$Name" + Description = "$Description" + } + } + + + $Space = " " + if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) { + # remove the space here + __%[1]s_debug "ShellCompDirectiveNoSpace is called" + $Space = "" + } + + if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or + (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 )) { + __%[1]s_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported" + + # return here to prevent the completion of the extensions + return + } + + $Values = $Values | Where-Object { + # filter the result + $_.Name -like "$WordToComplete*" + + # Join the flag back if we have an equal sign flag + if ( $IsEqualFlag ) { + __%[1]s_debug "Join the equal sign flag back to the completion value" + $_.Name = $Flag + "=" + $_.Name + } + } + + # we sort the values in ascending order by name if keep order isn't passed + if (($Directive -band $ShellCompDirectiveKeepOrder) -eq 0 ) { + $Values = $Values | Sort-Object -Property Name + } + + if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) { + __%[1]s_debug "ShellCompDirectiveNoFileComp is called" + + if ($Values.Length -eq 0) { + # Just print an empty string here so the + # shell does not start to complete paths. + # We cannot use CompletionResult here because + # it does not accept an empty string as argument. + "" + return + } + } + + # Get the current mode + $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function + __%[1]s_debug "Mode: $Mode" + + $Values | ForEach-Object { + + # store temporary because switch will overwrite $_ + $comp = $_ + + # PowerShell supports three different completion modes + # - TabCompleteNext (default windows style - on each key press the next option is displayed) + # - Complete (works like bash) + # - MenuComplete (works like zsh) + # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function + + # CompletionResult Arguments: + # 1) CompletionText text to be used as the auto completion result + # 2) ListItemText text to be displayed in the suggestion list + # 3) ResultType type of completion result + # 4) ToolTip text for the tooltip with details about the object + + switch ($Mode) { + + # bash like + "Complete" { + + if ($Values.Length -eq 1) { + __%[1]s_debug "Only one completion left" + + # insert space after value + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + + } else { + # Add the proper number of spaces to align the descriptions + while($comp.Name.Length -lt $Longest) { + $comp.Name = $comp.Name + " " + } + + # Check for empty description and only add parentheses if needed + if ($($comp.Description) -eq " " ) { + $Description = "" + } else { + $Description = " ($($comp.Description))" + } + + $CompletionText = "$($comp.Name)$Description" + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + } + } + + # zsh like + "MenuComplete" { + # insert space after value + # MenuComplete will automatically show the ToolTip of + # the highlighted value at the bottom of the suggestions. + + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + $Space + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + } + + # TabCompleteNext and in case we get something unknown + Default { + # Like MenuComplete but we don't want to add a space here because + # the user need to press space anyway to get the completion. + # Description will not be shown because that's not possible with TabCompleteNext + + $CompletionText = $($comp.Name | __%[1]s_escapeStringWithSpecialChars) + if ($ExecutionContext.SessionState.LanguageMode -eq "FullLanguage"){ + [System.Management.Automation.CompletionResult]::new($CompletionText, "$($comp.Name)", 'ParameterValue', "$($comp.Description)") + } else { + $CompletionText + } + } + } + + } +} + +Register-ArgumentCompleter -CommandName '%[1]s' -ScriptBlock ${__%[2]sCompleterBlock} +`, name, nameForVar, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, activeHelpEnvVar(name))) +} + +func (c *Command) genPowerShellCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genPowerShellComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func (c *Command) genPowerShellCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.genPowerShellCompletion(outFile, includeDesc) +} + +// GenPowerShellCompletionFile generates powershell completion file without descriptions. +func (c *Command) GenPowerShellCompletionFile(filename string) error { + return c.genPowerShellCompletionFile(filename, false) +} + +// GenPowerShellCompletion generates powershell completion file without descriptions +// and writes it to the passed writer. +func (c *Command) GenPowerShellCompletion(w io.Writer) error { + return c.genPowerShellCompletion(w, false) +} + +// GenPowerShellCompletionFileWithDesc generates powershell completion file with descriptions. +func (c *Command) GenPowerShellCompletionFileWithDesc(filename string) error { + return c.genPowerShellCompletionFile(filename, true) +} + +// GenPowerShellCompletionWithDesc generates powershell completion file with descriptions +// and writes it to the passed writer. +func (c *Command) GenPowerShellCompletionWithDesc(w io.Writer) error { + return c.genPowerShellCompletion(w, true) +} diff --git a/vendor/github.com/spf13/cobra/shell_completions.go b/vendor/github.com/spf13/cobra/shell_completions.go new file mode 100644 index 0000000..b035742 --- /dev/null +++ b/vendor/github.com/spf13/cobra/shell_completions.go @@ -0,0 +1,98 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "github.com/spf13/pflag" +) + +// MarkFlagRequired instructs the various shell completion implementations to +// prioritize the named flag when performing completion, +// and causes your command to report an error if invoked without the flag. +func (c *Command) MarkFlagRequired(name string) error { + return MarkFlagRequired(c.Flags(), name) +} + +// MarkPersistentFlagRequired instructs the various shell completion implementations to +// prioritize the named persistent flag when performing completion, +// and causes your command to report an error if invoked without the flag. +func (c *Command) MarkPersistentFlagRequired(name string) error { + return MarkFlagRequired(c.PersistentFlags(), name) +} + +// MarkFlagRequired instructs the various shell completion implementations to +// prioritize the named flag when performing completion, +// and causes your command to report an error if invoked without the flag. +func MarkFlagRequired(flags *pflag.FlagSet, name string) error { + return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"}) +} + +// MarkFlagFilename instructs the various shell completion implementations to +// limit completions for the named flag to the specified file extensions. +func (c *Command) MarkFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(c.Flags(), name, extensions...) +} + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. +// The bash completion script will call the bash function f for the flag. +// +// This will only work for bash completion. +// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows +// to register a Go function which will work across all shells. +func (c *Command) MarkFlagCustom(name string, f string) error { + return MarkFlagCustom(c.Flags(), name, f) +} + +// MarkPersistentFlagFilename instructs the various shell completion +// implementations to limit completions for the named persistent flag to the +// specified file extensions. +func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error { + return MarkFlagFilename(c.PersistentFlags(), name, extensions...) +} + +// MarkFlagFilename instructs the various shell completion implementations to +// limit completions for the named flag to the specified file extensions. +func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error { + return flags.SetAnnotation(name, BashCompFilenameExt, extensions) +} + +// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists. +// The bash completion script will call the bash function f for the flag. +// +// This will only work for bash completion. +// It is recommended to instead use c.RegisterFlagCompletionFunc(...) which allows +// to register a Go function which will work across all shells. +func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error { + return flags.SetAnnotation(name, BashCompCustom, []string{f}) +} + +// MarkFlagDirname instructs the various shell completion implementations to +// limit completions for the named flag to directory names. +func (c *Command) MarkFlagDirname(name string) error { + return MarkFlagDirname(c.Flags(), name) +} + +// MarkPersistentFlagDirname instructs the various shell completion +// implementations to limit completions for the named persistent flag to +// directory names. +func (c *Command) MarkPersistentFlagDirname(name string) error { + return MarkFlagDirname(c.PersistentFlags(), name) +} + +// MarkFlagDirname instructs the various shell completion implementations to +// limit completions for the named flag to directory names. +func MarkFlagDirname(flags *pflag.FlagSet, name string) error { + return flags.SetAnnotation(name, BashCompSubdirsInDir, []string{}) +} diff --git a/vendor/github.com/spf13/cobra/zsh_completions.go b/vendor/github.com/spf13/cobra/zsh_completions.go new file mode 100644 index 0000000..1856e4c --- /dev/null +++ b/vendor/github.com/spf13/cobra/zsh_completions.go @@ -0,0 +1,308 @@ +// Copyright 2013-2023 The Cobra Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cobra + +import ( + "bytes" + "fmt" + "io" + "os" +) + +// GenZshCompletionFile generates zsh completion file including descriptions. +func (c *Command) GenZshCompletionFile(filename string) error { + return c.genZshCompletionFile(filename, true) +} + +// GenZshCompletion generates zsh completion file including descriptions +// and writes it to the passed writer. +func (c *Command) GenZshCompletion(w io.Writer) error { + return c.genZshCompletion(w, true) +} + +// GenZshCompletionFileNoDesc generates zsh completion file without descriptions. +func (c *Command) GenZshCompletionFileNoDesc(filename string) error { + return c.genZshCompletionFile(filename, false) +} + +// GenZshCompletionNoDesc generates zsh completion file without descriptions +// and writes it to the passed writer. +func (c *Command) GenZshCompletionNoDesc(w io.Writer) error { + return c.genZshCompletion(w, false) +} + +// MarkZshCompPositionalArgumentFile only worked for zsh and its behavior was +// not consistent with Bash completion. It has therefore been disabled. +// Instead, when no other completion is specified, file completion is done by +// default for every argument. One can disable file completion on a per-argument +// basis by using ValidArgsFunction and ShellCompDirectiveNoFileComp. +// To achieve file extension filtering, one can use ValidArgsFunction and +// ShellCompDirectiveFilterFileExt. +// +// Deprecated +func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error { + return nil +} + +// MarkZshCompPositionalArgumentWords only worked for zsh. It has therefore +// been disabled. +// To achieve the same behavior across all shells, one can use +// ValidArgs (for the first argument only) or ValidArgsFunction for +// any argument (can include the first one also). +// +// Deprecated +func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error { + return nil +} + +func (c *Command) genZshCompletionFile(filename string, includeDesc bool) error { + outFile, err := os.Create(filename) + if err != nil { + return err + } + defer outFile.Close() + + return c.genZshCompletion(outFile, includeDesc) +} + +func (c *Command) genZshCompletion(w io.Writer, includeDesc bool) error { + buf := new(bytes.Buffer) + genZshComp(buf, c.Name(), includeDesc) + _, err := buf.WriteTo(w) + return err +} + +func genZshComp(buf io.StringWriter, name string, includeDesc bool) { + compCmd := ShellCompRequestCmd + if !includeDesc { + compCmd = ShellCompNoDescRequestCmd + } + WriteStringAndCheck(buf, fmt.Sprintf(`#compdef %[1]s +compdef _%[1]s %[1]s + +# zsh completion for %-36[1]s -*- shell-script -*- + +__%[1]s_debug() +{ + local file="$BASH_COMP_DEBUG_FILE" + if [[ -n ${file} ]]; then + echo "$*" >> "${file}" + fi +} + +_%[1]s() +{ + local shellCompDirectiveError=%[3]d + local shellCompDirectiveNoSpace=%[4]d + local shellCompDirectiveNoFileComp=%[5]d + local shellCompDirectiveFilterFileExt=%[6]d + local shellCompDirectiveFilterDirs=%[7]d + local shellCompDirectiveKeepOrder=%[8]d + + local lastParam lastChar flagPrefix requestComp out directive comp lastComp noSpace keepOrder + local -a completions + + __%[1]s_debug "\n========= starting completion logic ==========" + __%[1]s_debug "CURRENT: ${CURRENT}, words[*]: ${words[*]}" + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need + # to truncate the command-line ($words) up to the $CURRENT location. + # (We cannot use $CURSOR as its value does not work when a command is an alias.) + words=("${=words[1,CURRENT]}") + __%[1]s_debug "Truncated words[*]: ${words[*]}," + + lastParam=${words[-1]} + lastChar=${lastParam[-1]} + __%[1]s_debug "lastParam: ${lastParam}, lastChar: ${lastChar}" + + # For zsh, when completing a flag with an = (e.g., %[1]s -n=) + # completions must be prefixed with the flag + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = + flagPrefix="-P ${BASH_REMATCH}" + fi + + # Prepare the command to obtain completions + requestComp="${words[1]} %[2]s ${words[2,-1]}" + if [ "${lastChar}" = "" ]; then + # If the last parameter is complete (there is a space following it) + # We add an extra empty parameter so we can indicate this to the go completion code. + __%[1]s_debug "Adding extra empty parameter" + requestComp="${requestComp} \"\"" + fi + + __%[1]s_debug "About to call: eval ${requestComp}" + + # Use eval to handle any environment variables and such + out=$(eval ${requestComp} 2>/dev/null) + __%[1]s_debug "completion output: ${out}" + + # Extract the directive integer following a : from the last line + local lastLine + while IFS='\n' read -r line; do + lastLine=${line} + done < <(printf "%%s\n" "${out[@]}") + __%[1]s_debug "last line: ${lastLine}" + + if [ "${lastLine[1]}" = : ]; then + directive=${lastLine[2,-1]} + # Remove the directive including the : and the newline + local suffix + (( suffix=${#lastLine}+2)) + out=${out[1,-$suffix]} + else + # There is no directive specified. Leave $out as is. + __%[1]s_debug "No directive found. Setting do default" + directive=0 + fi + + __%[1]s_debug "directive: ${directive}" + __%[1]s_debug "completions: ${out}" + __%[1]s_debug "flagPrefix: ${flagPrefix}" + + if [ $((directive & shellCompDirectiveError)) -ne 0 ]; then + __%[1]s_debug "Completion received error. Ignoring completions." + return + fi + + local activeHelpMarker="%[9]s" + local endIndex=${#activeHelpMarker} + local startIndex=$((${#activeHelpMarker}+1)) + local hasActiveHelp=0 + while IFS='\n' read -r comp; do + # Check if this is an activeHelp statement (i.e., prefixed with $activeHelpMarker) + if [ "${comp[1,$endIndex]}" = "$activeHelpMarker" ];then + __%[1]s_debug "ActiveHelp found: $comp" + comp="${comp[$startIndex,-1]}" + if [ -n "$comp" ]; then + compadd -x "${comp}" + __%[1]s_debug "ActiveHelp will need delimiter" + hasActiveHelp=1 + fi + + continue + fi + + if [ -n "$comp" ]; then + # If requested, completions are returned with a description. + # The description is preceded by a TAB character. + # For zsh's _describe, we need to use a : instead of a TAB. + # We first need to escape any : as part of the completion itself. + comp=${comp//:/\\:} + + local tab="$(printf '\t')" + comp=${comp//$tab/:} + + __%[1]s_debug "Adding completion: ${comp}" + completions+=${comp} + lastComp=$comp + fi + done < <(printf "%%s\n" "${out[@]}") + + # Add a delimiter after the activeHelp statements, but only if: + # - there are completions following the activeHelp statements, or + # - file completion will be performed (so there will be choices after the activeHelp) + if [ $hasActiveHelp -eq 1 ]; then + if [ ${#completions} -ne 0 ] || [ $((directive & shellCompDirectiveNoFileComp)) -eq 0 ]; then + __%[1]s_debug "Adding activeHelp delimiter" + compadd -x "--" + hasActiveHelp=0 + fi + fi + + if [ $((directive & shellCompDirectiveNoSpace)) -ne 0 ]; then + __%[1]s_debug "Activating nospace." + noSpace="-S ''" + fi + + if [ $((directive & shellCompDirectiveKeepOrder)) -ne 0 ]; then + __%[1]s_debug "Activating keep order." + keepOrder="-V" + fi + + if [ $((directive & shellCompDirectiveFilterFileExt)) -ne 0 ]; then + # File extension filtering + local filteringCmd + filteringCmd='_files' + for filter in ${completions[@]}; do + if [ ${filter[1]} != '*' ]; then + # zsh requires a glob pattern to do file filtering + filter="\*.$filter" + fi + filteringCmd+=" -g $filter" + done + filteringCmd+=" ${flagPrefix}" + + __%[1]s_debug "File filtering command: $filteringCmd" + _arguments '*:filename:'"$filteringCmd" + elif [ $((directive & shellCompDirectiveFilterDirs)) -ne 0 ]; then + # File completion for directories only + local subdir + subdir="${completions[1]}" + if [ -n "$subdir" ]; then + __%[1]s_debug "Listing directories in $subdir" + pushd "${subdir}" >/dev/null 2>&1 + else + __%[1]s_debug "Listing directories in ." + fi + + local result + _arguments '*:dirname:_files -/'" ${flagPrefix}" + result=$? + if [ -n "$subdir" ]; then + popd >/dev/null 2>&1 + fi + return $result + else + __%[1]s_debug "Calling _describe" + if eval _describe $keepOrder "completions" completions $flagPrefix $noSpace; then + __%[1]s_debug "_describe found some completions" + + # Return the success of having called _describe + return 0 + else + __%[1]s_debug "_describe did not find completions." + __%[1]s_debug "Checking if we should do file completion." + if [ $((directive & shellCompDirectiveNoFileComp)) -ne 0 ]; then + __%[1]s_debug "deactivating file completion" + + # We must return an error code here to let zsh know that there were no + # completions found by _describe; this is what will trigger other + # matching algorithms to attempt to find completions. + # For example zsh can match letters in the middle of words. + return 1 + else + # Perform file completion + __%[1]s_debug "Activating file completion" + + # We must return the result of this command, so it must be the + # last command, or else we must store its result to return it. + _arguments '*:filename:_files'" ${flagPrefix}" + fi + fi + fi +} + +# don't run the completion function when being source-ed or eval-ed +if [ "$funcstack[1]" = "_%[1]s" ]; then + _%[1]s +fi +`, name, compCmd, + ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp, + ShellCompDirectiveFilterFileExt, ShellCompDirectiveFilterDirs, ShellCompDirectiveKeepOrder, + activeHelpMarker)) +} diff --git a/vendor/github.com/spf13/pflag/.editorconfig b/vendor/github.com/spf13/pflag/.editorconfig new file mode 100644 index 0000000..4492e9f --- /dev/null +++ b/vendor/github.com/spf13/pflag/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.go] +indent_style = tab diff --git a/vendor/github.com/spf13/pflag/.gitignore b/vendor/github.com/spf13/pflag/.gitignore new file mode 100644 index 0000000..c3da290 --- /dev/null +++ b/vendor/github.com/spf13/pflag/.gitignore @@ -0,0 +1,2 @@ +.idea/* + diff --git a/vendor/github.com/spf13/pflag/.golangci.yaml b/vendor/github.com/spf13/pflag/.golangci.yaml new file mode 100644 index 0000000..b274f24 --- /dev/null +++ b/vendor/github.com/spf13/pflag/.golangci.yaml @@ -0,0 +1,4 @@ +linters: + disable-all: true + enable: + - nolintlint diff --git a/vendor/github.com/spf13/pflag/.travis.yml b/vendor/github.com/spf13/pflag/.travis.yml new file mode 100644 index 0000000..00d04cb --- /dev/null +++ b/vendor/github.com/spf13/pflag/.travis.yml @@ -0,0 +1,22 @@ +sudo: false + +language: go + +go: + - 1.9.x + - 1.10.x + - 1.11.x + - tip + +matrix: + allow_failures: + - go: tip + +install: + - go get golang.org/x/lint/golint + - export PATH=$GOPATH/bin:$PATH + - go install ./... + +script: + - verify/all.sh -v + - go test ./... diff --git a/vendor/github.com/spf13/pflag/LICENSE b/vendor/github.com/spf13/pflag/LICENSE new file mode 100644 index 0000000..63ed1cf --- /dev/null +++ b/vendor/github.com/spf13/pflag/LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2012 Alex Ogier. All rights reserved. +Copyright (c) 2012 The Go Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/spf13/pflag/README.md b/vendor/github.com/spf13/pflag/README.md new file mode 100644 index 0000000..388c4e5 --- /dev/null +++ b/vendor/github.com/spf13/pflag/README.md @@ -0,0 +1,323 @@ +[![Build Status](https://travis-ci.org/spf13/pflag.svg?branch=master)](https://travis-ci.org/spf13/pflag) +[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/pflag)](https://goreportcard.com/report/github.com/spf13/pflag) +[![GoDoc](https://godoc.org/github.com/spf13/pflag?status.svg)](https://godoc.org/github.com/spf13/pflag) + +## Description + +pflag is a drop-in replacement for Go's flag package, implementing +POSIX/GNU-style --flags. + +pflag is compatible with the [GNU extensions to the POSIX recommendations +for command-line options][1]. For a more precise description, see the +"Command-line flag syntax" section below. + +[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + +pflag is available under the same style of BSD license as the Go language, +which can be found in the LICENSE file. + +## Installation + +pflag is available using the standard `go get` command. + +Install by running: + + go get github.com/spf13/pflag + +Run tests by running: + + go test github.com/spf13/pflag + +## Usage + +pflag is a drop-in replacement of Go's native flag package. If you import +pflag under the name "flag" then all code should continue to function +with no changes. + +``` go +import flag "github.com/spf13/pflag" +``` + +There is one exception to this: if you directly instantiate the Flag struct +there is one more field "Shorthand" that you will need to set. +Most code never instantiates this struct directly, and instead uses +functions such as String(), BoolVar(), and Var(), and is therefore +unaffected. + +Define flags using flag.String(), Bool(), Int(), etc. + +This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + +``` go +var ip *int = flag.Int("flagname", 1234, "help message for flagname") +``` + +If you like, you can bind the flag to a variable using the Var() functions. + +``` go +var flagvar int +func init() { + flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") +} +``` + +Or you can create custom flags that satisfy the Value interface (with +pointer receivers) and couple them to flag parsing by + +``` go +flag.Var(&flagVal, "name", "help message for flagname") +``` + +For such flags, the default value is just the initial value of the variable. + +After all flags are defined, call + +``` go +flag.Parse() +``` + +to parse the command line into the defined flags. + +Flags may then be used directly. If you're using the flags themselves, +they are all pointers; if you bind to variables, they're values. + +``` go +fmt.Println("ip has value ", *ip) +fmt.Println("flagvar has value ", flagvar) +``` + +There are helper functions available to get the value stored in a Flag if you have a FlagSet but find +it difficult to keep up with all of the pointers in your code. +If you have a pflag.FlagSet with a flag called 'flagname' of type int you +can use GetInt() to get the int value. But notice that 'flagname' must exist +and it must be an int. GetString("flagname") will fail. + +``` go +i, err := flagset.GetInt("flagname") +``` + +After parsing, the arguments after the flag are available as the +slice flag.Args() or individually as flag.Arg(i). +The arguments are indexed from 0 through flag.NArg()-1. + +The pflag package also defines some new functions that are not in flag, +that give one-letter shorthands for flags. You can use these by appending +'P' to the name of any function that defines a flag. + +``` go +var ip = flag.IntP("flagname", "f", 1234, "help message") +var flagvar bool +func init() { + flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") +} +flag.VarP(&flagVal, "varname", "v", "help message") +``` + +Shorthand letters can be used with single dashes on the command line. +Boolean shorthand flags can be combined with other shorthand flags. + +The default set of command-line flags is controlled by +top-level functions. The FlagSet type allows one to define +independent sets of flags, such as to implement subcommands +in a command-line interface. The methods of FlagSet are +analogous to the top-level functions for the command-line +flag set. + +## Setting no option default values for flags + +After you create a flag it is possible to set the pflag.NoOptDefVal for +the given flag. Doing this changes the meaning of the flag slightly. If +a flag has a NoOptDefVal and the flag is set on the command line without +an option the flag will be set to the NoOptDefVal. For example given: + +``` go +var ip = flag.IntP("flagname", "f", 1234, "help message") +flag.Lookup("flagname").NoOptDefVal = "4321" +``` + +Would result in something like + +| Parsed Arguments | Resulting Value | +| ------------- | ------------- | +| --flagname=1357 | ip=1357 | +| --flagname | ip=4321 | +| [nothing] | ip=1234 | + +## Command line flag syntax + +``` +--flag // boolean flags, or flags with no option default values +--flag x // only on flags without a default value +--flag=x +``` + +Unlike the flag package, a single dash before an option means something +different than a double dash. Single dashes signify a series of shorthand +letters for flags. All but the last shorthand letter must be boolean flags +or a flag with a default value + +``` +// boolean or flags where the 'no option default value' is set +-f +-f=true +-abc +but +-b true is INVALID + +// non-boolean and flags without a 'no option default value' +-n 1234 +-n=1234 +-n1234 + +// mixed +-abcs "hello" +-absd="hello" +-abcs1234 +``` + +Flag parsing stops after the terminator "--". Unlike the flag package, +flags can be interspersed with arguments anywhere on the command line +before this terminator. + +Integer flags accept 1234, 0664, 0x1234 and may be negative. +Boolean flags (in their long form) accept 1, 0, t, f, true, false, +TRUE, FALSE, True, False. +Duration flags accept any input valid for time.ParseDuration. + +## Mutating or "Normalizing" Flag names + +It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow. + +**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag + +``` go +func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { + from := []string{"-", "_"} + to := "." + for _, sep := range from { + name = strings.Replace(name, sep, to, -1) + } + return pflag.NormalizedName(name) +} + +myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc) +``` + +**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name + +``` go +func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName { + switch name { + case "old-flag-name": + name = "new-flag-name" + break + } + return pflag.NormalizedName(name) +} + +myFlagSet.SetNormalizeFunc(aliasNormalizeFunc) +``` + +## Deprecating a flag or its shorthand +It is possible to deprecate a flag, or just its shorthand. Deprecating a flag/shorthand hides it from help text and prints a usage message when the deprecated flag/shorthand is used. + +**Example #1**: You want to deprecate a flag named "badflag" as well as inform the users what flag they should use instead. +```go +// deprecate a flag by specifying its name and a usage message +flags.MarkDeprecated("badflag", "please use --good-flag instead") +``` +This hides "badflag" from help text, and prints `Flag --badflag has been deprecated, please use --good-flag instead` when "badflag" is used. + +**Example #2**: You want to keep a flag name "noshorthandflag" but deprecate its shortname "n". +```go +// deprecate a flag shorthand by specifying its flag name and a usage message +flags.MarkShorthandDeprecated("noshorthandflag", "please use --noshorthandflag only") +``` +This hides the shortname "n" from help text, and prints `Flag shorthand -n has been deprecated, please use --noshorthandflag only` when the shorthand "n" is used. + +Note that usage message is essential here, and it should not be empty. + +## Hidden flags +It is possible to mark a flag as hidden, meaning it will still function as normal, however will not show up in usage/help text. + +**Example**: You have a flag named "secretFlag" that you need for internal use only and don't want it showing up in help text, or for its usage text to be available. +```go +// hide a flag by specifying its name +flags.MarkHidden("secretFlag") +``` + +## Disable sorting of flags +`pflag` allows you to disable sorting of flags for help and usage message. + +**Example**: +```go +flags.BoolP("verbose", "v", false, "verbose output") +flags.String("coolflag", "yeaah", "it's really cool flag") +flags.Int("usefulflag", 777, "sometimes it's very useful") +flags.SortFlags = false +flags.PrintDefaults() +``` +**Output**: +``` + -v, --verbose verbose output + --coolflag string it's really cool flag (default "yeaah") + --usefulflag int sometimes it's very useful (default 777) +``` + + +## Supporting Go flags when using pflag +In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary +to support flags defined by third-party dependencies (e.g. `golang/glog`). + +**Example**: You want to add the Go flags to the `CommandLine` flagset +```go +import ( + goflag "flag" + flag "github.com/spf13/pflag" +) + +var ip *int = flag.Int("flagname", 1234, "help message for flagname") + +func main() { + flag.CommandLine.AddGoFlagSet(goflag.CommandLine) + flag.Parse() +} +``` + +### Using pflag with go test +`pflag` does not parse the shorthand versions of go test's built-in flags (i.e., those starting with `-test.`). +For more context, see issues [#63](https://github.com/spf13/pflag/issues/63) and [#238](https://github.com/spf13/pflag/issues/238) for more details. + +For example, if you use pflag in your `TestMain` function and call `pflag.Parse()` after defining your custom flags, running a test like this: +```bash +go test /your/tests -run ^YourTest -v --your-test-pflags +``` +will result in the `-v` flag being ignored. This happens because of the way pflag handles flag parsing, skipping over go test's built-in shorthand flags. +To work around this, you can use the `ParseSkippedFlags` function, which ensures that go test's flags are parsed separately using the standard flag package. + +**Example**: You want to parse go test flags that are otherwise ignore by `pflag.Parse()` +```go +import ( + goflag "flag" + flag "github.com/spf13/pflag" +) + +var ip *int = flag.Int("flagname", 1234, "help message for flagname") + +func main() { + flag.CommandLine.AddGoFlagSet(goflag.CommandLine) + flag.ParseSkippedFlags(os.Args[1:], goflag.CommandLine) + flag.Parse() +} +``` + +## More info + +You can see the full reference documentation of the pflag package +[at godoc.org][3], or through go's standard documentation system by +running `godoc -http=:6060` and browsing to +[http://localhost:6060/pkg/github.com/spf13/pflag][2] after +installation. + +[2]: http://localhost:6060/pkg/github.com/spf13/pflag +[3]: http://godoc.org/github.com/spf13/pflag diff --git a/vendor/github.com/spf13/pflag/bool.go b/vendor/github.com/spf13/pflag/bool.go new file mode 100644 index 0000000..c4c5c0b --- /dev/null +++ b/vendor/github.com/spf13/pflag/bool.go @@ -0,0 +1,94 @@ +package pflag + +import "strconv" + +// optional interface to indicate boolean flags that can be +// supplied without "=value" text +type boolFlag interface { + Value + IsBoolFlag() bool +} + +// -- bool Value +type boolValue bool + +func newBoolValue(val bool, p *bool) *boolValue { + *p = val + return (*boolValue)(p) +} + +func (b *boolValue) Set(s string) error { + v, err := strconv.ParseBool(s) + *b = boolValue(v) + return err +} + +func (b *boolValue) Type() string { + return "bool" +} + +func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) } + +func (b *boolValue) IsBoolFlag() bool { return true } + +func boolConv(sval string) (interface{}, error) { + return strconv.ParseBool(sval) +} + +// GetBool return the bool value of a flag with the given name +func (f *FlagSet) GetBool(name string) (bool, error) { + val, err := f.getFlagType(name, "bool", boolConv) + if err != nil { + return false, err + } + return val.(bool), nil +} + +// BoolVar defines a bool flag with specified name, default value, and usage string. +// The argument p points to a bool variable in which to store the value of the flag. +func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) { + f.BoolVarP(p, name, "", value, usage) +} + +// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) { + flag := f.VarPF(newBoolValue(value, p), name, shorthand, usage) + flag.NoOptDefVal = "true" +} + +// BoolVar defines a bool flag with specified name, default value, and usage string. +// The argument p points to a bool variable in which to store the value of the flag. +func BoolVar(p *bool, name string, value bool, usage string) { + BoolVarP(p, name, "", value, usage) +} + +// BoolVarP is like BoolVar, but accepts a shorthand letter that can be used after a single dash. +func BoolVarP(p *bool, name, shorthand string, value bool, usage string) { + flag := CommandLine.VarPF(newBoolValue(value, p), name, shorthand, usage) + flag.NoOptDefVal = "true" +} + +// Bool defines a bool flag with specified name, default value, and usage string. +// The return value is the address of a bool variable that stores the value of the flag. +func (f *FlagSet) Bool(name string, value bool, usage string) *bool { + return f.BoolP(name, "", value, usage) +} + +// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool { + p := new(bool) + f.BoolVarP(p, name, shorthand, value, usage) + return p +} + +// Bool defines a bool flag with specified name, default value, and usage string. +// The return value is the address of a bool variable that stores the value of the flag. +func Bool(name string, value bool, usage string) *bool { + return BoolP(name, "", value, usage) +} + +// BoolP is like Bool, but accepts a shorthand letter that can be used after a single dash. +func BoolP(name, shorthand string, value bool, usage string) *bool { + b := CommandLine.BoolP(name, shorthand, value, usage) + return b +} diff --git a/vendor/github.com/spf13/pflag/bool_func.go b/vendor/github.com/spf13/pflag/bool_func.go new file mode 100644 index 0000000..83d77af --- /dev/null +++ b/vendor/github.com/spf13/pflag/bool_func.go @@ -0,0 +1,40 @@ +package pflag + +// -- func Value +type boolfuncValue func(string) error + +func (f boolfuncValue) Set(s string) error { return f(s) } + +func (f boolfuncValue) Type() string { return "boolfunc" } + +func (f boolfuncValue) String() string { return "" } // same behavior as stdlib 'flag' package + +func (f boolfuncValue) IsBoolFlag() bool { return true } + +// BoolFunc defines a func flag with specified name, callback function and usage string. +// +// The callback function will be called every time "--{name}" (or any form that matches the flag) is parsed +// on the command line. +func (f *FlagSet) BoolFunc(name string, usage string, fn func(string) error) { + f.BoolFuncP(name, "", usage, fn) +} + +// BoolFuncP is like BoolFunc, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolFuncP(name, shorthand string, usage string, fn func(string) error) { + var val Value = boolfuncValue(fn) + flag := f.VarPF(val, name, shorthand, usage) + flag.NoOptDefVal = "true" +} + +// BoolFunc defines a func flag with specified name, callback function and usage string. +// +// The callback function will be called every time "--{name}" (or any form that matches the flag) is parsed +// on the command line. +func BoolFunc(name string, usage string, fn func(string) error) { + CommandLine.BoolFuncP(name, "", usage, fn) +} + +// BoolFuncP is like BoolFunc, but accepts a shorthand letter that can be used after a single dash. +func BoolFuncP(name, shorthand string, usage string, fn func(string) error) { + CommandLine.BoolFuncP(name, shorthand, usage, fn) +} diff --git a/vendor/github.com/spf13/pflag/bool_slice.go b/vendor/github.com/spf13/pflag/bool_slice.go new file mode 100644 index 0000000..3731370 --- /dev/null +++ b/vendor/github.com/spf13/pflag/bool_slice.go @@ -0,0 +1,185 @@ +package pflag + +import ( + "io" + "strconv" + "strings" +) + +// -- boolSlice Value +type boolSliceValue struct { + value *[]bool + changed bool +} + +func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue { + bsv := new(boolSliceValue) + bsv.value = p + *bsv.value = val + return bsv +} + +// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag. +// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended. +func (s *boolSliceValue) Set(val string) error { + + // remove all quote characters + rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") + + // read flag arguments with CSV parser + boolStrSlice, err := readAsCSV(rmQuote.Replace(val)) + if err != nil && err != io.EOF { + return err + } + + // parse boolean values into slice + out := make([]bool, 0, len(boolStrSlice)) + for _, boolStr := range boolStrSlice { + b, err := strconv.ParseBool(strings.TrimSpace(boolStr)) + if err != nil { + return err + } + out = append(out, b) + } + + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + + s.changed = true + + return nil +} + +// Type returns a string that uniquely represents this flag's type. +func (s *boolSliceValue) Type() string { + return "boolSlice" +} + +// String defines a "native" format for this boolean slice flag value. +func (s *boolSliceValue) String() string { + + boolStrSlice := make([]string, len(*s.value)) + for i, b := range *s.value { + boolStrSlice[i] = strconv.FormatBool(b) + } + + out, _ := writeAsCSV(boolStrSlice) + + return "[" + out + "]" +} + +func (s *boolSliceValue) fromString(val string) (bool, error) { + return strconv.ParseBool(val) +} + +func (s *boolSliceValue) toString(val bool) string { + return strconv.FormatBool(val) +} + +func (s *boolSliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *boolSliceValue) Replace(val []string) error { + out := make([]bool, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *boolSliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func boolSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []bool{}, nil + } + ss := strings.Split(val, ",") + out := make([]bool, len(ss)) + for i, t := range ss { + var err error + out[i], err = strconv.ParseBool(t) + if err != nil { + return nil, err + } + } + return out, nil +} + +// GetBoolSlice returns the []bool value of a flag with the given name. +func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) { + val, err := f.getFlagType(name, "boolSlice", boolSliceConv) + if err != nil { + return []bool{}, err + } + return val.([]bool), nil +} + +// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string. +// The argument p points to a []bool variable in which to store the value of the flag. +func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) { + f.VarP(newBoolSliceValue(value, p), name, "", usage) +} + +// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { + f.VarP(newBoolSliceValue(value, p), name, shorthand, usage) +} + +// BoolSliceVar defines a []bool flag with specified name, default value, and usage string. +// The argument p points to a []bool variable in which to store the value of the flag. +func BoolSliceVar(p *[]bool, name string, value []bool, usage string) { + CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage) +} + +// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash. +func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) { + CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage) +} + +// BoolSlice defines a []bool flag with specified name, default value, and usage string. +// The return value is the address of a []bool variable that stores the value of the flag. +func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool { + p := []bool{} + f.BoolSliceVarP(&p, name, "", value, usage) + return &p +} + +// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { + p := []bool{} + f.BoolSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// BoolSlice defines a []bool flag with specified name, default value, and usage string. +// The return value is the address of a []bool variable that stores the value of the flag. +func BoolSlice(name string, value []bool, usage string) *[]bool { + return CommandLine.BoolSliceP(name, "", value, usage) +} + +// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash. +func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool { + return CommandLine.BoolSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go new file mode 100644 index 0000000..67d5304 --- /dev/null +++ b/vendor/github.com/spf13/pflag/bytes.go @@ -0,0 +1,209 @@ +package pflag + +import ( + "encoding/base64" + "encoding/hex" + "fmt" + "strings" +) + +// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded +type bytesHexValue []byte + +// String implements pflag.Value.String. +func (bytesHex bytesHexValue) String() string { + return fmt.Sprintf("%X", []byte(bytesHex)) +} + +// Set implements pflag.Value.Set. +func (bytesHex *bytesHexValue) Set(value string) error { + bin, err := hex.DecodeString(strings.TrimSpace(value)) + + if err != nil { + return err + } + + *bytesHex = bin + + return nil +} + +// Type implements pflag.Value.Type. +func (*bytesHexValue) Type() string { + return "bytesHex" +} + +func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue { + *p = val + return (*bytesHexValue)(p) +} + +func bytesHexConv(sval string) (interface{}, error) { + + bin, err := hex.DecodeString(sval) + + if err == nil { + return bin, nil + } + + return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) +} + +// GetBytesHex return the []byte value of a flag with the given name +func (f *FlagSet) GetBytesHex(name string) ([]byte, error) { + val, err := f.getFlagType(name, "bytesHex", bytesHexConv) + + if err != nil { + return []byte{}, err + } + + return val.([]byte), nil +} + +// BytesHexVar defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) { + f.VarP(newBytesHexValue(value, p), name, "", usage) +} + +// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { + f.VarP(newBytesHexValue(value, p), name, shorthand, usage) +} + +// BytesHexVar defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func BytesHexVar(p *[]byte, name string, value []byte, usage string) { + CommandLine.VarP(newBytesHexValue(value, p), name, "", usage) +} + +// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash. +func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) { + CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage) +} + +// BytesHex defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesHexVarP(p, name, "", value, usage) + return p +} + +// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesHexVarP(p, name, shorthand, value, usage) + return p +} + +// BytesHex defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func BytesHex(name string, value []byte, usage string) *[]byte { + return CommandLine.BytesHexP(name, "", value, usage) +} + +// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash. +func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte { + return CommandLine.BytesHexP(name, shorthand, value, usage) +} + +// BytesBase64 adapts []byte for use as a flag. Value of flag is Base64 encoded +type bytesBase64Value []byte + +// String implements pflag.Value.String. +func (bytesBase64 bytesBase64Value) String() string { + return base64.StdEncoding.EncodeToString([]byte(bytesBase64)) +} + +// Set implements pflag.Value.Set. +func (bytesBase64 *bytesBase64Value) Set(value string) error { + bin, err := base64.StdEncoding.DecodeString(strings.TrimSpace(value)) + + if err != nil { + return err + } + + *bytesBase64 = bin + + return nil +} + +// Type implements pflag.Value.Type. +func (*bytesBase64Value) Type() string { + return "bytesBase64" +} + +func newBytesBase64Value(val []byte, p *[]byte) *bytesBase64Value { + *p = val + return (*bytesBase64Value)(p) +} + +func bytesBase64ValueConv(sval string) (interface{}, error) { + + bin, err := base64.StdEncoding.DecodeString(sval) + if err == nil { + return bin, nil + } + + return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err) +} + +// GetBytesBase64 return the []byte value of a flag with the given name +func (f *FlagSet) GetBytesBase64(name string) ([]byte, error) { + val, err := f.getFlagType(name, "bytesBase64", bytesBase64ValueConv) + + if err != nil { + return []byte{}, err + } + + return val.([]byte), nil +} + +// BytesBase64Var defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func (f *FlagSet) BytesBase64Var(p *[]byte, name string, value []byte, usage string) { + f.VarP(newBytesBase64Value(value, p), name, "", usage) +} + +// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) { + f.VarP(newBytesBase64Value(value, p), name, shorthand, usage) +} + +// BytesBase64Var defines an []byte flag with specified name, default value, and usage string. +// The argument p points to an []byte variable in which to store the value of the flag. +func BytesBase64Var(p *[]byte, name string, value []byte, usage string) { + CommandLine.VarP(newBytesBase64Value(value, p), name, "", usage) +} + +// BytesBase64VarP is like BytesBase64Var, but accepts a shorthand letter that can be used after a single dash. +func BytesBase64VarP(p *[]byte, name, shorthand string, value []byte, usage string) { + CommandLine.VarP(newBytesBase64Value(value, p), name, shorthand, usage) +} + +// BytesBase64 defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func (f *FlagSet) BytesBase64(name string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesBase64VarP(p, name, "", value, usage) + return p +} + +// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte { + p := new([]byte) + f.BytesBase64VarP(p, name, shorthand, value, usage) + return p +} + +// BytesBase64 defines an []byte flag with specified name, default value, and usage string. +// The return value is the address of an []byte variable that stores the value of the flag. +func BytesBase64(name string, value []byte, usage string) *[]byte { + return CommandLine.BytesBase64P(name, "", value, usage) +} + +// BytesBase64P is like BytesBase64, but accepts a shorthand letter that can be used after a single dash. +func BytesBase64P(name, shorthand string, value []byte, usage string) *[]byte { + return CommandLine.BytesBase64P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/count.go b/vendor/github.com/spf13/pflag/count.go new file mode 100644 index 0000000..d49c014 --- /dev/null +++ b/vendor/github.com/spf13/pflag/count.go @@ -0,0 +1,96 @@ +package pflag + +import "strconv" + +// -- count Value +type countValue int + +func newCountValue(val int, p *int) *countValue { + *p = val + return (*countValue)(p) +} + +func (i *countValue) Set(s string) error { + // "+1" means that no specific value was passed, so increment + if s == "+1" { + *i = countValue(*i + 1) + return nil + } + v, err := strconv.ParseInt(s, 0, 0) + *i = countValue(v) + return err +} + +func (i *countValue) Type() string { + return "count" +} + +func (i *countValue) String() string { return strconv.Itoa(int(*i)) } + +func countConv(sval string) (interface{}, error) { + i, err := strconv.Atoi(sval) + if err != nil { + return nil, err + } + return i, nil +} + +// GetCount return the int value of a flag with the given name +func (f *FlagSet) GetCount(name string) (int, error) { + val, err := f.getFlagType(name, "count", countConv) + if err != nil { + return 0, err + } + return val.(int), nil +} + +// CountVar defines a count flag with specified name, default value, and usage string. +// The argument p points to an int variable in which to store the value of the flag. +// A count flag will add 1 to its value every time it is found on the command line +func (f *FlagSet) CountVar(p *int, name string, usage string) { + f.CountVarP(p, name, "", usage) +} + +// CountVarP is like CountVar only take a shorthand for the flag name. +func (f *FlagSet) CountVarP(p *int, name, shorthand string, usage string) { + flag := f.VarPF(newCountValue(0, p), name, shorthand, usage) + flag.NoOptDefVal = "+1" +} + +// CountVar like CountVar only the flag is placed on the CommandLine instead of a given flag set +func CountVar(p *int, name string, usage string) { + CommandLine.CountVar(p, name, usage) +} + +// CountVarP is like CountVar only take a shorthand for the flag name. +func CountVarP(p *int, name, shorthand string, usage string) { + CommandLine.CountVarP(p, name, shorthand, usage) +} + +// Count defines a count flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +// A count flag will add 1 to its value every time it is found on the command line +func (f *FlagSet) Count(name string, usage string) *int { + p := new(int) + f.CountVarP(p, name, "", usage) + return p +} + +// CountP is like Count only takes a shorthand for the flag name. +func (f *FlagSet) CountP(name, shorthand string, usage string) *int { + p := new(int) + f.CountVarP(p, name, shorthand, usage) + return p +} + +// Count defines a count flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +// A count flag will add 1 to its value every time it is found on the command line +func Count(name string, usage string) *int { + return CommandLine.CountP(name, "", usage) +} + +// CountP is like Count only takes a shorthand for the flag name. +func CountP(name, shorthand string, usage string) *int { + return CommandLine.CountP(name, shorthand, usage) +} diff --git a/vendor/github.com/spf13/pflag/duration.go b/vendor/github.com/spf13/pflag/duration.go new file mode 100644 index 0000000..e9debef --- /dev/null +++ b/vendor/github.com/spf13/pflag/duration.go @@ -0,0 +1,86 @@ +package pflag + +import ( + "time" +) + +// -- time.Duration Value +type durationValue time.Duration + +func newDurationValue(val time.Duration, p *time.Duration) *durationValue { + *p = val + return (*durationValue)(p) +} + +func (d *durationValue) Set(s string) error { + v, err := time.ParseDuration(s) + *d = durationValue(v) + return err +} + +func (d *durationValue) Type() string { + return "duration" +} + +func (d *durationValue) String() string { return (*time.Duration)(d).String() } + +func durationConv(sval string) (interface{}, error) { + return time.ParseDuration(sval) +} + +// GetDuration return the duration value of a flag with the given name +func (f *FlagSet) GetDuration(name string) (time.Duration, error) { + val, err := f.getFlagType(name, "duration", durationConv) + if err != nil { + return 0, err + } + return val.(time.Duration), nil +} + +// DurationVar defines a time.Duration flag with specified name, default value, and usage string. +// The argument p points to a time.Duration variable in which to store the value of the flag. +func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) { + f.VarP(newDurationValue(value, p), name, "", usage) +} + +// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { + f.VarP(newDurationValue(value, p), name, shorthand, usage) +} + +// DurationVar defines a time.Duration flag with specified name, default value, and usage string. +// The argument p points to a time.Duration variable in which to store the value of the flag. +func DurationVar(p *time.Duration, name string, value time.Duration, usage string) { + CommandLine.VarP(newDurationValue(value, p), name, "", usage) +} + +// DurationVarP is like DurationVar, but accepts a shorthand letter that can be used after a single dash. +func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) { + CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage) +} + +// Duration defines a time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a time.Duration variable that stores the value of the flag. +func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration { + p := new(time.Duration) + f.DurationVarP(p, name, "", value, usage) + return p +} + +// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { + p := new(time.Duration) + f.DurationVarP(p, name, shorthand, value, usage) + return p +} + +// Duration defines a time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a time.Duration variable that stores the value of the flag. +func Duration(name string, value time.Duration, usage string) *time.Duration { + return CommandLine.DurationP(name, "", value, usage) +} + +// DurationP is like Duration, but accepts a shorthand letter that can be used after a single dash. +func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration { + return CommandLine.DurationP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/duration_slice.go b/vendor/github.com/spf13/pflag/duration_slice.go new file mode 100644 index 0000000..badadda --- /dev/null +++ b/vendor/github.com/spf13/pflag/duration_slice.go @@ -0,0 +1,166 @@ +package pflag + +import ( + "fmt" + "strings" + "time" +) + +// -- durationSlice Value +type durationSliceValue struct { + value *[]time.Duration + changed bool +} + +func newDurationSliceValue(val []time.Duration, p *[]time.Duration) *durationSliceValue { + dsv := new(durationSliceValue) + dsv.value = p + *dsv.value = val + return dsv +} + +func (s *durationSliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]time.Duration, len(ss)) + for i, d := range ss { + var err error + out[i], err = time.ParseDuration(d) + if err != nil { + return err + } + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *durationSliceValue) Type() string { + return "durationSlice" +} + +func (s *durationSliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%s", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *durationSliceValue) fromString(val string) (time.Duration, error) { + return time.ParseDuration(val) +} + +func (s *durationSliceValue) toString(val time.Duration) string { + return fmt.Sprintf("%s", val) +} + +func (s *durationSliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *durationSliceValue) Replace(val []string) error { + out := make([]time.Duration, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *durationSliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func durationSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []time.Duration{}, nil + } + ss := strings.Split(val, ",") + out := make([]time.Duration, len(ss)) + for i, d := range ss { + var err error + out[i], err = time.ParseDuration(d) + if err != nil { + return nil, err + } + + } + return out, nil +} + +// GetDurationSlice returns the []time.Duration value of a flag with the given name +func (f *FlagSet) GetDurationSlice(name string) ([]time.Duration, error) { + val, err := f.getFlagType(name, "durationSlice", durationSliceConv) + if err != nil { + return []time.Duration{}, err + } + return val.([]time.Duration), nil +} + +// DurationSliceVar defines a durationSlice flag with specified name, default value, and usage string. +// The argument p points to a []time.Duration variable in which to store the value of the flag. +func (f *FlagSet) DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { + f.VarP(newDurationSliceValue(value, p), name, "", usage) +} + +// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { + f.VarP(newDurationSliceValue(value, p), name, shorthand, usage) +} + +// DurationSliceVar defines a duration[] flag with specified name, default value, and usage string. +// The argument p points to a duration[] variable in which to store the value of the flag. +func DurationSliceVar(p *[]time.Duration, name string, value []time.Duration, usage string) { + CommandLine.VarP(newDurationSliceValue(value, p), name, "", usage) +} + +// DurationSliceVarP is like DurationSliceVar, but accepts a shorthand letter that can be used after a single dash. +func DurationSliceVarP(p *[]time.Duration, name, shorthand string, value []time.Duration, usage string) { + CommandLine.VarP(newDurationSliceValue(value, p), name, shorthand, usage) +} + +// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a []time.Duration variable that stores the value of the flag. +func (f *FlagSet) DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { + p := []time.Duration{} + f.DurationSliceVarP(&p, name, "", value, usage) + return &p +} + +// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { + p := []time.Duration{} + f.DurationSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// DurationSlice defines a []time.Duration flag with specified name, default value, and usage string. +// The return value is the address of a []time.Duration variable that stores the value of the flag. +func DurationSlice(name string, value []time.Duration, usage string) *[]time.Duration { + return CommandLine.DurationSliceP(name, "", value, usage) +} + +// DurationSliceP is like DurationSlice, but accepts a shorthand letter that can be used after a single dash. +func DurationSliceP(name, shorthand string, value []time.Duration, usage string) *[]time.Duration { + return CommandLine.DurationSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/errors.go b/vendor/github.com/spf13/pflag/errors.go new file mode 100644 index 0000000..ff11b66 --- /dev/null +++ b/vendor/github.com/spf13/pflag/errors.go @@ -0,0 +1,149 @@ +package pflag + +import "fmt" + +// notExistErrorMessageType specifies which flavor of "flag does not exist" +// is printed by NotExistError. This allows the related errors to be grouped +// under a single NotExistError struct without making a breaking change to +// the error message text. +type notExistErrorMessageType int + +const ( + flagNotExistMessage notExistErrorMessageType = iota + flagNotDefinedMessage + flagNoSuchFlagMessage + flagUnknownFlagMessage + flagUnknownShorthandFlagMessage +) + +// NotExistError is the error returned when trying to access a flag that +// does not exist in the FlagSet. +type NotExistError struct { + name string + specifiedShorthands string + messageType notExistErrorMessageType +} + +// Error implements error. +func (e *NotExistError) Error() string { + switch e.messageType { + case flagNotExistMessage: + return fmt.Sprintf("flag %q does not exist", e.name) + + case flagNotDefinedMessage: + return fmt.Sprintf("flag accessed but not defined: %s", e.name) + + case flagNoSuchFlagMessage: + return fmt.Sprintf("no such flag -%v", e.name) + + case flagUnknownFlagMessage: + return fmt.Sprintf("unknown flag: --%s", e.name) + + case flagUnknownShorthandFlagMessage: + c := rune(e.name[0]) + return fmt.Sprintf("unknown shorthand flag: %q in -%s", c, e.specifiedShorthands) + } + + panic(fmt.Errorf("unknown flagNotExistErrorMessageType: %v", e.messageType)) +} + +// GetSpecifiedName returns the name of the flag (without dashes) as it +// appeared in the parsed arguments. +func (e *NotExistError) GetSpecifiedName() string { + return e.name +} + +// GetSpecifiedShortnames returns the group of shorthand arguments +// (without dashes) that the flag appeared within. If the flag was not in a +// shorthand group, this will return an empty string. +func (e *NotExistError) GetSpecifiedShortnames() string { + return e.specifiedShorthands +} + +// ValueRequiredError is the error returned when a flag needs an argument but +// no argument was provided. +type ValueRequiredError struct { + flag *Flag + specifiedName string + specifiedShorthands string +} + +// Error implements error. +func (e *ValueRequiredError) Error() string { + if len(e.specifiedShorthands) > 0 { + c := rune(e.specifiedName[0]) + return fmt.Sprintf("flag needs an argument: %q in -%s", c, e.specifiedShorthands) + } + + return fmt.Sprintf("flag needs an argument: --%s", e.specifiedName) +} + +// GetFlag returns the flag for which the error occurred. +func (e *ValueRequiredError) GetFlag() *Flag { + return e.flag +} + +// GetSpecifiedName returns the name of the flag (without dashes) as it +// appeared in the parsed arguments. +func (e *ValueRequiredError) GetSpecifiedName() string { + return e.specifiedName +} + +// GetSpecifiedShortnames returns the group of shorthand arguments +// (without dashes) that the flag appeared within. If the flag was not in a +// shorthand group, this will return an empty string. +func (e *ValueRequiredError) GetSpecifiedShortnames() string { + return e.specifiedShorthands +} + +// InvalidValueError is the error returned when an invalid value is used +// for a flag. +type InvalidValueError struct { + flag *Flag + value string + cause error +} + +// Error implements error. +func (e *InvalidValueError) Error() string { + flag := e.flag + var flagName string + if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { + flagName = fmt.Sprintf("-%s, --%s", flag.Shorthand, flag.Name) + } else { + flagName = fmt.Sprintf("--%s", flag.Name) + } + return fmt.Sprintf("invalid argument %q for %q flag: %v", e.value, flagName, e.cause) +} + +// Unwrap implements errors.Unwrap. +func (e *InvalidValueError) Unwrap() error { + return e.cause +} + +// GetFlag returns the flag for which the error occurred. +func (e *InvalidValueError) GetFlag() *Flag { + return e.flag +} + +// GetValue returns the invalid value that was provided. +func (e *InvalidValueError) GetValue() string { + return e.value +} + +// InvalidSyntaxError is the error returned when a bad flag name is passed on +// the command line. +type InvalidSyntaxError struct { + specifiedFlag string +} + +// Error implements error. +func (e *InvalidSyntaxError) Error() string { + return fmt.Sprintf("bad flag syntax: %s", e.specifiedFlag) +} + +// GetSpecifiedName returns the exact flag (with dashes) as it +// appeared in the parsed arguments. +func (e *InvalidSyntaxError) GetSpecifiedFlag() string { + return e.specifiedFlag +} diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go new file mode 100644 index 0000000..eeed1e9 --- /dev/null +++ b/vendor/github.com/spf13/pflag/flag.go @@ -0,0 +1,1287 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package pflag is a drop-in replacement for Go's flag package, implementing +POSIX/GNU-style --flags. + +pflag is compatible with the GNU extensions to the POSIX recommendations +for command-line options. See +http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + +Usage: + +pflag is a drop-in replacement of Go's native flag package. If you import +pflag under the name "flag" then all code should continue to function +with no changes. + + import flag "github.com/spf13/pflag" + +There is one exception to this: if you directly instantiate the Flag struct +there is one more field "Shorthand" that you will need to set. +Most code never instantiates this struct directly, and instead uses +functions such as String(), BoolVar(), and Var(), and is therefore +unaffected. + +Define flags using flag.String(), Bool(), Int(), etc. + +This declares an integer flag, -flagname, stored in the pointer ip, with type *int. + + var ip = flag.Int("flagname", 1234, "help message for flagname") + +If you like, you can bind the flag to a variable using the Var() functions. + + var flagvar int + func init() { + flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname") + } + +Or you can create custom flags that satisfy the Value interface (with +pointer receivers) and couple them to flag parsing by + + flag.Var(&flagVal, "name", "help message for flagname") + +For such flags, the default value is just the initial value of the variable. + +After all flags are defined, call + + flag.Parse() + +to parse the command line into the defined flags. + +Flags may then be used directly. If you're using the flags themselves, +they are all pointers; if you bind to variables, they're values. + + fmt.Println("ip has value ", *ip) + fmt.Println("flagvar has value ", flagvar) + +After parsing, the arguments after the flag are available as the +slice flag.Args() or individually as flag.Arg(i). +The arguments are indexed from 0 through flag.NArg()-1. + +The pflag package also defines some new functions that are not in flag, +that give one-letter shorthands for flags. You can use these by appending +'P' to the name of any function that defines a flag. + + var ip = flag.IntP("flagname", "f", 1234, "help message") + var flagvar bool + func init() { + flag.BoolVarP(&flagvar, "boolname", "b", true, "help message") + } + flag.VarP(&flagval, "varname", "v", "help message") + +Shorthand letters can be used with single dashes on the command line. +Boolean shorthand flags can be combined with other shorthand flags. + +Command line flag syntax: + + --flag // boolean flags only + --flag=x + +Unlike the flag package, a single dash before an option means something +different than a double dash. Single dashes signify a series of shorthand +letters for flags. All but the last shorthand letter must be boolean flags. + + // boolean flags + -f + -abc + // non-boolean flags + -n 1234 + -Ifile + // mixed + -abcs "hello" + -abcn1234 + +Flag parsing stops after the terminator "--". Unlike the flag package, +flags can be interspersed with arguments anywhere on the command line +before this terminator. + +Integer flags accept 1234, 0664, 0x1234 and may be negative. +Boolean flags (in their long form) accept 1, 0, t, f, true, false, +TRUE, FALSE, True, False. +Duration flags accept any input valid for time.ParseDuration. + +The default set of command-line flags is controlled by +top-level functions. The FlagSet type allows one to define +independent sets of flags, such as to implement subcommands +in a command-line interface. The methods of FlagSet are +analogous to the top-level functions for the command-line +flag set. +*/ +package pflag + +import ( + "bytes" + "errors" + goflag "flag" + "fmt" + "io" + "os" + "sort" + "strings" +) + +// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined. +var ErrHelp = errors.New("pflag: help requested") + +// ErrorHandling defines how to handle flag parsing errors. +type ErrorHandling int + +const ( + // ContinueOnError will return an err from Parse() if an error is found + ContinueOnError ErrorHandling = iota + // ExitOnError will call os.Exit(2) if an error is found when parsing + ExitOnError + // PanicOnError will panic() if an error is found when parsing flags + PanicOnError +) + +// ParseErrorsAllowlist defines the parsing errors that can be ignored +type ParseErrorsAllowlist struct { + // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags + UnknownFlags bool +} + +// DEPRECATED: please use ParseErrorsAllowlist instead +// This type will be removed in a future release +type ParseErrorsWhitelist = ParseErrorsAllowlist + +// NormalizedName is a flag name that has been normalized according to rules +// for the FlagSet (e.g. making '-' and '_' equivalent). +type NormalizedName string + +// A FlagSet represents a set of defined flags. +type FlagSet struct { + // Usage is the function called when an error occurs while parsing flags. + // The field is a function (not a method) that may be changed to point to + // a custom error handler. + Usage func() + + // SortFlags is used to indicate, if user wants to have sorted flags in + // help/usage messages. + SortFlags bool + + // ParseErrorsAllowlist is used to configure an allowlist of errors + ParseErrorsAllowlist ParseErrorsAllowlist + + // DEPRECATED: please use ParseErrorsAllowlist instead + // This field will be removed in a future release + ParseErrorsWhitelist ParseErrorsAllowlist + + name string + parsed bool + actual map[NormalizedName]*Flag + orderedActual []*Flag + sortedActual []*Flag + formal map[NormalizedName]*Flag + orderedFormal []*Flag + sortedFormal []*Flag + shorthands map[byte]*Flag + args []string // arguments after flags + argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no -- + errorHandling ErrorHandling + output io.Writer // nil means stderr; use Output() accessor + interspersed bool // allow interspersed option/non-option args + normalizeNameFunc func(f *FlagSet, name string) NormalizedName + + addedGoFlagSets []*goflag.FlagSet +} + +// A Flag represents the state of a flag. +type Flag struct { + Name string // name as it appears on command line + Shorthand string // one-letter abbreviated flag + Usage string // help message + Value Value // value as set + DefValue string // default value (as text); for usage message + Changed bool // If the user set the value (or if left to default) + NoOptDefVal string // default value (as text); if the flag is on the command line without any options + Deprecated string // If this flag is deprecated, this string is the new or now thing to use + Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text + ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use + Annotations map[string][]string // used by cobra.Command bash autocomple code +} + +// Value is the interface to the dynamic value stored in a flag. +// (The default value is represented as a string.) +type Value interface { + String() string + Set(string) error + Type() string +} + +// SliceValue is a secondary interface to all flags which hold a list +// of values. This allows full control over the value of list flags, +// and avoids complicated marshalling and unmarshalling to csv. +type SliceValue interface { + // Append adds the specified value to the end of the flag value list. + Append(string) error + // Replace will fully overwrite any data currently in the flag value list. + Replace([]string) error + // GetSlice returns the flag value list as an array of strings. + GetSlice() []string +} + +// sortFlags returns the flags as a slice in lexicographical sorted order. +func sortFlags(flags map[NormalizedName]*Flag) []*Flag { + list := make(sort.StringSlice, len(flags)) + i := 0 + for k := range flags { + list[i] = string(k) + i++ + } + list.Sort() + result := make([]*Flag, len(list)) + for i, name := range list { + result[i] = flags[NormalizedName(name)] + } + return result +} + +// SetNormalizeFunc allows you to add a function which can translate flag names. +// Flags added to the FlagSet will be translated and then when anything tries to +// look up the flag that will also be translated. So it would be possible to create +// a flag named "getURL" and have it translated to "geturl". A user could then pass +// "--getUrl" which may also be translated to "geturl" and everything will work. +func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) { + f.normalizeNameFunc = n + f.sortedFormal = f.sortedFormal[:0] + for fname, flag := range f.formal { + nname := f.normalizeFlagName(flag.Name) + if fname == nname { + continue + } + flag.Name = string(nname) + delete(f.formal, fname) + f.formal[nname] = flag + if _, set := f.actual[fname]; set { + delete(f.actual, fname) + f.actual[nname] = flag + } + } +} + +// GetNormalizeFunc returns the previously set NormalizeFunc of a function which +// does no translation, if not set previously. +func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName { + if f.normalizeNameFunc != nil { + return f.normalizeNameFunc + } + return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) } +} + +func (f *FlagSet) normalizeFlagName(name string) NormalizedName { + n := f.GetNormalizeFunc() + return n(f, name) +} + +// Output returns the destination for usage and error messages. os.Stderr is returned if +// output was not set or was set to nil. +func (f *FlagSet) Output() io.Writer { + if f.output == nil { + return os.Stderr + } + return f.output +} + +// Name returns the name of the flag set. +func (f *FlagSet) Name() string { + return f.name +} + +// SetOutput sets the destination for usage and error messages. +// If output is nil, os.Stderr is used. +func (f *FlagSet) SetOutput(output io.Writer) { + f.output = output +} + +// VisitAll visits the flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. +// It visits all flags, even those not set. +func (f *FlagSet) VisitAll(fn func(*Flag)) { + if len(f.formal) == 0 { + return + } + + var flags []*Flag + if f.SortFlags { + if len(f.formal) != len(f.sortedFormal) { + f.sortedFormal = sortFlags(f.formal) + } + flags = f.sortedFormal + } else { + flags = f.orderedFormal + } + + for _, flag := range flags { + fn(flag) + } +} + +// HasFlags returns a bool to indicate if the FlagSet has any flags defined. +func (f *FlagSet) HasFlags() bool { + return len(f.formal) > 0 +} + +// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags +// that are not hidden. +func (f *FlagSet) HasAvailableFlags() bool { + for _, flag := range f.formal { + if !flag.Hidden { + return true + } + } + return false +} + +// VisitAll visits the command-line flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. +// It visits all flags, even those not set. +func VisitAll(fn func(*Flag)) { + CommandLine.VisitAll(fn) +} + +// Visit visits the flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. +// It visits only those flags that have been set. +func (f *FlagSet) Visit(fn func(*Flag)) { + if len(f.actual) == 0 { + return + } + + var flags []*Flag + if f.SortFlags { + if len(f.actual) != len(f.sortedActual) { + f.sortedActual = sortFlags(f.actual) + } + flags = f.sortedActual + } else { + flags = f.orderedActual + } + + for _, flag := range flags { + fn(flag) + } +} + +// Visit visits the command-line flags in lexicographical order or +// in primordial order if f.SortFlags is false, calling fn for each. +// It visits only those flags that have been set. +func Visit(fn func(*Flag)) { + CommandLine.Visit(fn) +} + +// Lookup returns the Flag structure of the named flag, returning nil if none exists. +func (f *FlagSet) Lookup(name string) *Flag { + return f.lookup(f.normalizeFlagName(name)) +} + +// ShorthandLookup returns the Flag structure of the short handed flag, +// returning nil if none exists. +// It panics, if len(name) > 1. +func (f *FlagSet) ShorthandLookup(name string) *Flag { + if name == "" { + return nil + } + if len(name) > 1 { + msg := fmt.Sprintf("can not look up shorthand which is more than one ASCII character: %q", name) + fmt.Fprintf(f.Output(), msg) + panic(msg) + } + c := name[0] + return f.shorthands[c] +} + +// lookup returns the Flag structure of the named flag, returning nil if none exists. +func (f *FlagSet) lookup(name NormalizedName) *Flag { + return f.formal[name] +} + +// func to return a given type for a given flag name +func (f *FlagSet) getFlagType(name string, ftype string, convFunc func(sval string) (interface{}, error)) (interface{}, error) { + flag := f.Lookup(name) + if flag == nil { + err := &NotExistError{name: name, messageType: flagNotDefinedMessage} + return nil, err + } + + if flag.Value.Type() != ftype { + err := fmt.Errorf("trying to get %s value of flag of type %s", ftype, flag.Value.Type()) + return nil, err + } + + sval := flag.Value.String() + result, err := convFunc(sval) + if err != nil { + return nil, err + } + return result, nil +} + +// ArgsLenAtDash will return the length of f.Args at the moment when a -- was +// found during arg parsing. This allows your program to know which args were +// before the -- and which came after. +func (f *FlagSet) ArgsLenAtDash() int { + return f.argsLenAtDash +} + +// MarkDeprecated indicated that a flag is deprecated in your program. It will +// continue to function but will not show up in help or usage messages. Using +// this flag will also print the given usageMessage. +func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error { + flag := f.Lookup(name) + if flag == nil { + return &NotExistError{name: name, messageType: flagNotExistMessage} + } + if usageMessage == "" { + return fmt.Errorf("deprecated message for flag %q must be set", name) + } + flag.Deprecated = usageMessage + flag.Hidden = true + return nil +} + +// MarkShorthandDeprecated will mark the shorthand of a flag deprecated in your +// program. It will continue to function but will not show up in help or usage +// messages. Using this flag will also print the given usageMessage. +func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error { + flag := f.Lookup(name) + if flag == nil { + return &NotExistError{name: name, messageType: flagNotExistMessage} + } + if usageMessage == "" { + return fmt.Errorf("deprecated message for flag %q must be set", name) + } + flag.ShorthandDeprecated = usageMessage + return nil +} + +// MarkHidden sets a flag to 'hidden' in your program. It will continue to +// function but will not show up in help or usage messages. +func (f *FlagSet) MarkHidden(name string) error { + flag := f.Lookup(name) + if flag == nil { + return &NotExistError{name: name, messageType: flagNotExistMessage} + } + flag.Hidden = true + return nil +} + +// Lookup returns the Flag structure of the named command-line flag, +// returning nil if none exists. +func Lookup(name string) *Flag { + return CommandLine.Lookup(name) +} + +// ShorthandLookup returns the Flag structure of the short handed flag, +// returning nil if none exists. +func ShorthandLookup(name string) *Flag { + return CommandLine.ShorthandLookup(name) +} + +// Set sets the value of the named flag. +func (f *FlagSet) Set(name, value string) error { + normalName := f.normalizeFlagName(name) + flag, ok := f.formal[normalName] + if !ok { + return &NotExistError{name: name, messageType: flagNoSuchFlagMessage} + } + + err := flag.Value.Set(value) + if err != nil { + return &InvalidValueError{ + flag: flag, + value: value, + cause: err, + } + } + + if !flag.Changed { + if f.actual == nil { + f.actual = make(map[NormalizedName]*Flag) + } + f.actual[normalName] = flag + f.orderedActual = append(f.orderedActual, flag) + + flag.Changed = true + } + + if flag.Deprecated != "" { + fmt.Fprintf(f.Output(), "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated) + } + return nil +} + +// SetAnnotation allows one to set arbitrary annotations on a flag in the FlagSet. +// This is sometimes used by spf13/cobra programs which want to generate additional +// bash completion information. +func (f *FlagSet) SetAnnotation(name, key string, values []string) error { + normalName := f.normalizeFlagName(name) + flag, ok := f.formal[normalName] + if !ok { + return &NotExistError{name: name, messageType: flagNoSuchFlagMessage} + } + if flag.Annotations == nil { + flag.Annotations = map[string][]string{} + } + flag.Annotations[key] = values + return nil +} + +// Changed returns true if the flag was explicitly set during Parse() and false +// otherwise +func (f *FlagSet) Changed(name string) bool { + flag := f.Lookup(name) + // If a flag doesn't exist, it wasn't changed.... + if flag == nil { + return false + } + return flag.Changed +} + +// Set sets the value of the named command-line flag. +func Set(name, value string) error { + return CommandLine.Set(name, value) +} + +// PrintDefaults prints, to standard error unless configured +// otherwise, the default values of all defined flags in the set. +func (f *FlagSet) PrintDefaults() { + usages := f.FlagUsages() + fmt.Fprint(f.Output(), usages) +} + +// defaultIsZeroValue returns true if the default value for this flag represents +// a zero value. +func (f *Flag) defaultIsZeroValue() bool { + switch f.Value.(type) { + case boolFlag: + return f.DefValue == "false" || f.DefValue == "" + case *durationValue: + // Beginning in Go 1.7, duration zero values are "0s" + return f.DefValue == "0" || f.DefValue == "0s" + case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value: + return f.DefValue == "0" + case *stringValue: + return f.DefValue == "" + case *ipValue, *ipMaskValue, *ipNetValue: + return f.DefValue == "" + case *intSliceValue, *stringSliceValue, *stringArrayValue: + return f.DefValue == "[]" + default: + switch f.DefValue { + case "false": + return true + case "": + return true + case "": + return true + case "0": + return true + } + return false + } +} + +// UnquoteUsage extracts a back-quoted name from the usage +// string for a flag and returns it and the un-quoted usage. +// Given "a `name` to show" it returns ("name", "a name to show"). +// If there are no back quotes, the name is an educated guess of the +// type of the flag's value, or the empty string if the flag is boolean. +func UnquoteUsage(flag *Flag) (name string, usage string) { + // Look for a back-quoted name, but avoid the strings package. + usage = flag.Usage + for i := 0; i < len(usage); i++ { + if usage[i] == '`' { + for j := i + 1; j < len(usage); j++ { + if usage[j] == '`' { + name = usage[i+1 : j] + usage = usage[:i] + name + usage[j+1:] + return name, usage + } + } + break // Only one back quote; use type name. + } + } + + name = flag.Value.Type() + switch name { + case "bool", "boolfunc": + name = "" + case "func": + name = "value" + case "float64": + name = "float" + case "int64": + name = "int" + case "uint64": + name = "uint" + case "stringSlice": + name = "strings" + case "intSlice": + name = "ints" + case "uintSlice": + name = "uints" + case "boolSlice": + name = "bools" + } + + return +} + +// Splits the string `s` on whitespace into an initial substring up to +// `i` runes in length and the remainder. Will go `slop` over `i` if +// that encompasses the entire string (which allows the caller to +// avoid short orphan words on the final line). +func wrapN(i, slop int, s string) (string, string) { + if i+slop > len(s) { + return s, "" + } + + w := strings.LastIndexAny(s[:i], " \t\n") + if w <= 0 { + return s, "" + } + nlPos := strings.LastIndex(s[:i], "\n") + if nlPos > 0 && nlPos < w { + return s[:nlPos], s[nlPos+1:] + } + return s[:w], s[w+1:] +} + +// Wraps the string `s` to a maximum width `w` with leading indent +// `i`. The first line is not indented (this is assumed to be done by +// caller). Pass `w` == 0 to do no wrapping +func wrap(i, w int, s string) string { + if w == 0 { + return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1) + } + + // space between indent i and end of line width w into which + // we should wrap the text. + wrap := w - i + + var r, l string + + // Not enough space for sensible wrapping. Wrap as a block on + // the next line instead. + if wrap < 24 { + i = 16 + wrap = w - i + r += "\n" + strings.Repeat(" ", i) + } + // If still not enough space then don't even try to wrap. + if wrap < 24 { + return strings.Replace(s, "\n", r, -1) + } + + // Try to avoid short orphan words on the final line, by + // allowing wrapN to go a bit over if that would fit in the + // remainder of the line. + slop := 5 + wrap = wrap - slop + + // Handle first line, which is indented by the caller (or the + // special case above) + l, s = wrapN(wrap, slop, s) + r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1) + + // Now wrap the rest + for s != "" { + var t string + + t, s = wrapN(wrap, slop, s) + r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1) + } + + return r + +} + +// FlagUsagesWrapped returns a string containing the usage information +// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no +// wrapping) +func (f *FlagSet) FlagUsagesWrapped(cols int) string { + buf := new(bytes.Buffer) + + lines := make([]string, 0, len(f.formal)) + + maxlen := 0 + f.VisitAll(func(flag *Flag) { + if flag.Hidden { + return + } + + line := "" + if flag.Shorthand != "" && flag.ShorthandDeprecated == "" { + line = fmt.Sprintf(" -%s, --%s", flag.Shorthand, flag.Name) + } else { + line = fmt.Sprintf(" --%s", flag.Name) + } + + varname, usage := UnquoteUsage(flag) + if varname != "" { + line += " " + varname + } + if flag.NoOptDefVal != "" { + switch flag.Value.Type() { + case "string": + line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal) + case "bool", "boolfunc": + if flag.NoOptDefVal != "true" { + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } + case "count": + if flag.NoOptDefVal != "+1" { + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } + default: + line += fmt.Sprintf("[=%s]", flag.NoOptDefVal) + } + } + + // This special character will be replaced with spacing once the + // correct alignment is calculated + line += "\x00" + if len(line) > maxlen { + maxlen = len(line) + } + + line += usage + if !flag.defaultIsZeroValue() { + if flag.Value.Type() == "string" { + line += fmt.Sprintf(" (default %q)", flag.DefValue) + } else { + line += fmt.Sprintf(" (default %s)", flag.DefValue) + } + } + if len(flag.Deprecated) != 0 { + line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated) + } + + lines = append(lines, line) + }) + + for _, line := range lines { + sidx := strings.Index(line, "\x00") + spacing := strings.Repeat(" ", maxlen-sidx) + // maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx + fmt.Fprintln(buf, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:])) + } + + return buf.String() +} + +// FlagUsages returns a string containing the usage information for all flags in +// the FlagSet +func (f *FlagSet) FlagUsages() string { + return f.FlagUsagesWrapped(0) +} + +// PrintDefaults prints to standard error the default values of all defined command-line flags. +func PrintDefaults() { + CommandLine.PrintDefaults() +} + +// defaultUsage is the default function to print a usage message. +func defaultUsage(f *FlagSet) { + fmt.Fprintf(f.Output(), "Usage of %s:\n", f.name) + f.PrintDefaults() +} + +// NOTE: Usage is not just defaultUsage(CommandLine) +// because it serves (via godoc flag Usage) as the example +// for how to write your own usage function. + +// Usage prints to standard error a usage message documenting all defined command-line flags. +// The function is a variable that may be changed to point to a custom function. +// By default it prints a simple header and calls PrintDefaults; for details about the +// format of the output and how to control it, see the documentation for PrintDefaults. +var Usage = func() { + fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) + PrintDefaults() +} + +// NFlag returns the number of flags that have been set. +func (f *FlagSet) NFlag() int { return len(f.actual) } + +// NFlag returns the number of command-line flags that have been set. +func NFlag() int { return len(CommandLine.actual) } + +// Arg returns the i'th argument. Arg(0) is the first remaining argument +// after flags have been processed. +func (f *FlagSet) Arg(i int) string { + if i < 0 || i >= len(f.args) { + return "" + } + return f.args[i] +} + +// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument +// after flags have been processed. +func Arg(i int) string { + return CommandLine.Arg(i) +} + +// NArg is the number of arguments remaining after flags have been processed. +func (f *FlagSet) NArg() int { return len(f.args) } + +// NArg is the number of arguments remaining after flags have been processed. +func NArg() int { return len(CommandLine.args) } + +// Args returns the non-flag arguments. +func (f *FlagSet) Args() []string { return f.args } + +// Args returns the non-flag command-line arguments. +func Args() []string { return CommandLine.args } + +// Var defines a flag with the specified name and usage string. The type and +// value of the flag are represented by the first argument, of type Value, which +// typically holds a user-defined implementation of Value. For instance, the +// caller could create a flag that turns a comma-separated string into a slice +// of strings by giving the slice the methods of Value; in particular, Set would +// decompose the comma-separated string into the slice. +func (f *FlagSet) Var(value Value, name string, usage string) { + f.VarP(value, name, "", usage) +} + +// VarPF is like VarP, but returns the flag created +func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag { + // Remember the default value as a string; it won't change. + flag := &Flag{ + Name: name, + Shorthand: shorthand, + Usage: usage, + Value: value, + DefValue: value.String(), + } + f.AddFlag(flag) + return flag +} + +// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) VarP(value Value, name, shorthand, usage string) { + f.VarPF(value, name, shorthand, usage) +} + +// AddFlag will add the flag to the FlagSet +func (f *FlagSet) AddFlag(flag *Flag) { + normalizedFlagName := f.normalizeFlagName(flag.Name) + + _, alreadyThere := f.formal[normalizedFlagName] + if alreadyThere { + msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name) + fmt.Fprintln(f.Output(), msg) + panic(msg) // Happens only if flags are declared with identical names + } + if f.formal == nil { + f.formal = make(map[NormalizedName]*Flag) + } + + flag.Name = string(normalizedFlagName) + f.formal[normalizedFlagName] = flag + f.orderedFormal = append(f.orderedFormal, flag) + + if flag.Shorthand == "" { + return + } + if len(flag.Shorthand) > 1 { + msg := fmt.Sprintf("%q shorthand is more than one ASCII character", flag.Shorthand) + fmt.Fprintf(f.Output(), msg) + panic(msg) + } + if f.shorthands == nil { + f.shorthands = make(map[byte]*Flag) + } + c := flag.Shorthand[0] + used, alreadyThere := f.shorthands[c] + if alreadyThere { + msg := fmt.Sprintf("unable to redefine %q shorthand in %q flagset: it's already used for %q flag", c, f.name, used.Name) + fmt.Fprintf(f.Output(), msg) + panic(msg) + } + f.shorthands[c] = flag +} + +// AddFlagSet adds one FlagSet to another. If a flag is already present in f +// the flag from newSet will be ignored. +func (f *FlagSet) AddFlagSet(newSet *FlagSet) { + if newSet == nil { + return + } + newSet.VisitAll(func(flag *Flag) { + if f.Lookup(flag.Name) == nil { + f.AddFlag(flag) + } + }) +} + +// Var defines a flag with the specified name and usage string. The type and +// value of the flag are represented by the first argument, of type Value, which +// typically holds a user-defined implementation of Value. For instance, the +// caller could create a flag that turns a comma-separated string into a slice +// of strings by giving the slice the methods of Value; in particular, Set would +// decompose the comma-separated string into the slice. +func Var(value Value, name string, usage string) { + CommandLine.VarP(value, name, "", usage) +} + +// VarP is like Var, but accepts a shorthand letter that can be used after a single dash. +func VarP(value Value, name, shorthand, usage string) { + CommandLine.VarP(value, name, shorthand, usage) +} + +// fail prints an error message and usage message to standard error and +// returns the error. +func (f *FlagSet) fail(err error) error { + if f.errorHandling != ContinueOnError { + f.usage() + } + return err +} + +// usage calls the Usage method for the flag set, or the usage function if +// the flag set is CommandLine. +func (f *FlagSet) usage() { + if f == CommandLine { + Usage() + } else if f.Usage == nil { + defaultUsage(f) + } else { + f.Usage() + } +} + +// --unknown (args will be empty) +// --unknown --next-flag ... (args will be --next-flag ...) +// --unknown arg ... (args will be arg ...) +func stripUnknownFlagValue(args []string) []string { + if len(args) == 0 { + //--unknown + return args + } + + first := args[0] + if len(first) > 0 && first[0] == '-' { + //--unknown --next-flag ... + return args + } + + //--unknown arg ... (args will be arg ...) + if len(args) > 1 { + return args[1:] + } + return nil +} + +func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) { + a = args + name := s[2:] + if len(name) == 0 || name[0] == '-' || name[0] == '=' { + err = f.fail(&InvalidSyntaxError{specifiedFlag: s}) + return + } + + split := strings.SplitN(name, "=", 2) + name = split[0] + flag, exists := f.formal[f.normalizeFlagName(name)] + + if !exists { + switch { + case name == "help": + f.usage() + return a, ErrHelp + case f.ParseErrorsWhitelist.UnknownFlags: + fallthrough + case f.ParseErrorsAllowlist.UnknownFlags: + // --unknown=unknownval arg ... + // we do not want to lose arg in this case + if len(split) >= 2 { + return a, nil + } + + return stripUnknownFlagValue(a), nil + default: + err = f.fail(&NotExistError{name: name, messageType: flagUnknownFlagMessage}) + return + } + } + + var value string + if len(split) == 2 { + // '--flag=arg' + value = split[1] + } else if flag.NoOptDefVal != "" { + // '--flag' (arg was optional) + value = flag.NoOptDefVal + } else if len(a) > 0 { + // '--flag arg' + value = a[0] + a = a[1:] + } else { + // '--flag' (arg was required) + err = f.fail(&ValueRequiredError{ + flag: flag, + specifiedName: name, + }) + return + } + + err = fn(flag, value) + if err != nil { + f.fail(err) + } + return +} + +func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) { + outArgs = args + + if isGotestShorthandFlag(shorthands) { + return + } + + outShorts = shorthands[1:] + c := shorthands[0] + + flag, exists := f.shorthands[c] + if !exists { + switch { + case c == 'h': + f.usage() + err = ErrHelp + return + case f.ParseErrorsWhitelist.UnknownFlags: + fallthrough + case f.ParseErrorsAllowlist.UnknownFlags: + // '-f=arg arg ...' + // we do not want to lose arg in this case + if len(shorthands) > 2 && shorthands[1] == '=' { + outShorts = "" + return + } + + outArgs = stripUnknownFlagValue(outArgs) + return + default: + err = f.fail(&NotExistError{ + name: string(c), + specifiedShorthands: shorthands, + messageType: flagUnknownShorthandFlagMessage, + }) + return + } + } + + var value string + if len(shorthands) > 2 && shorthands[1] == '=' { + // '-f=arg' + value = shorthands[2:] + outShorts = "" + } else if flag.NoOptDefVal != "" { + // '-f' (arg was optional) + value = flag.NoOptDefVal + } else if len(shorthands) > 1 { + // '-farg' + value = shorthands[1:] + outShorts = "" + } else if len(args) > 0 { + // '-f arg' + value = args[0] + outArgs = args[1:] + } else { + // '-f' (arg was required) + err = f.fail(&ValueRequiredError{ + flag: flag, + specifiedName: string(c), + specifiedShorthands: shorthands, + }) + return + } + + if flag.ShorthandDeprecated != "" { + fmt.Fprintf(f.Output(), "Flag shorthand -%s has been deprecated, %s\n", flag.Shorthand, flag.ShorthandDeprecated) + } + + err = fn(flag, value) + if err != nil { + f.fail(err) + } + return +} + +func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) { + a = args + shorthands := s[1:] + + // "shorthands" can be a series of shorthand letters of flags (e.g. "-vvv"). + for len(shorthands) > 0 { + shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn) + if err != nil { + return + } + } + + return +} + +func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) { + for len(args) > 0 { + s := args[0] + args = args[1:] + if len(s) == 0 || s[0] != '-' || len(s) == 1 { + if !f.interspersed { + f.args = append(f.args, s) + f.args = append(f.args, args...) + return nil + } + f.args = append(f.args, s) + continue + } + + if s[1] == '-' { + if len(s) == 2 { // "--" terminates the flags + f.argsLenAtDash = len(f.args) + f.args = append(f.args, args...) + break + } + args, err = f.parseLongArg(s, args, fn) + } else { + args, err = f.parseShortArg(s, args, fn) + } + if err != nil { + return + } + } + return +} + +// Parse parses flag definitions from the argument list, which should not +// include the command name. Must be called after all flags in the FlagSet +// are defined and before flags are accessed by the program. +// The return value will be ErrHelp if -help was set but not defined. +func (f *FlagSet) Parse(arguments []string) error { + if f.addedGoFlagSets != nil { + for _, goFlagSet := range f.addedGoFlagSets { + goFlagSet.Parse(nil) + } + } + f.parsed = true + + f.args = make([]string, 0, len(arguments)) + + if len(arguments) == 0 { + return nil + } + + set := func(flag *Flag, value string) error { + return f.Set(flag.Name, value) + } + + err := f.parseArgs(arguments, set) + if err != nil { + switch f.errorHandling { + case ContinueOnError: + return err + case ExitOnError: + if errors.Is(err, ErrHelp) { + os.Exit(0) + } + fmt.Fprintln(f.Output(), err) + os.Exit(2) + case PanicOnError: + panic(err) + } + } + return nil +} + +type parseFunc func(flag *Flag, value string) error + +// ParseAll parses flag definitions from the argument list, which should not +// include the command name. The arguments for fn are flag and value. Must be +// called after all flags in the FlagSet are defined and before flags are +// accessed by the program. The return value will be ErrHelp if -help was set +// but not defined. +func (f *FlagSet) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error { + f.parsed = true + f.args = make([]string, 0, len(arguments)) + + err := f.parseArgs(arguments, fn) + if err != nil { + switch f.errorHandling { + case ContinueOnError: + return err + case ExitOnError: + if errors.Is(err, ErrHelp) { + os.Exit(0) + } + fmt.Fprintln(f.Output(), err) + os.Exit(2) + case PanicOnError: + panic(err) + } + } + return nil +} + +// Parsed reports whether f.Parse has been called. +func (f *FlagSet) Parsed() bool { + return f.parsed +} + +// Parse parses the command-line flags from os.Args[1:]. Must be called +// after all flags are defined and before flags are accessed by the program. +func Parse() { + // Ignore errors; CommandLine is set for ExitOnError. + CommandLine.Parse(os.Args[1:]) +} + +// ParseAll parses the command-line flags from os.Args[1:] and called fn for each. +// The arguments for fn are flag and value. Must be called after all flags are +// defined and before flags are accessed by the program. +func ParseAll(fn func(flag *Flag, value string) error) { + // Ignore errors; CommandLine is set for ExitOnError. + CommandLine.ParseAll(os.Args[1:], fn) +} + +// SetInterspersed sets whether to support interspersed option/non-option arguments. +func SetInterspersed(interspersed bool) { + CommandLine.SetInterspersed(interspersed) +} + +// Parsed returns true if the command-line flags have been parsed. +func Parsed() bool { + return CommandLine.Parsed() +} + +// CommandLine is the default set of command-line flags, parsed from os.Args. +var CommandLine = NewFlagSet(os.Args[0], ExitOnError) + +// NewFlagSet returns a new, empty flag set with the specified name, +// error handling property and SortFlags set to true. +func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet { + f := &FlagSet{ + name: name, + errorHandling: errorHandling, + argsLenAtDash: -1, + interspersed: true, + SortFlags: true, + } + return f +} + +// SetInterspersed sets whether to support interspersed option/non-option arguments. +func (f *FlagSet) SetInterspersed(interspersed bool) { + f.interspersed = interspersed +} + +// Init sets the name and error handling property for a flag set. +// By default, the zero FlagSet uses an empty name and the +// ContinueOnError error handling policy. +func (f *FlagSet) Init(name string, errorHandling ErrorHandling) { + f.name = name + f.errorHandling = errorHandling + f.argsLenAtDash = -1 +} diff --git a/vendor/github.com/spf13/pflag/float32.go b/vendor/github.com/spf13/pflag/float32.go new file mode 100644 index 0000000..a243f81 --- /dev/null +++ b/vendor/github.com/spf13/pflag/float32.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- float32 Value +type float32Value float32 + +func newFloat32Value(val float32, p *float32) *float32Value { + *p = val + return (*float32Value)(p) +} + +func (f *float32Value) Set(s string) error { + v, err := strconv.ParseFloat(s, 32) + *f = float32Value(v) + return err +} + +func (f *float32Value) Type() string { + return "float32" +} + +func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) } + +func float32Conv(sval string) (interface{}, error) { + v, err := strconv.ParseFloat(sval, 32) + if err != nil { + return 0, err + } + return float32(v), nil +} + +// GetFloat32 return the float32 value of a flag with the given name +func (f *FlagSet) GetFloat32(name string) (float32, error) { + val, err := f.getFlagType(name, "float32", float32Conv) + if err != nil { + return 0, err + } + return val.(float32), nil +} + +// Float32Var defines a float32 flag with specified name, default value, and usage string. +// The argument p points to a float32 variable in which to store the value of the flag. +func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) { + f.VarP(newFloat32Value(value, p), name, "", usage) +} + +// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) { + f.VarP(newFloat32Value(value, p), name, shorthand, usage) +} + +// Float32Var defines a float32 flag with specified name, default value, and usage string. +// The argument p points to a float32 variable in which to store the value of the flag. +func Float32Var(p *float32, name string, value float32, usage string) { + CommandLine.VarP(newFloat32Value(value, p), name, "", usage) +} + +// Float32VarP is like Float32Var, but accepts a shorthand letter that can be used after a single dash. +func Float32VarP(p *float32, name, shorthand string, value float32, usage string) { + CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage) +} + +// Float32 defines a float32 flag with specified name, default value, and usage string. +// The return value is the address of a float32 variable that stores the value of the flag. +func (f *FlagSet) Float32(name string, value float32, usage string) *float32 { + p := new(float32) + f.Float32VarP(p, name, "", value, usage) + return p +} + +// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 { + p := new(float32) + f.Float32VarP(p, name, shorthand, value, usage) + return p +} + +// Float32 defines a float32 flag with specified name, default value, and usage string. +// The return value is the address of a float32 variable that stores the value of the flag. +func Float32(name string, value float32, usage string) *float32 { + return CommandLine.Float32P(name, "", value, usage) +} + +// Float32P is like Float32, but accepts a shorthand letter that can be used after a single dash. +func Float32P(name, shorthand string, value float32, usage string) *float32 { + return CommandLine.Float32P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/float32_slice.go b/vendor/github.com/spf13/pflag/float32_slice.go new file mode 100644 index 0000000..caa3527 --- /dev/null +++ b/vendor/github.com/spf13/pflag/float32_slice.go @@ -0,0 +1,174 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- float32Slice Value +type float32SliceValue struct { + value *[]float32 + changed bool +} + +func newFloat32SliceValue(val []float32, p *[]float32) *float32SliceValue { + isv := new(float32SliceValue) + isv.value = p + *isv.value = val + return isv +} + +func (s *float32SliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]float32, len(ss)) + for i, d := range ss { + var err error + var temp64 float64 + temp64, err = strconv.ParseFloat(d, 32) + if err != nil { + return err + } + out[i] = float32(temp64) + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *float32SliceValue) Type() string { + return "float32Slice" +} + +func (s *float32SliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%f", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *float32SliceValue) fromString(val string) (float32, error) { + t64, err := strconv.ParseFloat(val, 32) + if err != nil { + return 0, err + } + return float32(t64), nil +} + +func (s *float32SliceValue) toString(val float32) string { + return fmt.Sprintf("%f", val) +} + +func (s *float32SliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *float32SliceValue) Replace(val []string) error { + out := make([]float32, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *float32SliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func float32SliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []float32{}, nil + } + ss := strings.Split(val, ",") + out := make([]float32, len(ss)) + for i, d := range ss { + var err error + var temp64 float64 + temp64, err = strconv.ParseFloat(d, 32) + if err != nil { + return nil, err + } + out[i] = float32(temp64) + + } + return out, nil +} + +// GetFloat32Slice return the []float32 value of a flag with the given name +func (f *FlagSet) GetFloat32Slice(name string) ([]float32, error) { + val, err := f.getFlagType(name, "float32Slice", float32SliceConv) + if err != nil { + return []float32{}, err + } + return val.([]float32), nil +} + +// Float32SliceVar defines a float32Slice flag with specified name, default value, and usage string. +// The argument p points to a []float32 variable in which to store the value of the flag. +func (f *FlagSet) Float32SliceVar(p *[]float32, name string, value []float32, usage string) { + f.VarP(newFloat32SliceValue(value, p), name, "", usage) +} + +// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) { + f.VarP(newFloat32SliceValue(value, p), name, shorthand, usage) +} + +// Float32SliceVar defines a float32[] flag with specified name, default value, and usage string. +// The argument p points to a float32[] variable in which to store the value of the flag. +func Float32SliceVar(p *[]float32, name string, value []float32, usage string) { + CommandLine.VarP(newFloat32SliceValue(value, p), name, "", usage) +} + +// Float32SliceVarP is like Float32SliceVar, but accepts a shorthand letter that can be used after a single dash. +func Float32SliceVarP(p *[]float32, name, shorthand string, value []float32, usage string) { + CommandLine.VarP(newFloat32SliceValue(value, p), name, shorthand, usage) +} + +// Float32Slice defines a []float32 flag with specified name, default value, and usage string. +// The return value is the address of a []float32 variable that stores the value of the flag. +func (f *FlagSet) Float32Slice(name string, value []float32, usage string) *[]float32 { + p := []float32{} + f.Float32SliceVarP(&p, name, "", value, usage) + return &p +} + +// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 { + p := []float32{} + f.Float32SliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// Float32Slice defines a []float32 flag with specified name, default value, and usage string. +// The return value is the address of a []float32 variable that stores the value of the flag. +func Float32Slice(name string, value []float32, usage string) *[]float32 { + return CommandLine.Float32SliceP(name, "", value, usage) +} + +// Float32SliceP is like Float32Slice, but accepts a shorthand letter that can be used after a single dash. +func Float32SliceP(name, shorthand string, value []float32, usage string) *[]float32 { + return CommandLine.Float32SliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/float64.go b/vendor/github.com/spf13/pflag/float64.go new file mode 100644 index 0000000..04b5492 --- /dev/null +++ b/vendor/github.com/spf13/pflag/float64.go @@ -0,0 +1,84 @@ +package pflag + +import "strconv" + +// -- float64 Value +type float64Value float64 + +func newFloat64Value(val float64, p *float64) *float64Value { + *p = val + return (*float64Value)(p) +} + +func (f *float64Value) Set(s string) error { + v, err := strconv.ParseFloat(s, 64) + *f = float64Value(v) + return err +} + +func (f *float64Value) Type() string { + return "float64" +} + +func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) } + +func float64Conv(sval string) (interface{}, error) { + return strconv.ParseFloat(sval, 64) +} + +// GetFloat64 return the float64 value of a flag with the given name +func (f *FlagSet) GetFloat64(name string) (float64, error) { + val, err := f.getFlagType(name, "float64", float64Conv) + if err != nil { + return 0, err + } + return val.(float64), nil +} + +// Float64Var defines a float64 flag with specified name, default value, and usage string. +// The argument p points to a float64 variable in which to store the value of the flag. +func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) { + f.VarP(newFloat64Value(value, p), name, "", usage) +} + +// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) { + f.VarP(newFloat64Value(value, p), name, shorthand, usage) +} + +// Float64Var defines a float64 flag with specified name, default value, and usage string. +// The argument p points to a float64 variable in which to store the value of the flag. +func Float64Var(p *float64, name string, value float64, usage string) { + CommandLine.VarP(newFloat64Value(value, p), name, "", usage) +} + +// Float64VarP is like Float64Var, but accepts a shorthand letter that can be used after a single dash. +func Float64VarP(p *float64, name, shorthand string, value float64, usage string) { + CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage) +} + +// Float64 defines a float64 flag with specified name, default value, and usage string. +// The return value is the address of a float64 variable that stores the value of the flag. +func (f *FlagSet) Float64(name string, value float64, usage string) *float64 { + p := new(float64) + f.Float64VarP(p, name, "", value, usage) + return p +} + +// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 { + p := new(float64) + f.Float64VarP(p, name, shorthand, value, usage) + return p +} + +// Float64 defines a float64 flag with specified name, default value, and usage string. +// The return value is the address of a float64 variable that stores the value of the flag. +func Float64(name string, value float64, usage string) *float64 { + return CommandLine.Float64P(name, "", value, usage) +} + +// Float64P is like Float64, but accepts a shorthand letter that can be used after a single dash. +func Float64P(name, shorthand string, value float64, usage string) *float64 { + return CommandLine.Float64P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/float64_slice.go b/vendor/github.com/spf13/pflag/float64_slice.go new file mode 100644 index 0000000..85bf307 --- /dev/null +++ b/vendor/github.com/spf13/pflag/float64_slice.go @@ -0,0 +1,166 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- float64Slice Value +type float64SliceValue struct { + value *[]float64 + changed bool +} + +func newFloat64SliceValue(val []float64, p *[]float64) *float64SliceValue { + isv := new(float64SliceValue) + isv.value = p + *isv.value = val + return isv +} + +func (s *float64SliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]float64, len(ss)) + for i, d := range ss { + var err error + out[i], err = strconv.ParseFloat(d, 64) + if err != nil { + return err + } + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *float64SliceValue) Type() string { + return "float64Slice" +} + +func (s *float64SliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%f", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *float64SliceValue) fromString(val string) (float64, error) { + return strconv.ParseFloat(val, 64) +} + +func (s *float64SliceValue) toString(val float64) string { + return fmt.Sprintf("%f", val) +} + +func (s *float64SliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *float64SliceValue) Replace(val []string) error { + out := make([]float64, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *float64SliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func float64SliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []float64{}, nil + } + ss := strings.Split(val, ",") + out := make([]float64, len(ss)) + for i, d := range ss { + var err error + out[i], err = strconv.ParseFloat(d, 64) + if err != nil { + return nil, err + } + + } + return out, nil +} + +// GetFloat64Slice return the []float64 value of a flag with the given name +func (f *FlagSet) GetFloat64Slice(name string) ([]float64, error) { + val, err := f.getFlagType(name, "float64Slice", float64SliceConv) + if err != nil { + return []float64{}, err + } + return val.([]float64), nil +} + +// Float64SliceVar defines a float64Slice flag with specified name, default value, and usage string. +// The argument p points to a []float64 variable in which to store the value of the flag. +func (f *FlagSet) Float64SliceVar(p *[]float64, name string, value []float64, usage string) { + f.VarP(newFloat64SliceValue(value, p), name, "", usage) +} + +// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) { + f.VarP(newFloat64SliceValue(value, p), name, shorthand, usage) +} + +// Float64SliceVar defines a float64[] flag with specified name, default value, and usage string. +// The argument p points to a float64[] variable in which to store the value of the flag. +func Float64SliceVar(p *[]float64, name string, value []float64, usage string) { + CommandLine.VarP(newFloat64SliceValue(value, p), name, "", usage) +} + +// Float64SliceVarP is like Float64SliceVar, but accepts a shorthand letter that can be used after a single dash. +func Float64SliceVarP(p *[]float64, name, shorthand string, value []float64, usage string) { + CommandLine.VarP(newFloat64SliceValue(value, p), name, shorthand, usage) +} + +// Float64Slice defines a []float64 flag with specified name, default value, and usage string. +// The return value is the address of a []float64 variable that stores the value of the flag. +func (f *FlagSet) Float64Slice(name string, value []float64, usage string) *[]float64 { + p := []float64{} + f.Float64SliceVarP(&p, name, "", value, usage) + return &p +} + +// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 { + p := []float64{} + f.Float64SliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// Float64Slice defines a []float64 flag with specified name, default value, and usage string. +// The return value is the address of a []float64 variable that stores the value of the flag. +func Float64Slice(name string, value []float64, usage string) *[]float64 { + return CommandLine.Float64SliceP(name, "", value, usage) +} + +// Float64SliceP is like Float64Slice, but accepts a shorthand letter that can be used after a single dash. +func Float64SliceP(name, shorthand string, value []float64, usage string) *[]float64 { + return CommandLine.Float64SliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/func.go b/vendor/github.com/spf13/pflag/func.go new file mode 100644 index 0000000..9f4d88f --- /dev/null +++ b/vendor/github.com/spf13/pflag/func.go @@ -0,0 +1,37 @@ +package pflag + +// -- func Value +type funcValue func(string) error + +func (f funcValue) Set(s string) error { return f(s) } + +func (f funcValue) Type() string { return "func" } + +func (f funcValue) String() string { return "" } // same behavior as stdlib 'flag' package + +// Func defines a func flag with specified name, callback function and usage string. +// +// The callback function will be called every time "--{name}={value}" (or equivalent) is +// parsed on the command line, with "{value}" as an argument. +func (f *FlagSet) Func(name string, usage string, fn func(string) error) { + f.FuncP(name, "", usage, fn) +} + +// FuncP is like Func, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) FuncP(name string, shorthand string, usage string, fn func(string) error) { + var val Value = funcValue(fn) + f.VarP(val, name, shorthand, usage) +} + +// Func defines a func flag with specified name, callback function and usage string. +// +// The callback function will be called every time "--{name}={value}" (or equivalent) is +// parsed on the command line, with "{value}" as an argument. +func Func(name string, usage string, fn func(string) error) { + CommandLine.FuncP(name, "", usage, fn) +} + +// FuncP is like Func, but accepts a shorthand letter that can be used after a single dash. +func FuncP(name, shorthand string, usage string, fn func(string) error) { + CommandLine.FuncP(name, shorthand, usage, fn) +} diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go new file mode 100644 index 0000000..e62eab5 --- /dev/null +++ b/vendor/github.com/spf13/pflag/golangflag.go @@ -0,0 +1,161 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package pflag + +import ( + goflag "flag" + "reflect" + "strings" + "time" +) + +// go test flags prefixes +func isGotestFlag(flag string) bool { + return strings.HasPrefix(flag, "-test.") +} + +func isGotestShorthandFlag(flag string) bool { + return strings.HasPrefix(flag, "test.") +} + +// flagValueWrapper implements pflag.Value around a flag.Value. The main +// difference here is the addition of the Type method that returns a string +// name of the type. As this is generally unknown, we approximate that with +// reflection. +type flagValueWrapper struct { + inner goflag.Value + flagType string +} + +// We are just copying the boolFlag interface out of goflag as that is what +// they use to decide if a flag should get "true" when no arg is given. +type goBoolFlag interface { + goflag.Value + IsBoolFlag() bool +} + +func wrapFlagValue(v goflag.Value) Value { + // If the flag.Value happens to also be a pflag.Value, just use it directly. + if pv, ok := v.(Value); ok { + return pv + } + + pv := &flagValueWrapper{ + inner: v, + } + + t := reflect.TypeOf(v) + if t.Kind() == reflect.Interface || t.Kind() == reflect.Ptr { + t = t.Elem() + } + + pv.flagType = strings.TrimSuffix(t.Name(), "Value") + return pv +} + +func (v *flagValueWrapper) String() string { + return v.inner.String() +} + +func (v *flagValueWrapper) Set(s string) error { + return v.inner.Set(s) +} + +func (v *flagValueWrapper) Type() string { + return v.flagType +} + +// PFlagFromGoFlag will return a *pflag.Flag given a *flag.Flag +// If the *flag.Flag.Name was a single character (ex: `v`) it will be accessiblei +// with both `-v` and `--v` in flags. If the golang flag was more than a single +// character (ex: `verbose`) it will only be accessible via `--verbose` +func PFlagFromGoFlag(goflag *goflag.Flag) *Flag { + // Remember the default value as a string; it won't change. + flag := &Flag{ + Name: goflag.Name, + Usage: goflag.Usage, + Value: wrapFlagValue(goflag.Value), + // Looks like golang flags don't set DefValue correctly :-( + //DefValue: goflag.DefValue, + DefValue: goflag.Value.String(), + } + // Ex: if the golang flag was -v, allow both -v and --v to work + if len(flag.Name) == 1 { + flag.Shorthand = flag.Name + } + if fv, ok := goflag.Value.(goBoolFlag); ok && fv.IsBoolFlag() { + flag.NoOptDefVal = "true" + } + return flag +} + +// AddGoFlag will add the given *flag.Flag to the pflag.FlagSet +func (f *FlagSet) AddGoFlag(goflag *goflag.Flag) { + if f.Lookup(goflag.Name) != nil { + return + } + newflag := PFlagFromGoFlag(goflag) + f.AddFlag(newflag) +} + +// AddGoFlagSet will add the given *flag.FlagSet to the pflag.FlagSet +func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) { + if newSet == nil { + return + } + newSet.VisitAll(func(goflag *goflag.Flag) { + f.AddGoFlag(goflag) + }) + if f.addedGoFlagSets == nil { + f.addedGoFlagSets = make([]*goflag.FlagSet, 0) + } + f.addedGoFlagSets = append(f.addedGoFlagSets, newSet) +} + +// CopyToGoFlagSet will add all current flags to the given Go flag set. +// Deprecation remarks get copied into the usage description. +// Whenever possible, a flag gets added for which Go flags shows +// a proper type in the help message. +func (f *FlagSet) CopyToGoFlagSet(newSet *goflag.FlagSet) { + f.VisitAll(func(flag *Flag) { + usage := flag.Usage + if flag.Deprecated != "" { + usage += " (DEPRECATED: " + flag.Deprecated + ")" + } + + switch value := flag.Value.(type) { + case *stringValue: + newSet.StringVar((*string)(value), flag.Name, flag.DefValue, usage) + case *intValue: + newSet.IntVar((*int)(value), flag.Name, *(*int)(value), usage) + case *int64Value: + newSet.Int64Var((*int64)(value), flag.Name, *(*int64)(value), usage) + case *uintValue: + newSet.UintVar((*uint)(value), flag.Name, *(*uint)(value), usage) + case *uint64Value: + newSet.Uint64Var((*uint64)(value), flag.Name, *(*uint64)(value), usage) + case *durationValue: + newSet.DurationVar((*time.Duration)(value), flag.Name, *(*time.Duration)(value), usage) + case *float64Value: + newSet.Float64Var((*float64)(value), flag.Name, *(*float64)(value), usage) + default: + newSet.Var(flag.Value, flag.Name, usage) + } + }) +} + +// ParseSkippedFlags explicitly Parses go test flags (i.e. the one starting with '-test.') with goflag.Parse(), +// since by default those are skipped by pflag.Parse(). +// Typical usage example: `ParseGoTestFlags(os.Args[1:], goflag.CommandLine)` +func ParseSkippedFlags(osArgs []string, goFlagSet *goflag.FlagSet) error { + var skippedFlags []string + for _, f := range osArgs { + if isGotestFlag(f) { + skippedFlags = append(skippedFlags, f) + } + } + return goFlagSet.Parse(skippedFlags) +} + diff --git a/vendor/github.com/spf13/pflag/int.go b/vendor/github.com/spf13/pflag/int.go new file mode 100644 index 0000000..1474b89 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int.go @@ -0,0 +1,84 @@ +package pflag + +import "strconv" + +// -- int Value +type intValue int + +func newIntValue(val int, p *int) *intValue { + *p = val + return (*intValue)(p) +} + +func (i *intValue) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 64) + *i = intValue(v) + return err +} + +func (i *intValue) Type() string { + return "int" +} + +func (i *intValue) String() string { return strconv.Itoa(int(*i)) } + +func intConv(sval string) (interface{}, error) { + return strconv.Atoi(sval) +} + +// GetInt return the int value of a flag with the given name +func (f *FlagSet) GetInt(name string) (int, error) { + val, err := f.getFlagType(name, "int", intConv) + if err != nil { + return 0, err + } + return val.(int), nil +} + +// IntVar defines an int flag with specified name, default value, and usage string. +// The argument p points to an int variable in which to store the value of the flag. +func (f *FlagSet) IntVar(p *int, name string, value int, usage string) { + f.VarP(newIntValue(value, p), name, "", usage) +} + +// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) { + f.VarP(newIntValue(value, p), name, shorthand, usage) +} + +// IntVar defines an int flag with specified name, default value, and usage string. +// The argument p points to an int variable in which to store the value of the flag. +func IntVar(p *int, name string, value int, usage string) { + CommandLine.VarP(newIntValue(value, p), name, "", usage) +} + +// IntVarP is like IntVar, but accepts a shorthand letter that can be used after a single dash. +func IntVarP(p *int, name, shorthand string, value int, usage string) { + CommandLine.VarP(newIntValue(value, p), name, shorthand, usage) +} + +// Int defines an int flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +func (f *FlagSet) Int(name string, value int, usage string) *int { + p := new(int) + f.IntVarP(p, name, "", value, usage) + return p +} + +// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int { + p := new(int) + f.IntVarP(p, name, shorthand, value, usage) + return p +} + +// Int defines an int flag with specified name, default value, and usage string. +// The return value is the address of an int variable that stores the value of the flag. +func Int(name string, value int, usage string) *int { + return CommandLine.IntP(name, "", value, usage) +} + +// IntP is like Int, but accepts a shorthand letter that can be used after a single dash. +func IntP(name, shorthand string, value int, usage string) *int { + return CommandLine.IntP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int16.go b/vendor/github.com/spf13/pflag/int16.go new file mode 100644 index 0000000..f1a01d0 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int16.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- int16 Value +type int16Value int16 + +func newInt16Value(val int16, p *int16) *int16Value { + *p = val + return (*int16Value)(p) +} + +func (i *int16Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 16) + *i = int16Value(v) + return err +} + +func (i *int16Value) Type() string { + return "int16" +} + +func (i *int16Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +func int16Conv(sval string) (interface{}, error) { + v, err := strconv.ParseInt(sval, 0, 16) + if err != nil { + return 0, err + } + return int16(v), nil +} + +// GetInt16 returns the int16 value of a flag with the given name +func (f *FlagSet) GetInt16(name string) (int16, error) { + val, err := f.getFlagType(name, "int16", int16Conv) + if err != nil { + return 0, err + } + return val.(int16), nil +} + +// Int16Var defines an int16 flag with specified name, default value, and usage string. +// The argument p points to an int16 variable in which to store the value of the flag. +func (f *FlagSet) Int16Var(p *int16, name string, value int16, usage string) { + f.VarP(newInt16Value(value, p), name, "", usage) +} + +// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int16VarP(p *int16, name, shorthand string, value int16, usage string) { + f.VarP(newInt16Value(value, p), name, shorthand, usage) +} + +// Int16Var defines an int16 flag with specified name, default value, and usage string. +// The argument p points to an int16 variable in which to store the value of the flag. +func Int16Var(p *int16, name string, value int16, usage string) { + CommandLine.VarP(newInt16Value(value, p), name, "", usage) +} + +// Int16VarP is like Int16Var, but accepts a shorthand letter that can be used after a single dash. +func Int16VarP(p *int16, name, shorthand string, value int16, usage string) { + CommandLine.VarP(newInt16Value(value, p), name, shorthand, usage) +} + +// Int16 defines an int16 flag with specified name, default value, and usage string. +// The return value is the address of an int16 variable that stores the value of the flag. +func (f *FlagSet) Int16(name string, value int16, usage string) *int16 { + p := new(int16) + f.Int16VarP(p, name, "", value, usage) + return p +} + +// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int16P(name, shorthand string, value int16, usage string) *int16 { + p := new(int16) + f.Int16VarP(p, name, shorthand, value, usage) + return p +} + +// Int16 defines an int16 flag with specified name, default value, and usage string. +// The return value is the address of an int16 variable that stores the value of the flag. +func Int16(name string, value int16, usage string) *int16 { + return CommandLine.Int16P(name, "", value, usage) +} + +// Int16P is like Int16, but accepts a shorthand letter that can be used after a single dash. +func Int16P(name, shorthand string, value int16, usage string) *int16 { + return CommandLine.Int16P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int32.go b/vendor/github.com/spf13/pflag/int32.go new file mode 100644 index 0000000..9b95944 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int32.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- int32 Value +type int32Value int32 + +func newInt32Value(val int32, p *int32) *int32Value { + *p = val + return (*int32Value)(p) +} + +func (i *int32Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 32) + *i = int32Value(v) + return err +} + +func (i *int32Value) Type() string { + return "int32" +} + +func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +func int32Conv(sval string) (interface{}, error) { + v, err := strconv.ParseInt(sval, 0, 32) + if err != nil { + return 0, err + } + return int32(v), nil +} + +// GetInt32 return the int32 value of a flag with the given name +func (f *FlagSet) GetInt32(name string) (int32, error) { + val, err := f.getFlagType(name, "int32", int32Conv) + if err != nil { + return 0, err + } + return val.(int32), nil +} + +// Int32Var defines an int32 flag with specified name, default value, and usage string. +// The argument p points to an int32 variable in which to store the value of the flag. +func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) { + f.VarP(newInt32Value(value, p), name, "", usage) +} + +// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) { + f.VarP(newInt32Value(value, p), name, shorthand, usage) +} + +// Int32Var defines an int32 flag with specified name, default value, and usage string. +// The argument p points to an int32 variable in which to store the value of the flag. +func Int32Var(p *int32, name string, value int32, usage string) { + CommandLine.VarP(newInt32Value(value, p), name, "", usage) +} + +// Int32VarP is like Int32Var, but accepts a shorthand letter that can be used after a single dash. +func Int32VarP(p *int32, name, shorthand string, value int32, usage string) { + CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage) +} + +// Int32 defines an int32 flag with specified name, default value, and usage string. +// The return value is the address of an int32 variable that stores the value of the flag. +func (f *FlagSet) Int32(name string, value int32, usage string) *int32 { + p := new(int32) + f.Int32VarP(p, name, "", value, usage) + return p +} + +// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 { + p := new(int32) + f.Int32VarP(p, name, shorthand, value, usage) + return p +} + +// Int32 defines an int32 flag with specified name, default value, and usage string. +// The return value is the address of an int32 variable that stores the value of the flag. +func Int32(name string, value int32, usage string) *int32 { + return CommandLine.Int32P(name, "", value, usage) +} + +// Int32P is like Int32, but accepts a shorthand letter that can be used after a single dash. +func Int32P(name, shorthand string, value int32, usage string) *int32 { + return CommandLine.Int32P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int32_slice.go b/vendor/github.com/spf13/pflag/int32_slice.go new file mode 100644 index 0000000..ff128ff --- /dev/null +++ b/vendor/github.com/spf13/pflag/int32_slice.go @@ -0,0 +1,174 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- int32Slice Value +type int32SliceValue struct { + value *[]int32 + changed bool +} + +func newInt32SliceValue(val []int32, p *[]int32) *int32SliceValue { + isv := new(int32SliceValue) + isv.value = p + *isv.value = val + return isv +} + +func (s *int32SliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]int32, len(ss)) + for i, d := range ss { + var err error + var temp64 int64 + temp64, err = strconv.ParseInt(d, 0, 32) + if err != nil { + return err + } + out[i] = int32(temp64) + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *int32SliceValue) Type() string { + return "int32Slice" +} + +func (s *int32SliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%d", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *int32SliceValue) fromString(val string) (int32, error) { + t64, err := strconv.ParseInt(val, 0, 32) + if err != nil { + return 0, err + } + return int32(t64), nil +} + +func (s *int32SliceValue) toString(val int32) string { + return fmt.Sprintf("%d", val) +} + +func (s *int32SliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *int32SliceValue) Replace(val []string) error { + out := make([]int32, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *int32SliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func int32SliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []int32{}, nil + } + ss := strings.Split(val, ",") + out := make([]int32, len(ss)) + for i, d := range ss { + var err error + var temp64 int64 + temp64, err = strconv.ParseInt(d, 0, 32) + if err != nil { + return nil, err + } + out[i] = int32(temp64) + + } + return out, nil +} + +// GetInt32Slice return the []int32 value of a flag with the given name +func (f *FlagSet) GetInt32Slice(name string) ([]int32, error) { + val, err := f.getFlagType(name, "int32Slice", int32SliceConv) + if err != nil { + return []int32{}, err + } + return val.([]int32), nil +} + +// Int32SliceVar defines a int32Slice flag with specified name, default value, and usage string. +// The argument p points to a []int32 variable in which to store the value of the flag. +func (f *FlagSet) Int32SliceVar(p *[]int32, name string, value []int32, usage string) { + f.VarP(newInt32SliceValue(value, p), name, "", usage) +} + +// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) { + f.VarP(newInt32SliceValue(value, p), name, shorthand, usage) +} + +// Int32SliceVar defines a int32[] flag with specified name, default value, and usage string. +// The argument p points to a int32[] variable in which to store the value of the flag. +func Int32SliceVar(p *[]int32, name string, value []int32, usage string) { + CommandLine.VarP(newInt32SliceValue(value, p), name, "", usage) +} + +// Int32SliceVarP is like Int32SliceVar, but accepts a shorthand letter that can be used after a single dash. +func Int32SliceVarP(p *[]int32, name, shorthand string, value []int32, usage string) { + CommandLine.VarP(newInt32SliceValue(value, p), name, shorthand, usage) +} + +// Int32Slice defines a []int32 flag with specified name, default value, and usage string. +// The return value is the address of a []int32 variable that stores the value of the flag. +func (f *FlagSet) Int32Slice(name string, value []int32, usage string) *[]int32 { + p := []int32{} + f.Int32SliceVarP(&p, name, "", value, usage) + return &p +} + +// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 { + p := []int32{} + f.Int32SliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// Int32Slice defines a []int32 flag with specified name, default value, and usage string. +// The return value is the address of a []int32 variable that stores the value of the flag. +func Int32Slice(name string, value []int32, usage string) *[]int32 { + return CommandLine.Int32SliceP(name, "", value, usage) +} + +// Int32SliceP is like Int32Slice, but accepts a shorthand letter that can be used after a single dash. +func Int32SliceP(name, shorthand string, value []int32, usage string) *[]int32 { + return CommandLine.Int32SliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int64.go b/vendor/github.com/spf13/pflag/int64.go new file mode 100644 index 0000000..0026d78 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int64.go @@ -0,0 +1,84 @@ +package pflag + +import "strconv" + +// -- int64 Value +type int64Value int64 + +func newInt64Value(val int64, p *int64) *int64Value { + *p = val + return (*int64Value)(p) +} + +func (i *int64Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 64) + *i = int64Value(v) + return err +} + +func (i *int64Value) Type() string { + return "int64" +} + +func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +func int64Conv(sval string) (interface{}, error) { + return strconv.ParseInt(sval, 0, 64) +} + +// GetInt64 return the int64 value of a flag with the given name +func (f *FlagSet) GetInt64(name string) (int64, error) { + val, err := f.getFlagType(name, "int64", int64Conv) + if err != nil { + return 0, err + } + return val.(int64), nil +} + +// Int64Var defines an int64 flag with specified name, default value, and usage string. +// The argument p points to an int64 variable in which to store the value of the flag. +func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) { + f.VarP(newInt64Value(value, p), name, "", usage) +} + +// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) { + f.VarP(newInt64Value(value, p), name, shorthand, usage) +} + +// Int64Var defines an int64 flag with specified name, default value, and usage string. +// The argument p points to an int64 variable in which to store the value of the flag. +func Int64Var(p *int64, name string, value int64, usage string) { + CommandLine.VarP(newInt64Value(value, p), name, "", usage) +} + +// Int64VarP is like Int64Var, but accepts a shorthand letter that can be used after a single dash. +func Int64VarP(p *int64, name, shorthand string, value int64, usage string) { + CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage) +} + +// Int64 defines an int64 flag with specified name, default value, and usage string. +// The return value is the address of an int64 variable that stores the value of the flag. +func (f *FlagSet) Int64(name string, value int64, usage string) *int64 { + p := new(int64) + f.Int64VarP(p, name, "", value, usage) + return p +} + +// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 { + p := new(int64) + f.Int64VarP(p, name, shorthand, value, usage) + return p +} + +// Int64 defines an int64 flag with specified name, default value, and usage string. +// The return value is the address of an int64 variable that stores the value of the flag. +func Int64(name string, value int64, usage string) *int64 { + return CommandLine.Int64P(name, "", value, usage) +} + +// Int64P is like Int64, but accepts a shorthand letter that can be used after a single dash. +func Int64P(name, shorthand string, value int64, usage string) *int64 { + return CommandLine.Int64P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int64_slice.go b/vendor/github.com/spf13/pflag/int64_slice.go new file mode 100644 index 0000000..2546463 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int64_slice.go @@ -0,0 +1,166 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- int64Slice Value +type int64SliceValue struct { + value *[]int64 + changed bool +} + +func newInt64SliceValue(val []int64, p *[]int64) *int64SliceValue { + isv := new(int64SliceValue) + isv.value = p + *isv.value = val + return isv +} + +func (s *int64SliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]int64, len(ss)) + for i, d := range ss { + var err error + out[i], err = strconv.ParseInt(d, 0, 64) + if err != nil { + return err + } + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *int64SliceValue) Type() string { + return "int64Slice" +} + +func (s *int64SliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%d", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *int64SliceValue) fromString(val string) (int64, error) { + return strconv.ParseInt(val, 0, 64) +} + +func (s *int64SliceValue) toString(val int64) string { + return fmt.Sprintf("%d", val) +} + +func (s *int64SliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *int64SliceValue) Replace(val []string) error { + out := make([]int64, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *int64SliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func int64SliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []int64{}, nil + } + ss := strings.Split(val, ",") + out := make([]int64, len(ss)) + for i, d := range ss { + var err error + out[i], err = strconv.ParseInt(d, 0, 64) + if err != nil { + return nil, err + } + + } + return out, nil +} + +// GetInt64Slice return the []int64 value of a flag with the given name +func (f *FlagSet) GetInt64Slice(name string) ([]int64, error) { + val, err := f.getFlagType(name, "int64Slice", int64SliceConv) + if err != nil { + return []int64{}, err + } + return val.([]int64), nil +} + +// Int64SliceVar defines a int64Slice flag with specified name, default value, and usage string. +// The argument p points to a []int64 variable in which to store the value of the flag. +func (f *FlagSet) Int64SliceVar(p *[]int64, name string, value []int64, usage string) { + f.VarP(newInt64SliceValue(value, p), name, "", usage) +} + +// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) { + f.VarP(newInt64SliceValue(value, p), name, shorthand, usage) +} + +// Int64SliceVar defines a int64[] flag with specified name, default value, and usage string. +// The argument p points to a int64[] variable in which to store the value of the flag. +func Int64SliceVar(p *[]int64, name string, value []int64, usage string) { + CommandLine.VarP(newInt64SliceValue(value, p), name, "", usage) +} + +// Int64SliceVarP is like Int64SliceVar, but accepts a shorthand letter that can be used after a single dash. +func Int64SliceVarP(p *[]int64, name, shorthand string, value []int64, usage string) { + CommandLine.VarP(newInt64SliceValue(value, p), name, shorthand, usage) +} + +// Int64Slice defines a []int64 flag with specified name, default value, and usage string. +// The return value is the address of a []int64 variable that stores the value of the flag. +func (f *FlagSet) Int64Slice(name string, value []int64, usage string) *[]int64 { + p := []int64{} + f.Int64SliceVarP(&p, name, "", value, usage) + return &p +} + +// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 { + p := []int64{} + f.Int64SliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// Int64Slice defines a []int64 flag with specified name, default value, and usage string. +// The return value is the address of a []int64 variable that stores the value of the flag. +func Int64Slice(name string, value []int64, usage string) *[]int64 { + return CommandLine.Int64SliceP(name, "", value, usage) +} + +// Int64SliceP is like Int64Slice, but accepts a shorthand letter that can be used after a single dash. +func Int64SliceP(name, shorthand string, value []int64, usage string) *[]int64 { + return CommandLine.Int64SliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int8.go b/vendor/github.com/spf13/pflag/int8.go new file mode 100644 index 0000000..4da9222 --- /dev/null +++ b/vendor/github.com/spf13/pflag/int8.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- int8 Value +type int8Value int8 + +func newInt8Value(val int8, p *int8) *int8Value { + *p = val + return (*int8Value)(p) +} + +func (i *int8Value) Set(s string) error { + v, err := strconv.ParseInt(s, 0, 8) + *i = int8Value(v) + return err +} + +func (i *int8Value) Type() string { + return "int8" +} + +func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) } + +func int8Conv(sval string) (interface{}, error) { + v, err := strconv.ParseInt(sval, 0, 8) + if err != nil { + return 0, err + } + return int8(v), nil +} + +// GetInt8 return the int8 value of a flag with the given name +func (f *FlagSet) GetInt8(name string) (int8, error) { + val, err := f.getFlagType(name, "int8", int8Conv) + if err != nil { + return 0, err + } + return val.(int8), nil +} + +// Int8Var defines an int8 flag with specified name, default value, and usage string. +// The argument p points to an int8 variable in which to store the value of the flag. +func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) { + f.VarP(newInt8Value(value, p), name, "", usage) +} + +// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) { + f.VarP(newInt8Value(value, p), name, shorthand, usage) +} + +// Int8Var defines an int8 flag with specified name, default value, and usage string. +// The argument p points to an int8 variable in which to store the value of the flag. +func Int8Var(p *int8, name string, value int8, usage string) { + CommandLine.VarP(newInt8Value(value, p), name, "", usage) +} + +// Int8VarP is like Int8Var, but accepts a shorthand letter that can be used after a single dash. +func Int8VarP(p *int8, name, shorthand string, value int8, usage string) { + CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage) +} + +// Int8 defines an int8 flag with specified name, default value, and usage string. +// The return value is the address of an int8 variable that stores the value of the flag. +func (f *FlagSet) Int8(name string, value int8, usage string) *int8 { + p := new(int8) + f.Int8VarP(p, name, "", value, usage) + return p +} + +// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 { + p := new(int8) + f.Int8VarP(p, name, shorthand, value, usage) + return p +} + +// Int8 defines an int8 flag with specified name, default value, and usage string. +// The return value is the address of an int8 variable that stores the value of the flag. +func Int8(name string, value int8, usage string) *int8 { + return CommandLine.Int8P(name, "", value, usage) +} + +// Int8P is like Int8, but accepts a shorthand letter that can be used after a single dash. +func Int8P(name, shorthand string, value int8, usage string) *int8 { + return CommandLine.Int8P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/int_slice.go b/vendor/github.com/spf13/pflag/int_slice.go new file mode 100644 index 0000000..e71c39d --- /dev/null +++ b/vendor/github.com/spf13/pflag/int_slice.go @@ -0,0 +1,158 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- intSlice Value +type intSliceValue struct { + value *[]int + changed bool +} + +func newIntSliceValue(val []int, p *[]int) *intSliceValue { + isv := new(intSliceValue) + isv.value = p + *isv.value = val + return isv +} + +func (s *intSliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]int, len(ss)) + for i, d := range ss { + var err error + out[i], err = strconv.Atoi(d) + if err != nil { + return err + } + + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *intSliceValue) Type() string { + return "intSlice" +} + +func (s *intSliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%d", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *intSliceValue) Append(val string) error { + i, err := strconv.Atoi(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *intSliceValue) Replace(val []string) error { + out := make([]int, len(val)) + for i, d := range val { + var err error + out[i], err = strconv.Atoi(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *intSliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = strconv.Itoa(d) + } + return out +} + +func intSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []int{}, nil + } + ss := strings.Split(val, ",") + out := make([]int, len(ss)) + for i, d := range ss { + var err error + out[i], err = strconv.Atoi(d) + if err != nil { + return nil, err + } + + } + return out, nil +} + +// GetIntSlice return the []int value of a flag with the given name +func (f *FlagSet) GetIntSlice(name string) ([]int, error) { + val, err := f.getFlagType(name, "intSlice", intSliceConv) + if err != nil { + return []int{}, err + } + return val.([]int), nil +} + +// IntSliceVar defines a intSlice flag with specified name, default value, and usage string. +// The argument p points to a []int variable in which to store the value of the flag. +func (f *FlagSet) IntSliceVar(p *[]int, name string, value []int, usage string) { + f.VarP(newIntSliceValue(value, p), name, "", usage) +} + +// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { + f.VarP(newIntSliceValue(value, p), name, shorthand, usage) +} + +// IntSliceVar defines a int[] flag with specified name, default value, and usage string. +// The argument p points to a int[] variable in which to store the value of the flag. +func IntSliceVar(p *[]int, name string, value []int, usage string) { + CommandLine.VarP(newIntSliceValue(value, p), name, "", usage) +} + +// IntSliceVarP is like IntSliceVar, but accepts a shorthand letter that can be used after a single dash. +func IntSliceVarP(p *[]int, name, shorthand string, value []int, usage string) { + CommandLine.VarP(newIntSliceValue(value, p), name, shorthand, usage) +} + +// IntSlice defines a []int flag with specified name, default value, and usage string. +// The return value is the address of a []int variable that stores the value of the flag. +func (f *FlagSet) IntSlice(name string, value []int, usage string) *[]int { + p := []int{} + f.IntSliceVarP(&p, name, "", value, usage) + return &p +} + +// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IntSliceP(name, shorthand string, value []int, usage string) *[]int { + p := []int{} + f.IntSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// IntSlice defines a []int flag with specified name, default value, and usage string. +// The return value is the address of a []int variable that stores the value of the flag. +func IntSlice(name string, value []int, usage string) *[]int { + return CommandLine.IntSliceP(name, "", value, usage) +} + +// IntSliceP is like IntSlice, but accepts a shorthand letter that can be used after a single dash. +func IntSliceP(name, shorthand string, value []int, usage string) *[]int { + return CommandLine.IntSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/ip.go b/vendor/github.com/spf13/pflag/ip.go new file mode 100644 index 0000000..06b8bcb --- /dev/null +++ b/vendor/github.com/spf13/pflag/ip.go @@ -0,0 +1,97 @@ +package pflag + +import ( + "fmt" + "net" + "strings" +) + +// -- net.IP value +type ipValue net.IP + +func newIPValue(val net.IP, p *net.IP) *ipValue { + *p = val + return (*ipValue)(p) +} + +func (i *ipValue) String() string { return net.IP(*i).String() } +func (i *ipValue) Set(s string) error { + if s == "" { + return nil + } + ip := net.ParseIP(strings.TrimSpace(s)) + if ip == nil { + return fmt.Errorf("failed to parse IP: %q", s) + } + *i = ipValue(ip) + return nil +} + +func (i *ipValue) Type() string { + return "ip" +} + +func ipConv(sval string) (interface{}, error) { + ip := net.ParseIP(sval) + if ip != nil { + return ip, nil + } + return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) +} + +// GetIP return the net.IP value of a flag with the given name +func (f *FlagSet) GetIP(name string) (net.IP, error) { + val, err := f.getFlagType(name, "ip", ipConv) + if err != nil { + return nil, err + } + return val.(net.IP), nil +} + +// IPVar defines an net.IP flag with specified name, default value, and usage string. +// The argument p points to an net.IP variable in which to store the value of the flag. +func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) { + f.VarP(newIPValue(value, p), name, "", usage) +} + +// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { + f.VarP(newIPValue(value, p), name, shorthand, usage) +} + +// IPVar defines an net.IP flag with specified name, default value, and usage string. +// The argument p points to an net.IP variable in which to store the value of the flag. +func IPVar(p *net.IP, name string, value net.IP, usage string) { + CommandLine.VarP(newIPValue(value, p), name, "", usage) +} + +// IPVarP is like IPVar, but accepts a shorthand letter that can be used after a single dash. +func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) { + CommandLine.VarP(newIPValue(value, p), name, shorthand, usage) +} + +// IP defines an net.IP flag with specified name, default value, and usage string. +// The return value is the address of an net.IP variable that stores the value of the flag. +func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP { + p := new(net.IP) + f.IPVarP(p, name, "", value, usage) + return p +} + +// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP { + p := new(net.IP) + f.IPVarP(p, name, shorthand, value, usage) + return p +} + +// IP defines an net.IP flag with specified name, default value, and usage string. +// The return value is the address of an net.IP variable that stores the value of the flag. +func IP(name string, value net.IP, usage string) *net.IP { + return CommandLine.IPP(name, "", value, usage) +} + +// IPP is like IP, but accepts a shorthand letter that can be used after a single dash. +func IPP(name, shorthand string, value net.IP, usage string) *net.IP { + return CommandLine.IPP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/ip_slice.go b/vendor/github.com/spf13/pflag/ip_slice.go new file mode 100644 index 0000000..775faae --- /dev/null +++ b/vendor/github.com/spf13/pflag/ip_slice.go @@ -0,0 +1,186 @@ +package pflag + +import ( + "fmt" + "io" + "net" + "strings" +) + +// -- ipSlice Value +type ipSliceValue struct { + value *[]net.IP + changed bool +} + +func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue { + ipsv := new(ipSliceValue) + ipsv.value = p + *ipsv.value = val + return ipsv +} + +// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag. +// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended. +func (s *ipSliceValue) Set(val string) error { + + // remove all quote characters + rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") + + // read flag arguments with CSV parser + ipStrSlice, err := readAsCSV(rmQuote.Replace(val)) + if err != nil && err != io.EOF { + return err + } + + // parse ip values into slice + out := make([]net.IP, 0, len(ipStrSlice)) + for _, ipStr := range ipStrSlice { + ip := net.ParseIP(strings.TrimSpace(ipStr)) + if ip == nil { + return fmt.Errorf("invalid string being converted to IP address: %s", ipStr) + } + out = append(out, ip) + } + + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + + s.changed = true + + return nil +} + +// Type returns a string that uniquely represents this flag's type. +func (s *ipSliceValue) Type() string { + return "ipSlice" +} + +// String defines a "native" format for this net.IP slice flag value. +func (s *ipSliceValue) String() string { + + ipStrSlice := make([]string, len(*s.value)) + for i, ip := range *s.value { + ipStrSlice[i] = ip.String() + } + + out, _ := writeAsCSV(ipStrSlice) + + return "[" + out + "]" +} + +func (s *ipSliceValue) fromString(val string) (net.IP, error) { + return net.ParseIP(strings.TrimSpace(val)), nil +} + +func (s *ipSliceValue) toString(val net.IP) string { + return val.String() +} + +func (s *ipSliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *ipSliceValue) Replace(val []string) error { + out := make([]net.IP, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *ipSliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func ipSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []net.IP{}, nil + } + ss := strings.Split(val, ",") + out := make([]net.IP, len(ss)) + for i, sval := range ss { + ip := net.ParseIP(strings.TrimSpace(sval)) + if ip == nil { + return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval) + } + out[i] = ip + } + return out, nil +} + +// GetIPSlice returns the []net.IP value of a flag with the given name +func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) { + val, err := f.getFlagType(name, "ipSlice", ipSliceConv) + if err != nil { + return []net.IP{}, err + } + return val.([]net.IP), nil +} + +// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string. +// The argument p points to a []net.IP variable in which to store the value of the flag. +func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { + f.VarP(newIPSliceValue(value, p), name, "", usage) +} + +// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { + f.VarP(newIPSliceValue(value, p), name, shorthand, usage) +} + +// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string. +// The argument p points to a []net.IP variable in which to store the value of the flag. +func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) { + CommandLine.VarP(newIPSliceValue(value, p), name, "", usage) +} + +// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash. +func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) { + CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage) +} + +// IPSlice defines a []net.IP flag with specified name, default value, and usage string. +// The return value is the address of a []net.IP variable that stores the value of that flag. +func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP { + p := []net.IP{} + f.IPSliceVarP(&p, name, "", value, usage) + return &p +} + +// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { + p := []net.IP{} + f.IPSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// IPSlice defines a []net.IP flag with specified name, default value, and usage string. +// The return value is the address of a []net.IP variable that stores the value of the flag. +func IPSlice(name string, value []net.IP, usage string) *[]net.IP { + return CommandLine.IPSliceP(name, "", value, usage) +} + +// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash. +func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP { + return CommandLine.IPSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/ipmask.go b/vendor/github.com/spf13/pflag/ipmask.go new file mode 100644 index 0000000..5bd44bd --- /dev/null +++ b/vendor/github.com/spf13/pflag/ipmask.go @@ -0,0 +1,122 @@ +package pflag + +import ( + "fmt" + "net" + "strconv" +) + +// -- net.IPMask value +type ipMaskValue net.IPMask + +func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue { + *p = val + return (*ipMaskValue)(p) +} + +func (i *ipMaskValue) String() string { return net.IPMask(*i).String() } +func (i *ipMaskValue) Set(s string) error { + ip := ParseIPv4Mask(s) + if ip == nil { + return fmt.Errorf("failed to parse IP mask: %q", s) + } + *i = ipMaskValue(ip) + return nil +} + +func (i *ipMaskValue) Type() string { + return "ipMask" +} + +// ParseIPv4Mask written in IP form (e.g. 255.255.255.0). +// This function should really belong to the net package. +func ParseIPv4Mask(s string) net.IPMask { + mask := net.ParseIP(s) + if mask == nil { + if len(s) != 8 { + return nil + } + // net.IPMask.String() actually outputs things like ffffff00 + // so write a horrible parser for that as well :-( + m := []int{} + for i := 0; i < 4; i++ { + b := "0x" + s[2*i:2*i+2] + d, err := strconv.ParseInt(b, 0, 0) + if err != nil { + return nil + } + m = append(m, int(d)) + } + s := fmt.Sprintf("%d.%d.%d.%d", m[0], m[1], m[2], m[3]) + mask = net.ParseIP(s) + if mask == nil { + return nil + } + } + return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15]) +} + +func parseIPv4Mask(sval string) (interface{}, error) { + mask := ParseIPv4Mask(sval) + if mask == nil { + return nil, fmt.Errorf("unable to parse %s as net.IPMask", sval) + } + return mask, nil +} + +// GetIPv4Mask return the net.IPv4Mask value of a flag with the given name +func (f *FlagSet) GetIPv4Mask(name string) (net.IPMask, error) { + val, err := f.getFlagType(name, "ipMask", parseIPv4Mask) + if err != nil { + return nil, err + } + return val.(net.IPMask), nil +} + +// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. +// The argument p points to an net.IPMask variable in which to store the value of the flag. +func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { + f.VarP(newIPMaskValue(value, p), name, "", usage) +} + +// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { + f.VarP(newIPMaskValue(value, p), name, shorthand, usage) +} + +// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string. +// The argument p points to an net.IPMask variable in which to store the value of the flag. +func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) { + CommandLine.VarP(newIPMaskValue(value, p), name, "", usage) +} + +// IPMaskVarP is like IPMaskVar, but accepts a shorthand letter that can be used after a single dash. +func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) { + CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage) +} + +// IPMask defines an net.IPMask flag with specified name, default value, and usage string. +// The return value is the address of an net.IPMask variable that stores the value of the flag. +func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask { + p := new(net.IPMask) + f.IPMaskVarP(p, name, "", value, usage) + return p +} + +// IPMaskP is like IPMask, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { + p := new(net.IPMask) + f.IPMaskVarP(p, name, shorthand, value, usage) + return p +} + +// IPMask defines an net.IPMask flag with specified name, default value, and usage string. +// The return value is the address of an net.IPMask variable that stores the value of the flag. +func IPMask(name string, value net.IPMask, usage string) *net.IPMask { + return CommandLine.IPMaskP(name, "", value, usage) +} + +// IPMaskP is like IP, but accepts a shorthand letter that can be used after a single dash. +func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask { + return CommandLine.IPMaskP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/ipnet.go b/vendor/github.com/spf13/pflag/ipnet.go new file mode 100644 index 0000000..e2c1b8b --- /dev/null +++ b/vendor/github.com/spf13/pflag/ipnet.go @@ -0,0 +1,98 @@ +package pflag + +import ( + "fmt" + "net" + "strings" +) + +// IPNet adapts net.IPNet for use as a flag. +type ipNetValue net.IPNet + +func (ipnet ipNetValue) String() string { + n := net.IPNet(ipnet) + return n.String() +} + +func (ipnet *ipNetValue) Set(value string) error { + _, n, err := net.ParseCIDR(strings.TrimSpace(value)) + if err != nil { + return err + } + *ipnet = ipNetValue(*n) + return nil +} + +func (*ipNetValue) Type() string { + return "ipNet" +} + +func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue { + *p = val + return (*ipNetValue)(p) +} + +func ipNetConv(sval string) (interface{}, error) { + _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) + if err == nil { + return *n, nil + } + return nil, fmt.Errorf("invalid string being converted to IPNet: %s", sval) +} + +// GetIPNet return the net.IPNet value of a flag with the given name +func (f *FlagSet) GetIPNet(name string) (net.IPNet, error) { + val, err := f.getFlagType(name, "ipNet", ipNetConv) + if err != nil { + return net.IPNet{}, err + } + return val.(net.IPNet), nil +} + +// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. +// The argument p points to an net.IPNet variable in which to store the value of the flag. +func (f *FlagSet) IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { + f.VarP(newIPNetValue(value, p), name, "", usage) +} + +// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { + f.VarP(newIPNetValue(value, p), name, shorthand, usage) +} + +// IPNetVar defines an net.IPNet flag with specified name, default value, and usage string. +// The argument p points to an net.IPNet variable in which to store the value of the flag. +func IPNetVar(p *net.IPNet, name string, value net.IPNet, usage string) { + CommandLine.VarP(newIPNetValue(value, p), name, "", usage) +} + +// IPNetVarP is like IPNetVar, but accepts a shorthand letter that can be used after a single dash. +func IPNetVarP(p *net.IPNet, name, shorthand string, value net.IPNet, usage string) { + CommandLine.VarP(newIPNetValue(value, p), name, shorthand, usage) +} + +// IPNet defines an net.IPNet flag with specified name, default value, and usage string. +// The return value is the address of an net.IPNet variable that stores the value of the flag. +func (f *FlagSet) IPNet(name string, value net.IPNet, usage string) *net.IPNet { + p := new(net.IPNet) + f.IPNetVarP(p, name, "", value, usage) + return p +} + +// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { + p := new(net.IPNet) + f.IPNetVarP(p, name, shorthand, value, usage) + return p +} + +// IPNet defines an net.IPNet flag with specified name, default value, and usage string. +// The return value is the address of an net.IPNet variable that stores the value of the flag. +func IPNet(name string, value net.IPNet, usage string) *net.IPNet { + return CommandLine.IPNetP(name, "", value, usage) +} + +// IPNetP is like IPNet, but accepts a shorthand letter that can be used after a single dash. +func IPNetP(name, shorthand string, value net.IPNet, usage string) *net.IPNet { + return CommandLine.IPNetP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/ipnet_slice.go b/vendor/github.com/spf13/pflag/ipnet_slice.go new file mode 100644 index 0000000..c6e89da --- /dev/null +++ b/vendor/github.com/spf13/pflag/ipnet_slice.go @@ -0,0 +1,147 @@ +package pflag + +import ( + "fmt" + "io" + "net" + "strings" +) + +// -- ipNetSlice Value +type ipNetSliceValue struct { + value *[]net.IPNet + changed bool +} + +func newIPNetSliceValue(val []net.IPNet, p *[]net.IPNet) *ipNetSliceValue { + ipnsv := new(ipNetSliceValue) + ipnsv.value = p + *ipnsv.value = val + return ipnsv +} + +// Set converts, and assigns, the comma-separated IPNet argument string representation as the []net.IPNet value of this flag. +// If Set is called on a flag that already has a []net.IPNet assigned, the newly converted values will be appended. +func (s *ipNetSliceValue) Set(val string) error { + + // remove all quote characters + rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "") + + // read flag arguments with CSV parser + ipNetStrSlice, err := readAsCSV(rmQuote.Replace(val)) + if err != nil && err != io.EOF { + return err + } + + // parse ip values into slice + out := make([]net.IPNet, 0, len(ipNetStrSlice)) + for _, ipNetStr := range ipNetStrSlice { + _, n, err := net.ParseCIDR(strings.TrimSpace(ipNetStr)) + if err != nil { + return fmt.Errorf("invalid string being converted to CIDR: %s", ipNetStr) + } + out = append(out, *n) + } + + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + + s.changed = true + + return nil +} + +// Type returns a string that uniquely represents this flag's type. +func (s *ipNetSliceValue) Type() string { + return "ipNetSlice" +} + +// String defines a "native" format for this net.IPNet slice flag value. +func (s *ipNetSliceValue) String() string { + + ipNetStrSlice := make([]string, len(*s.value)) + for i, n := range *s.value { + ipNetStrSlice[i] = n.String() + } + + out, _ := writeAsCSV(ipNetStrSlice) + return "[" + out + "]" +} + +func ipNetSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []net.IPNet{}, nil + } + ss := strings.Split(val, ",") + out := make([]net.IPNet, len(ss)) + for i, sval := range ss { + _, n, err := net.ParseCIDR(strings.TrimSpace(sval)) + if err != nil { + return nil, fmt.Errorf("invalid string being converted to CIDR: %s", sval) + } + out[i] = *n + } + return out, nil +} + +// GetIPNetSlice returns the []net.IPNet value of a flag with the given name +func (f *FlagSet) GetIPNetSlice(name string) ([]net.IPNet, error) { + val, err := f.getFlagType(name, "ipNetSlice", ipNetSliceConv) + if err != nil { + return []net.IPNet{}, err + } + return val.([]net.IPNet), nil +} + +// IPNetSliceVar defines a ipNetSlice flag with specified name, default value, and usage string. +// The argument p points to a []net.IPNet variable in which to store the value of the flag. +func (f *FlagSet) IPNetSliceVar(p *[]net.IPNet, name string, value []net.IPNet, usage string) { + f.VarP(newIPNetSliceValue(value, p), name, "", usage) +} + +// IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPNetSliceVarP(p *[]net.IPNet, name, shorthand string, value []net.IPNet, usage string) { + f.VarP(newIPNetSliceValue(value, p), name, shorthand, usage) +} + +// IPNetSliceVar defines a []net.IPNet flag with specified name, default value, and usage string. +// The argument p points to a []net.IPNet variable in which to store the value of the flag. +func IPNetSliceVar(p *[]net.IPNet, name string, value []net.IPNet, usage string) { + CommandLine.VarP(newIPNetSliceValue(value, p), name, "", usage) +} + +// IPNetSliceVarP is like IPNetSliceVar, but accepts a shorthand letter that can be used after a single dash. +func IPNetSliceVarP(p *[]net.IPNet, name, shorthand string, value []net.IPNet, usage string) { + CommandLine.VarP(newIPNetSliceValue(value, p), name, shorthand, usage) +} + +// IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string. +// The return value is the address of a []net.IPNet variable that stores the value of that flag. +func (f *FlagSet) IPNetSlice(name string, value []net.IPNet, usage string) *[]net.IPNet { + p := []net.IPNet{} + f.IPNetSliceVarP(&p, name, "", value, usage) + return &p +} + +// IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) IPNetSliceP(name, shorthand string, value []net.IPNet, usage string) *[]net.IPNet { + p := []net.IPNet{} + f.IPNetSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// IPNetSlice defines a []net.IPNet flag with specified name, default value, and usage string. +// The return value is the address of a []net.IP variable that stores the value of the flag. +func IPNetSlice(name string, value []net.IPNet, usage string) *[]net.IPNet { + return CommandLine.IPNetSliceP(name, "", value, usage) +} + +// IPNetSliceP is like IPNetSlice, but accepts a shorthand letter that can be used after a single dash. +func IPNetSliceP(name, shorthand string, value []net.IPNet, usage string) *[]net.IPNet { + return CommandLine.IPNetSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string.go b/vendor/github.com/spf13/pflag/string.go new file mode 100644 index 0000000..04e0a26 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string.go @@ -0,0 +1,80 @@ +package pflag + +// -- string Value +type stringValue string + +func newStringValue(val string, p *string) *stringValue { + *p = val + return (*stringValue)(p) +} + +func (s *stringValue) Set(val string) error { + *s = stringValue(val) + return nil +} +func (s *stringValue) Type() string { + return "string" +} + +func (s *stringValue) String() string { return string(*s) } + +func stringConv(sval string) (interface{}, error) { + return sval, nil +} + +// GetString return the string value of a flag with the given name +func (f *FlagSet) GetString(name string) (string, error) { + val, err := f.getFlagType(name, "string", stringConv) + if err != nil { + return "", err + } + return val.(string), nil +} + +// StringVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a string variable in which to store the value of the flag. +func (f *FlagSet) StringVar(p *string, name string, value string, usage string) { + f.VarP(newStringValue(value, p), name, "", usage) +} + +// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) { + f.VarP(newStringValue(value, p), name, shorthand, usage) +} + +// StringVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a string variable in which to store the value of the flag. +func StringVar(p *string, name string, value string, usage string) { + CommandLine.VarP(newStringValue(value, p), name, "", usage) +} + +// StringVarP is like StringVar, but accepts a shorthand letter that can be used after a single dash. +func StringVarP(p *string, name, shorthand string, value string, usage string) { + CommandLine.VarP(newStringValue(value, p), name, shorthand, usage) +} + +// String defines a string flag with specified name, default value, and usage string. +// The return value is the address of a string variable that stores the value of the flag. +func (f *FlagSet) String(name string, value string, usage string) *string { + p := new(string) + f.StringVarP(p, name, "", value, usage) + return p +} + +// StringP is like String, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string { + p := new(string) + f.StringVarP(p, name, shorthand, value, usage) + return p +} + +// String defines a string flag with specified name, default value, and usage string. +// The return value is the address of a string variable that stores the value of the flag. +func String(name string, value string, usage string) *string { + return CommandLine.StringP(name, "", value, usage) +} + +// StringP is like String, but accepts a shorthand letter that can be used after a single dash. +func StringP(name, shorthand string, value string, usage string) *string { + return CommandLine.StringP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go new file mode 100644 index 0000000..d1ff0a9 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_array.go @@ -0,0 +1,125 @@ +package pflag + +// -- stringArray Value +type stringArrayValue struct { + value *[]string + changed bool +} + +func newStringArrayValue(val []string, p *[]string) *stringArrayValue { + ssv := new(stringArrayValue) + ssv.value = p + *ssv.value = val + return ssv +} + +func (s *stringArrayValue) Set(val string) error { + if !s.changed { + *s.value = []string{val} + s.changed = true + } else { + *s.value = append(*s.value, val) + } + return nil +} + +func (s *stringArrayValue) Append(val string) error { + *s.value = append(*s.value, val) + return nil +} + +func (s *stringArrayValue) Replace(val []string) error { + out := make([]string, len(val)) + for i, d := range val { + out[i] = d + } + *s.value = out + return nil +} + +func (s *stringArrayValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = d + } + return out +} + +func (s *stringArrayValue) Type() string { + return "stringArray" +} + +func (s *stringArrayValue) String() string { + str, _ := writeAsCSV(*s.value) + return "[" + str + "]" +} + +func stringArrayConv(sval string) (interface{}, error) { + sval = sval[1 : len(sval)-1] + // An empty string would cause a array with one (empty) string + if len(sval) == 0 { + return []string{}, nil + } + return readAsCSV(sval) +} + +// GetStringArray return the []string value of a flag with the given name +func (f *FlagSet) GetStringArray(name string) ([]string, error) { + val, err := f.getFlagType(name, "stringArray", stringArrayConv) + if err != nil { + return []string{}, err + } + return val.([]string), nil +} + +// StringArrayVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a []string variable in which to store the values of the multiple flags. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) { + f.VarP(newStringArrayValue(value, p), name, "", usage) +} + +// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { + f.VarP(newStringArrayValue(value, p), name, shorthand, usage) +} + +// StringArrayVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a []string variable in which to store the value of the flag. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func StringArrayVar(p *[]string, name string, value []string, usage string) { + CommandLine.VarP(newStringArrayValue(value, p), name, "", usage) +} + +// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash. +func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) { + CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, usage) +} + +// StringArray defines a string flag with specified name, default value, and usage string. +// The return value is the address of a []string variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string { + p := []string{} + f.StringArrayVarP(&p, name, "", value, usage) + return &p +} + +// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string { + p := []string{} + f.StringArrayVarP(&p, name, shorthand, value, usage) + return &p +} + +// StringArray defines a string flag with specified name, default value, and usage string. +// The return value is the address of a []string variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma. Use a StringSlice for that. +func StringArray(name string, value []string, usage string) *[]string { + return CommandLine.StringArrayP(name, "", value, usage) +} + +// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash. +func StringArrayP(name, shorthand string, value []string, usage string) *[]string { + return CommandLine.StringArrayP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go new file mode 100644 index 0000000..3cb2e69 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_slice.go @@ -0,0 +1,163 @@ +package pflag + +import ( + "bytes" + "encoding/csv" + "strings" +) + +// -- stringSlice Value +type stringSliceValue struct { + value *[]string + changed bool +} + +func newStringSliceValue(val []string, p *[]string) *stringSliceValue { + ssv := new(stringSliceValue) + ssv.value = p + *ssv.value = val + return ssv +} + +func readAsCSV(val string) ([]string, error) { + if val == "" { + return []string{}, nil + } + stringReader := strings.NewReader(val) + csvReader := csv.NewReader(stringReader) + return csvReader.Read() +} + +func writeAsCSV(vals []string) (string, error) { + b := &bytes.Buffer{} + w := csv.NewWriter(b) + err := w.Write(vals) + if err != nil { + return "", err + } + w.Flush() + return strings.TrimSuffix(b.String(), "\n"), nil +} + +func (s *stringSliceValue) Set(val string) error { + v, err := readAsCSV(val) + if err != nil { + return err + } + if !s.changed { + *s.value = v + } else { + *s.value = append(*s.value, v...) + } + s.changed = true + return nil +} + +func (s *stringSliceValue) Type() string { + return "stringSlice" +} + +func (s *stringSliceValue) String() string { + str, _ := writeAsCSV(*s.value) + return "[" + str + "]" +} + +func (s *stringSliceValue) Append(val string) error { + *s.value = append(*s.value, val) + return nil +} + +func (s *stringSliceValue) Replace(val []string) error { + *s.value = val + return nil +} + +func (s *stringSliceValue) GetSlice() []string { + return *s.value +} + +func stringSliceConv(sval string) (interface{}, error) { + sval = sval[1 : len(sval)-1] + // An empty string would cause a slice with one (empty) string + if len(sval) == 0 { + return []string{}, nil + } + return readAsCSV(sval) +} + +// GetStringSlice return the []string value of a flag with the given name +func (f *FlagSet) GetStringSlice(name string) ([]string, error) { + val, err := f.getFlagType(name, "stringSlice", stringSliceConv) + if err != nil { + return []string{}, err + } + return val.([]string), nil +} + +// StringSliceVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a []string variable in which to store the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" --ss="v3" +// will result in +// []string{"v1", "v2", "v3"} +func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) { + f.VarP(newStringSliceValue(value, p), name, "", usage) +} + +// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { + f.VarP(newStringSliceValue(value, p), name, shorthand, usage) +} + +// StringSliceVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a []string variable in which to store the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" --ss="v3" +// will result in +// []string{"v1", "v2", "v3"} +func StringSliceVar(p *[]string, name string, value []string, usage string) { + CommandLine.VarP(newStringSliceValue(value, p), name, "", usage) +} + +// StringSliceVarP is like StringSliceVar, but accepts a shorthand letter that can be used after a single dash. +func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage string) { + CommandLine.VarP(newStringSliceValue(value, p), name, shorthand, usage) +} + +// StringSlice defines a string flag with specified name, default value, and usage string. +// The return value is the address of a []string variable that stores the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" --ss="v3" +// will result in +// []string{"v1", "v2", "v3"} +func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string { + p := []string{} + f.StringSliceVarP(&p, name, "", value, usage) + return &p +} + +// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage string) *[]string { + p := []string{} + f.StringSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// StringSlice defines a string flag with specified name, default value, and usage string. +// The return value is the address of a []string variable that stores the value of the flag. +// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly. +// For example: +// --ss="v1,v2" --ss="v3" +// will result in +// []string{"v1", "v2", "v3"} +func StringSlice(name string, value []string, usage string) *[]string { + return CommandLine.StringSliceP(name, "", value, usage) +} + +// StringSliceP is like StringSlice, but accepts a shorthand letter that can be used after a single dash. +func StringSliceP(name, shorthand string, value []string, usage string) *[]string { + return CommandLine.StringSliceP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_to_int.go b/vendor/github.com/spf13/pflag/string_to_int.go new file mode 100644 index 0000000..5ceda39 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_to_int.go @@ -0,0 +1,149 @@ +package pflag + +import ( + "bytes" + "fmt" + "strconv" + "strings" +) + +// -- stringToInt Value +type stringToIntValue struct { + value *map[string]int + changed bool +} + +func newStringToIntValue(val map[string]int, p *map[string]int) *stringToIntValue { + ssv := new(stringToIntValue) + ssv.value = p + *ssv.value = val + return ssv +} + +// Format: a=1,b=2 +func (s *stringToIntValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make(map[string]int, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return fmt.Errorf("%s must be formatted as key=value", pair) + } + var err error + out[kv[0]], err = strconv.Atoi(kv[1]) + if err != nil { + return err + } + } + if !s.changed { + *s.value = out + } else { + for k, v := range out { + (*s.value)[k] = v + } + } + s.changed = true + return nil +} + +func (s *stringToIntValue) Type() string { + return "stringToInt" +} + +func (s *stringToIntValue) String() string { + var buf bytes.Buffer + i := 0 + for k, v := range *s.value { + if i > 0 { + buf.WriteRune(',') + } + buf.WriteString(k) + buf.WriteRune('=') + buf.WriteString(strconv.Itoa(v)) + i++ + } + return "[" + buf.String() + "]" +} + +func stringToIntConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // An empty string would cause an empty map + if len(val) == 0 { + return map[string]int{}, nil + } + ss := strings.Split(val, ",") + out := make(map[string]int, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return nil, fmt.Errorf("%s must be formatted as key=value", pair) + } + var err error + out[kv[0]], err = strconv.Atoi(kv[1]) + if err != nil { + return nil, err + } + } + return out, nil +} + +// GetStringToInt return the map[string]int value of a flag with the given name +func (f *FlagSet) GetStringToInt(name string) (map[string]int, error) { + val, err := f.getFlagType(name, "stringToInt", stringToIntConv) + if err != nil { + return map[string]int{}, err + } + return val.(map[string]int), nil +} + +// StringToIntVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a map[string]int variable in which to store the values of the multiple flags. +// The value of each argument will not try to be separated by comma +func (f *FlagSet) StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) { + f.VarP(newStringToIntValue(value, p), name, "", usage) +} + +// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) { + f.VarP(newStringToIntValue(value, p), name, shorthand, usage) +} + +// StringToIntVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a map[string]int variable in which to store the value of the flag. +// The value of each argument will not try to be separated by comma +func StringToIntVar(p *map[string]int, name string, value map[string]int, usage string) { + CommandLine.VarP(newStringToIntValue(value, p), name, "", usage) +} + +// StringToIntVarP is like StringToIntVar, but accepts a shorthand letter that can be used after a single dash. +func StringToIntVarP(p *map[string]int, name, shorthand string, value map[string]int, usage string) { + CommandLine.VarP(newStringToIntValue(value, p), name, shorthand, usage) +} + +// StringToInt defines a string flag with specified name, default value, and usage string. +// The return value is the address of a map[string]int variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma +func (f *FlagSet) StringToInt(name string, value map[string]int, usage string) *map[string]int { + p := map[string]int{} + f.StringToIntVarP(&p, name, "", value, usage) + return &p +} + +// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int { + p := map[string]int{} + f.StringToIntVarP(&p, name, shorthand, value, usage) + return &p +} + +// StringToInt defines a string flag with specified name, default value, and usage string. +// The return value is the address of a map[string]int variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma +func StringToInt(name string, value map[string]int, usage string) *map[string]int { + return CommandLine.StringToIntP(name, "", value, usage) +} + +// StringToIntP is like StringToInt, but accepts a shorthand letter that can be used after a single dash. +func StringToIntP(name, shorthand string, value map[string]int, usage string) *map[string]int { + return CommandLine.StringToIntP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_to_int64.go b/vendor/github.com/spf13/pflag/string_to_int64.go new file mode 100644 index 0000000..a807a04 --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_to_int64.go @@ -0,0 +1,149 @@ +package pflag + +import ( + "bytes" + "fmt" + "strconv" + "strings" +) + +// -- stringToInt64 Value +type stringToInt64Value struct { + value *map[string]int64 + changed bool +} + +func newStringToInt64Value(val map[string]int64, p *map[string]int64) *stringToInt64Value { + ssv := new(stringToInt64Value) + ssv.value = p + *ssv.value = val + return ssv +} + +// Format: a=1,b=2 +func (s *stringToInt64Value) Set(val string) error { + ss := strings.Split(val, ",") + out := make(map[string]int64, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return fmt.Errorf("%s must be formatted as key=value", pair) + } + var err error + out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64) + if err != nil { + return err + } + } + if !s.changed { + *s.value = out + } else { + for k, v := range out { + (*s.value)[k] = v + } + } + s.changed = true + return nil +} + +func (s *stringToInt64Value) Type() string { + return "stringToInt64" +} + +func (s *stringToInt64Value) String() string { + var buf bytes.Buffer + i := 0 + for k, v := range *s.value { + if i > 0 { + buf.WriteRune(',') + } + buf.WriteString(k) + buf.WriteRune('=') + buf.WriteString(strconv.FormatInt(v, 10)) + i++ + } + return "[" + buf.String() + "]" +} + +func stringToInt64Conv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // An empty string would cause an empty map + if len(val) == 0 { + return map[string]int64{}, nil + } + ss := strings.Split(val, ",") + out := make(map[string]int64, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return nil, fmt.Errorf("%s must be formatted as key=value", pair) + } + var err error + out[kv[0]], err = strconv.ParseInt(kv[1], 10, 64) + if err != nil { + return nil, err + } + } + return out, nil +} + +// GetStringToInt64 return the map[string]int64 value of a flag with the given name +func (f *FlagSet) GetStringToInt64(name string) (map[string]int64, error) { + val, err := f.getFlagType(name, "stringToInt64", stringToInt64Conv) + if err != nil { + return map[string]int64{}, err + } + return val.(map[string]int64), nil +} + +// StringToInt64Var defines a string flag with specified name, default value, and usage string. +// The argument p point64s to a map[string]int64 variable in which to store the values of the multiple flags. +// The value of each argument will not try to be separated by comma +func (f *FlagSet) StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) { + f.VarP(newStringToInt64Value(value, p), name, "", usage) +} + +// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) { + f.VarP(newStringToInt64Value(value, p), name, shorthand, usage) +} + +// StringToInt64Var defines a string flag with specified name, default value, and usage string. +// The argument p point64s to a map[string]int64 variable in which to store the value of the flag. +// The value of each argument will not try to be separated by comma +func StringToInt64Var(p *map[string]int64, name string, value map[string]int64, usage string) { + CommandLine.VarP(newStringToInt64Value(value, p), name, "", usage) +} + +// StringToInt64VarP is like StringToInt64Var, but accepts a shorthand letter that can be used after a single dash. +func StringToInt64VarP(p *map[string]int64, name, shorthand string, value map[string]int64, usage string) { + CommandLine.VarP(newStringToInt64Value(value, p), name, shorthand, usage) +} + +// StringToInt64 defines a string flag with specified name, default value, and usage string. +// The return value is the address of a map[string]int64 variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma +func (f *FlagSet) StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 { + p := map[string]int64{} + f.StringToInt64VarP(&p, name, "", value, usage) + return &p +} + +// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 { + p := map[string]int64{} + f.StringToInt64VarP(&p, name, shorthand, value, usage) + return &p +} + +// StringToInt64 defines a string flag with specified name, default value, and usage string. +// The return value is the address of a map[string]int64 variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma +func StringToInt64(name string, value map[string]int64, usage string) *map[string]int64 { + return CommandLine.StringToInt64P(name, "", value, usage) +} + +// StringToInt64P is like StringToInt64, but accepts a shorthand letter that can be used after a single dash. +func StringToInt64P(name, shorthand string, value map[string]int64, usage string) *map[string]int64 { + return CommandLine.StringToInt64P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/string_to_string.go b/vendor/github.com/spf13/pflag/string_to_string.go new file mode 100644 index 0000000..1d1e3bf --- /dev/null +++ b/vendor/github.com/spf13/pflag/string_to_string.go @@ -0,0 +1,168 @@ +package pflag + +import ( + "bytes" + "encoding/csv" + "fmt" + "sort" + "strings" +) + +// -- stringToString Value +type stringToStringValue struct { + value *map[string]string + changed bool +} + +func newStringToStringValue(val map[string]string, p *map[string]string) *stringToStringValue { + ssv := new(stringToStringValue) + ssv.value = p + *ssv.value = val + return ssv +} + +// Format: a=1,b=2 +func (s *stringToStringValue) Set(val string) error { + var ss []string + n := strings.Count(val, "=") + switch n { + case 0: + return fmt.Errorf("%s must be formatted as key=value", val) + case 1: + ss = append(ss, strings.Trim(val, `"`)) + default: + r := csv.NewReader(strings.NewReader(val)) + var err error + ss, err = r.Read() + if err != nil { + return err + } + } + + out := make(map[string]string, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return fmt.Errorf("%s must be formatted as key=value", pair) + } + out[kv[0]] = kv[1] + } + if !s.changed { + *s.value = out + } else { + for k, v := range out { + (*s.value)[k] = v + } + } + s.changed = true + return nil +} + +func (s *stringToStringValue) Type() string { + return "stringToString" +} + +func (s *stringToStringValue) String() string { + keys := make([]string, 0, len(*s.value)) + for k := range *s.value { + keys = append(keys, k) + } + sort.Strings(keys) + + records := make([]string, 0, len(*s.value)>>1) + for _, k := range keys { + v := (*s.value)[k] + records = append(records, k+"="+v) + } + + var buf bytes.Buffer + w := csv.NewWriter(&buf) + if err := w.Write(records); err != nil { + panic(err) + } + w.Flush() + return "[" + strings.TrimSpace(buf.String()) + "]" +} + +func stringToStringConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // An empty string would cause an empty map + if len(val) == 0 { + return map[string]string{}, nil + } + r := csv.NewReader(strings.NewReader(val)) + ss, err := r.Read() + if err != nil { + return nil, err + } + out := make(map[string]string, len(ss)) + for _, pair := range ss { + kv := strings.SplitN(pair, "=", 2) + if len(kv) != 2 { + return nil, fmt.Errorf("%s must be formatted as key=value", pair) + } + out[kv[0]] = kv[1] + } + return out, nil +} + +// GetStringToString return the map[string]string value of a flag with the given name +func (f *FlagSet) GetStringToString(name string) (map[string]string, error) { + val, err := f.getFlagType(name, "stringToString", stringToStringConv) + if err != nil { + return map[string]string{}, err + } + return val.(map[string]string), nil +} + +// StringToStringVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a map[string]string variable in which to store the values of the multiple flags. +// The value of each argument will not try to be separated by comma +func (f *FlagSet) StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) { + f.VarP(newStringToStringValue(value, p), name, "", usage) +} + +// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) { + f.VarP(newStringToStringValue(value, p), name, shorthand, usage) +} + +// StringToStringVar defines a string flag with specified name, default value, and usage string. +// The argument p points to a map[string]string variable in which to store the value of the flag. +// The value of each argument will not try to be separated by comma +func StringToStringVar(p *map[string]string, name string, value map[string]string, usage string) { + CommandLine.VarP(newStringToStringValue(value, p), name, "", usage) +} + +// StringToStringVarP is like StringToStringVar, but accepts a shorthand letter that can be used after a single dash. +func StringToStringVarP(p *map[string]string, name, shorthand string, value map[string]string, usage string) { + CommandLine.VarP(newStringToStringValue(value, p), name, shorthand, usage) +} + +// StringToString defines a string flag with specified name, default value, and usage string. +// The return value is the address of a map[string]string variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma +func (f *FlagSet) StringToString(name string, value map[string]string, usage string) *map[string]string { + p := map[string]string{} + f.StringToStringVarP(&p, name, "", value, usage) + return &p +} + +// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string { + p := map[string]string{} + f.StringToStringVarP(&p, name, shorthand, value, usage) + return &p +} + +// StringToString defines a string flag with specified name, default value, and usage string. +// The return value is the address of a map[string]string variable that stores the value of the flag. +// The value of each argument will not try to be separated by comma +func StringToString(name string, value map[string]string, usage string) *map[string]string { + return CommandLine.StringToStringP(name, "", value, usage) +} + +// StringToStringP is like StringToString, but accepts a shorthand letter that can be used after a single dash. +func StringToStringP(name, shorthand string, value map[string]string, usage string) *map[string]string { + return CommandLine.StringToStringP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/text.go b/vendor/github.com/spf13/pflag/text.go new file mode 100644 index 0000000..886d5a3 --- /dev/null +++ b/vendor/github.com/spf13/pflag/text.go @@ -0,0 +1,81 @@ +package pflag + +import ( + "encoding" + "fmt" + "reflect" +) + +// following is copied from go 1.23.4 flag.go +type textValue struct{ p encoding.TextUnmarshaler } + +func newTextValue(val encoding.TextMarshaler, p encoding.TextUnmarshaler) textValue { + ptrVal := reflect.ValueOf(p) + if ptrVal.Kind() != reflect.Ptr { + panic("variable value type must be a pointer") + } + defVal := reflect.ValueOf(val) + if defVal.Kind() == reflect.Ptr { + defVal = defVal.Elem() + } + if defVal.Type() != ptrVal.Type().Elem() { + panic(fmt.Sprintf("default type does not match variable type: %v != %v", defVal.Type(), ptrVal.Type().Elem())) + } + ptrVal.Elem().Set(defVal) + return textValue{p} +} + +func (v textValue) Set(s string) error { + return v.p.UnmarshalText([]byte(s)) +} + +func (v textValue) Get() interface{} { + return v.p +} + +func (v textValue) String() string { + if m, ok := v.p.(encoding.TextMarshaler); ok { + if b, err := m.MarshalText(); err == nil { + return string(b) + } + } + return "" +} + +//end of copy + +func (v textValue) Type() string { + return reflect.ValueOf(v.p).Type().Name() +} + +// GetText set out, which implements encoding.UnmarshalText, to the value of a flag with given name +func (f *FlagSet) GetText(name string, out encoding.TextUnmarshaler) error { + flag := f.Lookup(name) + if flag == nil { + return fmt.Errorf("flag accessed but not defined: %s", name) + } + if flag.Value.Type() != reflect.TypeOf(out).Name() { + return fmt.Errorf("trying to get %s value of flag of type %s", reflect.TypeOf(out).Name(), flag.Value.Type()) + } + return out.UnmarshalText([]byte(flag.Value.String())) +} + +// TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p. +func (f *FlagSet) TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) { + f.VarP(newTextValue(value, p), name, "", usage) +} + +// TextVarP is like TextVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) TextVarP(p encoding.TextUnmarshaler, name, shorthand string, value encoding.TextMarshaler, usage string) { + f.VarP(newTextValue(value, p), name, shorthand, usage) +} + +// TextVar defines a flag with a specified name, default value, and usage string. The argument p must be a pointer to a variable that will hold the value of the flag, and p must implement encoding.TextUnmarshaler. If the flag is used, the flag value will be passed to p's UnmarshalText method. The type of the default value must be the same as the type of p. +func TextVar(p encoding.TextUnmarshaler, name string, value encoding.TextMarshaler, usage string) { + CommandLine.VarP(newTextValue(value, p), name, "", usage) +} + +// TextVarP is like TextVar, but accepts a shorthand letter that can be used after a single dash. +func TextVarP(p encoding.TextUnmarshaler, name, shorthand string, value encoding.TextMarshaler, usage string) { + CommandLine.VarP(newTextValue(value, p), name, shorthand, usage) +} diff --git a/vendor/github.com/spf13/pflag/time.go b/vendor/github.com/spf13/pflag/time.go new file mode 100644 index 0000000..3dee424 --- /dev/null +++ b/vendor/github.com/spf13/pflag/time.go @@ -0,0 +1,124 @@ +package pflag + +import ( + "fmt" + "strings" + "time" +) + +// TimeValue adapts time.Time for use as a flag. +type timeValue struct { + *time.Time + formats []string +} + +func newTimeValue(val time.Time, p *time.Time, formats []string) *timeValue { + *p = val + return &timeValue{ + Time: p, + formats: formats, + } +} + +// Set time.Time value from string based on accepted formats. +func (d *timeValue) Set(s string) error { + s = strings.TrimSpace(s) + for _, f := range d.formats { + v, err := time.Parse(f, s) + if err != nil { + continue + } + *d.Time = v + return nil + } + + formatsString := "" + for i, f := range d.formats { + if i > 0 { + formatsString += ", " + } + formatsString += fmt.Sprintf("`%s`", f) + } + + return fmt.Errorf("invalid time format `%s` must be one of: %s", s, formatsString) +} + +// Type name for time.Time flags. +func (d *timeValue) Type() string { + return "time" +} + +func (d *timeValue) String() string { + if d.Time.IsZero() { + return "" + } else { + return d.Time.Format(time.RFC3339Nano) + } +} + +// GetTime return the time value of a flag with the given name +func (f *FlagSet) GetTime(name string) (time.Time, error) { + flag := f.Lookup(name) + if flag == nil { + err := fmt.Errorf("flag accessed but not defined: %s", name) + return time.Time{}, err + } + + if flag.Value.Type() != "time" { + err := fmt.Errorf("trying to get %s value of flag of type %s", "time", flag.Value.Type()) + return time.Time{}, err + } + + val, ok := flag.Value.(*timeValue) + if !ok { + return time.Time{}, fmt.Errorf("value %s is not a time", flag.Value) + } + + return *val.Time, nil +} + +// TimeVar defines a time.Time flag with specified name, default value, and usage string. +// The argument p points to a time.Time variable in which to store the value of the flag. +func (f *FlagSet) TimeVar(p *time.Time, name string, value time.Time, formats []string, usage string) { + f.TimeVarP(p, name, "", value, formats, usage) +} + +// TimeVarP is like TimeVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) TimeVarP(p *time.Time, name, shorthand string, value time.Time, formats []string, usage string) { + f.VarP(newTimeValue(value, p, formats), name, shorthand, usage) +} + +// TimeVar defines a time.Time flag with specified name, default value, and usage string. +// The argument p points to a time.Time variable in which to store the value of the flag. +func TimeVar(p *time.Time, name string, value time.Time, formats []string, usage string) { + CommandLine.TimeVarP(p, name, "", value, formats, usage) +} + +// TimeVarP is like TimeVar, but accepts a shorthand letter that can be used after a single dash. +func TimeVarP(p *time.Time, name, shorthand string, value time.Time, formats []string, usage string) { + CommandLine.VarP(newTimeValue(value, p, formats), name, shorthand, usage) +} + +// Time defines a time.Time flag with specified name, default value, and usage string. +// The return value is the address of a time.Time variable that stores the value of the flag. +func (f *FlagSet) Time(name string, value time.Time, formats []string, usage string) *time.Time { + return f.TimeP(name, "", value, formats, usage) +} + +// TimeP is like Time, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) TimeP(name, shorthand string, value time.Time, formats []string, usage string) *time.Time { + p := new(time.Time) + f.TimeVarP(p, name, shorthand, value, formats, usage) + return p +} + +// Time defines a time.Time flag with specified name, default value, and usage string. +// The return value is the address of a time.Time variable that stores the value of the flag. +func Time(name string, value time.Time, formats []string, usage string) *time.Time { + return CommandLine.TimeP(name, "", value, formats, usage) +} + +// TimeP is like Time, but accepts a shorthand letter that can be used after a single dash. +func TimeP(name, shorthand string, value time.Time, formats []string, usage string) *time.Time { + return CommandLine.TimeP(name, shorthand, value, formats, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint.go b/vendor/github.com/spf13/pflag/uint.go new file mode 100644 index 0000000..dcbc2b7 --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- uint Value +type uintValue uint + +func newUintValue(val uint, p *uint) *uintValue { + *p = val + return (*uintValue)(p) +} + +func (i *uintValue) Set(s string) error { + v, err := strconv.ParseUint(s, 0, 64) + *i = uintValue(v) + return err +} + +func (i *uintValue) Type() string { + return "uint" +} + +func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) } + +func uintConv(sval string) (interface{}, error) { + v, err := strconv.ParseUint(sval, 0, 0) + if err != nil { + return 0, err + } + return uint(v), nil +} + +// GetUint return the uint value of a flag with the given name +func (f *FlagSet) GetUint(name string) (uint, error) { + val, err := f.getFlagType(name, "uint", uintConv) + if err != nil { + return 0, err + } + return val.(uint), nil +} + +// UintVar defines a uint flag with specified name, default value, and usage string. +// The argument p points to a uint variable in which to store the value of the flag. +func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) { + f.VarP(newUintValue(value, p), name, "", usage) +} + +// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) { + f.VarP(newUintValue(value, p), name, shorthand, usage) +} + +// UintVar defines a uint flag with specified name, default value, and usage string. +// The argument p points to a uint variable in which to store the value of the flag. +func UintVar(p *uint, name string, value uint, usage string) { + CommandLine.VarP(newUintValue(value, p), name, "", usage) +} + +// UintVarP is like UintVar, but accepts a shorthand letter that can be used after a single dash. +func UintVarP(p *uint, name, shorthand string, value uint, usage string) { + CommandLine.VarP(newUintValue(value, p), name, shorthand, usage) +} + +// Uint defines a uint flag with specified name, default value, and usage string. +// The return value is the address of a uint variable that stores the value of the flag. +func (f *FlagSet) Uint(name string, value uint, usage string) *uint { + p := new(uint) + f.UintVarP(p, name, "", value, usage) + return p +} + +// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint { + p := new(uint) + f.UintVarP(p, name, shorthand, value, usage) + return p +} + +// Uint defines a uint flag with specified name, default value, and usage string. +// The return value is the address of a uint variable that stores the value of the flag. +func Uint(name string, value uint, usage string) *uint { + return CommandLine.UintP(name, "", value, usage) +} + +// UintP is like Uint, but accepts a shorthand letter that can be used after a single dash. +func UintP(name, shorthand string, value uint, usage string) *uint { + return CommandLine.UintP(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint16.go b/vendor/github.com/spf13/pflag/uint16.go new file mode 100644 index 0000000..7e9914e --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint16.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- uint16 value +type uint16Value uint16 + +func newUint16Value(val uint16, p *uint16) *uint16Value { + *p = val + return (*uint16Value)(p) +} + +func (i *uint16Value) Set(s string) error { + v, err := strconv.ParseUint(s, 0, 16) + *i = uint16Value(v) + return err +} + +func (i *uint16Value) Type() string { + return "uint16" +} + +func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + +func uint16Conv(sval string) (interface{}, error) { + v, err := strconv.ParseUint(sval, 0, 16) + if err != nil { + return 0, err + } + return uint16(v), nil +} + +// GetUint16 return the uint16 value of a flag with the given name +func (f *FlagSet) GetUint16(name string) (uint16, error) { + val, err := f.getFlagType(name, "uint16", uint16Conv) + if err != nil { + return 0, err + } + return val.(uint16), nil +} + +// Uint16Var defines a uint flag with specified name, default value, and usage string. +// The argument p points to a uint variable in which to store the value of the flag. +func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) { + f.VarP(newUint16Value(value, p), name, "", usage) +} + +// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { + f.VarP(newUint16Value(value, p), name, shorthand, usage) +} + +// Uint16Var defines a uint flag with specified name, default value, and usage string. +// The argument p points to a uint variable in which to store the value of the flag. +func Uint16Var(p *uint16, name string, value uint16, usage string) { + CommandLine.VarP(newUint16Value(value, p), name, "", usage) +} + +// Uint16VarP is like Uint16Var, but accepts a shorthand letter that can be used after a single dash. +func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) { + CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage) +} + +// Uint16 defines a uint flag with specified name, default value, and usage string. +// The return value is the address of a uint variable that stores the value of the flag. +func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 { + p := new(uint16) + f.Uint16VarP(p, name, "", value, usage) + return p +} + +// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 { + p := new(uint16) + f.Uint16VarP(p, name, shorthand, value, usage) + return p +} + +// Uint16 defines a uint flag with specified name, default value, and usage string. +// The return value is the address of a uint variable that stores the value of the flag. +func Uint16(name string, value uint16, usage string) *uint16 { + return CommandLine.Uint16P(name, "", value, usage) +} + +// Uint16P is like Uint16, but accepts a shorthand letter that can be used after a single dash. +func Uint16P(name, shorthand string, value uint16, usage string) *uint16 { + return CommandLine.Uint16P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint32.go b/vendor/github.com/spf13/pflag/uint32.go new file mode 100644 index 0000000..d802453 --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint32.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- uint32 value +type uint32Value uint32 + +func newUint32Value(val uint32, p *uint32) *uint32Value { + *p = val + return (*uint32Value)(p) +} + +func (i *uint32Value) Set(s string) error { + v, err := strconv.ParseUint(s, 0, 32) + *i = uint32Value(v) + return err +} + +func (i *uint32Value) Type() string { + return "uint32" +} + +func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + +func uint32Conv(sval string) (interface{}, error) { + v, err := strconv.ParseUint(sval, 0, 32) + if err != nil { + return 0, err + } + return uint32(v), nil +} + +// GetUint32 return the uint32 value of a flag with the given name +func (f *FlagSet) GetUint32(name string) (uint32, error) { + val, err := f.getFlagType(name, "uint32", uint32Conv) + if err != nil { + return 0, err + } + return val.(uint32), nil +} + +// Uint32Var defines a uint32 flag with specified name, default value, and usage string. +// The argument p points to a uint32 variable in which to store the value of the flag. +func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) { + f.VarP(newUint32Value(value, p), name, "", usage) +} + +// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { + f.VarP(newUint32Value(value, p), name, shorthand, usage) +} + +// Uint32Var defines a uint32 flag with specified name, default value, and usage string. +// The argument p points to a uint32 variable in which to store the value of the flag. +func Uint32Var(p *uint32, name string, value uint32, usage string) { + CommandLine.VarP(newUint32Value(value, p), name, "", usage) +} + +// Uint32VarP is like Uint32Var, but accepts a shorthand letter that can be used after a single dash. +func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) { + CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage) +} + +// Uint32 defines a uint32 flag with specified name, default value, and usage string. +// The return value is the address of a uint32 variable that stores the value of the flag. +func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 { + p := new(uint32) + f.Uint32VarP(p, name, "", value, usage) + return p +} + +// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 { + p := new(uint32) + f.Uint32VarP(p, name, shorthand, value, usage) + return p +} + +// Uint32 defines a uint32 flag with specified name, default value, and usage string. +// The return value is the address of a uint32 variable that stores the value of the flag. +func Uint32(name string, value uint32, usage string) *uint32 { + return CommandLine.Uint32P(name, "", value, usage) +} + +// Uint32P is like Uint32, but accepts a shorthand letter that can be used after a single dash. +func Uint32P(name, shorthand string, value uint32, usage string) *uint32 { + return CommandLine.Uint32P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint64.go b/vendor/github.com/spf13/pflag/uint64.go new file mode 100644 index 0000000..f62240f --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint64.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- uint64 Value +type uint64Value uint64 + +func newUint64Value(val uint64, p *uint64) *uint64Value { + *p = val + return (*uint64Value)(p) +} + +func (i *uint64Value) Set(s string) error { + v, err := strconv.ParseUint(s, 0, 64) + *i = uint64Value(v) + return err +} + +func (i *uint64Value) Type() string { + return "uint64" +} + +func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + +func uint64Conv(sval string) (interface{}, error) { + v, err := strconv.ParseUint(sval, 0, 64) + if err != nil { + return 0, err + } + return uint64(v), nil +} + +// GetUint64 return the uint64 value of a flag with the given name +func (f *FlagSet) GetUint64(name string) (uint64, error) { + val, err := f.getFlagType(name, "uint64", uint64Conv) + if err != nil { + return 0, err + } + return val.(uint64), nil +} + +// Uint64Var defines a uint64 flag with specified name, default value, and usage string. +// The argument p points to a uint64 variable in which to store the value of the flag. +func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) { + f.VarP(newUint64Value(value, p), name, "", usage) +} + +// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { + f.VarP(newUint64Value(value, p), name, shorthand, usage) +} + +// Uint64Var defines a uint64 flag with specified name, default value, and usage string. +// The argument p points to a uint64 variable in which to store the value of the flag. +func Uint64Var(p *uint64, name string, value uint64, usage string) { + CommandLine.VarP(newUint64Value(value, p), name, "", usage) +} + +// Uint64VarP is like Uint64Var, but accepts a shorthand letter that can be used after a single dash. +func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) { + CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage) +} + +// Uint64 defines a uint64 flag with specified name, default value, and usage string. +// The return value is the address of a uint64 variable that stores the value of the flag. +func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 { + p := new(uint64) + f.Uint64VarP(p, name, "", value, usage) + return p +} + +// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 { + p := new(uint64) + f.Uint64VarP(p, name, shorthand, value, usage) + return p +} + +// Uint64 defines a uint64 flag with specified name, default value, and usage string. +// The return value is the address of a uint64 variable that stores the value of the flag. +func Uint64(name string, value uint64, usage string) *uint64 { + return CommandLine.Uint64P(name, "", value, usage) +} + +// Uint64P is like Uint64, but accepts a shorthand letter that can be used after a single dash. +func Uint64P(name, shorthand string, value uint64, usage string) *uint64 { + return CommandLine.Uint64P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint8.go b/vendor/github.com/spf13/pflag/uint8.go new file mode 100644 index 0000000..bb0e83c --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint8.go @@ -0,0 +1,88 @@ +package pflag + +import "strconv" + +// -- uint8 Value +type uint8Value uint8 + +func newUint8Value(val uint8, p *uint8) *uint8Value { + *p = val + return (*uint8Value)(p) +} + +func (i *uint8Value) Set(s string) error { + v, err := strconv.ParseUint(s, 0, 8) + *i = uint8Value(v) + return err +} + +func (i *uint8Value) Type() string { + return "uint8" +} + +func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) } + +func uint8Conv(sval string) (interface{}, error) { + v, err := strconv.ParseUint(sval, 0, 8) + if err != nil { + return 0, err + } + return uint8(v), nil +} + +// GetUint8 return the uint8 value of a flag with the given name +func (f *FlagSet) GetUint8(name string) (uint8, error) { + val, err := f.getFlagType(name, "uint8", uint8Conv) + if err != nil { + return 0, err + } + return val.(uint8), nil +} + +// Uint8Var defines a uint8 flag with specified name, default value, and usage string. +// The argument p points to a uint8 variable in which to store the value of the flag. +func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) { + f.VarP(newUint8Value(value, p), name, "", usage) +} + +// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { + f.VarP(newUint8Value(value, p), name, shorthand, usage) +} + +// Uint8Var defines a uint8 flag with specified name, default value, and usage string. +// The argument p points to a uint8 variable in which to store the value of the flag. +func Uint8Var(p *uint8, name string, value uint8, usage string) { + CommandLine.VarP(newUint8Value(value, p), name, "", usage) +} + +// Uint8VarP is like Uint8Var, but accepts a shorthand letter that can be used after a single dash. +func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) { + CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage) +} + +// Uint8 defines a uint8 flag with specified name, default value, and usage string. +// The return value is the address of a uint8 variable that stores the value of the flag. +func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 { + p := new(uint8) + f.Uint8VarP(p, name, "", value, usage) + return p +} + +// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 { + p := new(uint8) + f.Uint8VarP(p, name, shorthand, value, usage) + return p +} + +// Uint8 defines a uint8 flag with specified name, default value, and usage string. +// The return value is the address of a uint8 variable that stores the value of the flag. +func Uint8(name string, value uint8, usage string) *uint8 { + return CommandLine.Uint8P(name, "", value, usage) +} + +// Uint8P is like Uint8, but accepts a shorthand letter that can be used after a single dash. +func Uint8P(name, shorthand string, value uint8, usage string) *uint8 { + return CommandLine.Uint8P(name, shorthand, value, usage) +} diff --git a/vendor/github.com/spf13/pflag/uint_slice.go b/vendor/github.com/spf13/pflag/uint_slice.go new file mode 100644 index 0000000..5fa9248 --- /dev/null +++ b/vendor/github.com/spf13/pflag/uint_slice.go @@ -0,0 +1,168 @@ +package pflag + +import ( + "fmt" + "strconv" + "strings" +) + +// -- uintSlice Value +type uintSliceValue struct { + value *[]uint + changed bool +} + +func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue { + uisv := new(uintSliceValue) + uisv.value = p + *uisv.value = val + return uisv +} + +func (s *uintSliceValue) Set(val string) error { + ss := strings.Split(val, ",") + out := make([]uint, len(ss)) + for i, d := range ss { + u, err := strconv.ParseUint(d, 10, 0) + if err != nil { + return err + } + out[i] = uint(u) + } + if !s.changed { + *s.value = out + } else { + *s.value = append(*s.value, out...) + } + s.changed = true + return nil +} + +func (s *uintSliceValue) Type() string { + return "uintSlice" +} + +func (s *uintSliceValue) String() string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = fmt.Sprintf("%d", d) + } + return "[" + strings.Join(out, ",") + "]" +} + +func (s *uintSliceValue) fromString(val string) (uint, error) { + t, err := strconv.ParseUint(val, 10, 0) + if err != nil { + return 0, err + } + return uint(t), nil +} + +func (s *uintSliceValue) toString(val uint) string { + return fmt.Sprintf("%d", val) +} + +func (s *uintSliceValue) Append(val string) error { + i, err := s.fromString(val) + if err != nil { + return err + } + *s.value = append(*s.value, i) + return nil +} + +func (s *uintSliceValue) Replace(val []string) error { + out := make([]uint, len(val)) + for i, d := range val { + var err error + out[i], err = s.fromString(d) + if err != nil { + return err + } + } + *s.value = out + return nil +} + +func (s *uintSliceValue) GetSlice() []string { + out := make([]string, len(*s.value)) + for i, d := range *s.value { + out[i] = s.toString(d) + } + return out +} + +func uintSliceConv(val string) (interface{}, error) { + val = strings.Trim(val, "[]") + // Empty string would cause a slice with one (empty) entry + if len(val) == 0 { + return []uint{}, nil + } + ss := strings.Split(val, ",") + out := make([]uint, len(ss)) + for i, d := range ss { + u, err := strconv.ParseUint(d, 10, 0) + if err != nil { + return nil, err + } + out[i] = uint(u) + } + return out, nil +} + +// GetUintSlice returns the []uint value of a flag with the given name. +func (f *FlagSet) GetUintSlice(name string) ([]uint, error) { + val, err := f.getFlagType(name, "uintSlice", uintSliceConv) + if err != nil { + return []uint{}, err + } + return val.([]uint), nil +} + +// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string. +// The argument p points to a []uint variable in which to store the value of the flag. +func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) { + f.VarP(newUintSliceValue(value, p), name, "", usage) +} + +// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { + f.VarP(newUintSliceValue(value, p), name, shorthand, usage) +} + +// UintSliceVar defines a uint[] flag with specified name, default value, and usage string. +// The argument p points to a uint[] variable in which to store the value of the flag. +func UintSliceVar(p *[]uint, name string, value []uint, usage string) { + CommandLine.VarP(newUintSliceValue(value, p), name, "", usage) +} + +// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash. +func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) { + CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage) +} + +// UintSlice defines a []uint flag with specified name, default value, and usage string. +// The return value is the address of a []uint variable that stores the value of the flag. +func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint { + p := []uint{} + f.UintSliceVarP(&p, name, "", value, usage) + return &p +} + +// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. +func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { + p := []uint{} + f.UintSliceVarP(&p, name, shorthand, value, usage) + return &p +} + +// UintSlice defines a []uint flag with specified name, default value, and usage string. +// The return value is the address of a []uint variable that stores the value of the flag. +func UintSlice(name string, value []uint, usage string) *[]uint { + return CommandLine.UintSliceP(name, "", value, usage) +} + +// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash. +func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint { + return CommandLine.UintSliceP(name, shorthand, value, usage) +} diff --git a/vendor/modules.txt b/vendor/modules.txt new file mode 100644 index 0000000..e978173 --- /dev/null +++ b/vendor/modules.txt @@ -0,0 +1,28 @@ +# github.com/dennwc/btrfs v0.0.0-20260222081608-edfb8b9e4f55 +## explicit; go 1.12 +github.com/dennwc/btrfs +github.com/dennwc/btrfs/mtab +# github.com/dennwc/ioctl v1.0.1-0.20181021180353-017804252068 +## explicit +github.com/dennwc/ioctl +# github.com/inconshreveable/mousetrap v1.1.0 +## explicit; go 1.18 +github.com/inconshreveable/mousetrap +# github.com/lib/pq v1.12.3 +## explicit; go 1.21 +github.com/lib/pq +github.com/lib/pq/internal/pgpass +github.com/lib/pq/internal/pgservice +github.com/lib/pq/internal/pqsql +github.com/lib/pq/internal/pqtime +github.com/lib/pq/internal/pqutil +github.com/lib/pq/internal/proto +github.com/lib/pq/oid +github.com/lib/pq/pqerror +github.com/lib/pq/scram +# github.com/spf13/cobra v1.10.2 +## explicit; go 1.15 +github.com/spf13/cobra +# github.com/spf13/pflag v1.0.9 +## explicit; go 1.12 +github.com/spf13/pflag